package cn.ibizlab.codegen.model;

import cn.ibizlab.codegen.utils.StringAdvUtils;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import net.ibizsys.model.app.dataentity.IPSAppDEField;
import net.ibizsys.model.control.IPSEditor;
import net.ibizsys.model.control.editor.*;
import net.ibizsys.model.control.form.IPSDEFDCatGroupLogic;
import net.ibizsys.model.control.form.IPSDEForm;
import net.ibizsys.model.control.form.IPSDEFormItem;
import net.ibizsys.model.dataentity.service.IPSDEMethodDTOField;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
public class VoFieldModel extends BaseModel {

    private CtrlModel voModel;

    private PropType type ;

    public VoFieldModel(CtrlModel voModel, IPSDEFormItem formItem) {
        this.opt = formItem;
        this.voModel = voModel;
        this.setCodeName(StringUtils.isEmpty(formItem.getCodeName())?formItem.getName():formItem.getCodeName());
        this.setName(formItem.getName());
    }


    private int position;

    public IPSDEFormItem getPSDEFormItem() {
        return (IPSDEFormItem) opt;
    }

    public IPSEditor getPSEditor() {
        return getPSDEFormItem().getPSEditor();
    }

    public String getEditorType()
    {
        if(getPSDEFormItem().getPSEditor()!=null) {
            return getPSDEFormItem().getPSEditor().getEditorType();
        }
        return null;
    }

    public IPSDEForm getPSDEForm()
    {
        return (IPSDEForm)getVoModel().getControl();
    }

    private FieldModel appDEField;
    public FieldModel getAppDEField() {
        if(appDEField==null) {
            appDEField=getVoModel().getAppEntity().getEntity().getFieldMap().get(this.getName().toUpperCase());
        }
        return appDEField;
    }

    public PropType getType() {
        if(type==null) {
            type = PropType.findType(this.getPSDEFormItem().getDataType());
            if(type.equals(PropType.VARCHAR)&&this.getPSEditor()!=null&&this.getPSEditor() instanceof IPSDatePicker)
            {
                IPSDatePicker datePicker=(IPSDatePicker)this.getPSEditor();
                if("YYYY-MM-DD".equalsIgnoreCase(datePicker.getDateTimeFormat()))
                    type=PropType.DATE;
                else if(!StringUtils.isEmpty(datePicker.getDateTimeFormat()) && datePicker.getDateTimeFormat().toUpperCase().startsWith("HH"))
                    type=PropType.TIME;
                else
                    type=PropType.DATETIME;
            }
        }
        return type;
    }


    private String logicName;
    public String getLogicName() {
        if(logicName==null)
        {
            logicName=this.getPSDEFormItem().getCaption();

            if (StringUtils.isEmpty(logicName)&&this.getPSEditor()!=null) {
                logicName=this.getPSEditor().getLogicName();
            }
            if (StringUtils.isEmpty(logicName)&&this.getAppDEField()!=null) {
                logicName=this.getAppDEField().getLogicName();
            }

        }

        return logicName;
    }

    private String javaType;

    private boolean singleFile=false;

    private String fileExt;

    private boolean fileList=false;

    private boolean singleDict=false;

    private boolean dictList=false;

    public String getJavaType()
    {
        if(javaType==null)
        {
            javaType=getType().getJava();
            if(this.getDict()!=null) {
                javaType = StringAdvUtils.pascalcase(this.getDictCodeName())+"Dict";
                if(!singleSelect) {
                    javaType = javaType + ".LIST";
                    formatShape="STRING";
                    serializeUsing="com.alibaba.fastjson.serializer.ToStringSerializer.class";
                    dictList=true;
                }
                else {
                    javaType = javaType + ".ENUM";
                    if("Integer".equals(getType().getJava()))
                        formatShape="NUMBER";
                    else
                        formatShape="STRING";
                    singleDict=true;
                }
            }
            else if(this.getPSEditor()!=null&&(this.getPSDEFormItem() instanceof IPSFileUploader||"FILEUPLOADER".equals(this.getPSEditor().getEditorType())))
            {
                javaType = "FileListDto";
                serializeUsing="com.alibaba.fastjson.serializer.ToStringSerializer.class";
                fileList=true;
            }
            else if(this.getPSEditor()!=null&&("zp".equals(this.getPSEditor().getEditorStyle())))
            {
                javaType = "FileDto";
                serializeUsing="com.alibaba.fastjson.serializer.ToStringSerializer.class";
                singleFile=true;
                fileExt=".png";
            }
            else if(this.getPSEditor()!=null&&("hfh".equals(this.getPSEditor().getEditorStyle())))
            {
                javaType = "FileDto";
                serializeUsing="com.alibaba.fastjson.serializer.ToStringSerializer.class";
                singleFile=true;
                fileExt=".doc";
            }
        }
        return javaType;
    }

    private String serializeUsing;
    public String getSerializeUsing()
    {
        if(serializeUsing==null)
        {
            serializeUsing="";
            getJavaType();
        }
        return serializeUsing;
    }
    private String formatShape;
    public String getFormatShape(){
        if(formatShape==null)
        {
            formatShape="";
            getJavaType();
        }
        return formatShape;
    }

    private String dictCodeName;
    private boolean singleSelect = true;
    private Catalog dict;

    public Catalog getDict() {
        if(dictCodeName==null) {
            dictCodeName = "";
            if(getPSEditor()!=null&&getPSEditor() instanceof IPSCodeListEditor) {
                IPSCodeListEditor codeListEditor=(IPSCodeListEditor)getPSDEFormItem().getPSEditor();
                if(codeListEditor.getPSAppCodeList()!=null) {
                    dictCodeName = codeListEditor.getPSAppCodeList().getCodeName();
                    dict=this.getVoModel().getApp().getDictMaps().get(dictCodeName);
                    if(dict==null)
                    {
                        dictCodeName="";
                    }
                    if ("treempick".equalsIgnoreCase(codeListEditor.getEditorType())||codeListEditor instanceof IPSMDropDownList
                        ||codeListEditor instanceof IPSCheckBoxList)
                        singleSelect=false;
                }
            }
        }
        return dict;
    }

    private String format;
    private String timeType;

    public String getTimeType()
    {
        getFormat();
        return timeType;
    }

    public String getFormat(){
        if(format==null)
        {
            format="";
            if("Timestamp".equals(getType().getJava()))
            {
                if(this.getPSDEFormItem().getDataType()==PropType.DATE.getCode()||"%1$tY-%1$tm-%1$td".equalsIgnoreCase(this.getPSDEFormItem().getValueFormat())||type.equals(PropType.DATE)){
                    timeType="DATE";
                    format = "yyyy-MM-dd";
                }
                else if(this.getPSDEFormItem().getDataType()==PropType.TIME.getCode()||"%1$tH:%1$tM:%1$tS".equalsIgnoreCase(this.getPSDEFormItem().getValueFormat())||type.equals(PropType.TIME)){
                    timeType="TIME";
                    format = "HH:mm:ss";
                }
                else{
                    timeType="DATETIME";
                    format = "yyyy-MM-dd HH:mm:ss";
                }
            }
        }

        return format;
    }

    public String getJsonName() {
        return getCodeName().toLowerCase();
    }

    public boolean isRequired() {
        if(!getPSDEFormItem().isAllowEmpty())
        {
            if(!ObjectUtils.isEmpty(getPSDEFormItem().getPSDEFDGroupLogics())) {
                for(IPSDEFDCatGroupLogic logic:getPSDEFormItem().getPSDEFDGroupLogics())
                    if("ITEMBLANK".equalsIgnoreCase(logic.getLogicCat()))
                        return false;
            }
            return true;
        }
        return false;
    }

    public String getCreateDefaultValue()
    {
        String dv="";
        if(!ObjectUtils.isEmpty(this.getPSDEFormItem().getCreateDV())) {
            if(ObjectUtils.isEmpty(this.getPSDEFormItem().getCreateDVT()))
                dv=this.getPSDEFormItem().getCreateDV();
        }
        return getDefaultValue(dv);
    }
    public String getUpdateDefaultValue()
    {
        String dv="";
        if(ObjectUtils.isEmpty(dv)) {
            if(!ObjectUtils.isEmpty(this.getPSDEFormItem().getUpdateDV())) {
                if(ObjectUtils.isEmpty(this.getPSDEFormItem().getUpdateDVT()))
                    dv=this.getPSDEFormItem().getUpdateDV();
            }
        }
        return getDefaultValue(dv);
    }

    public String getDefaultValue() {
        String dv=getCreateDefaultValue();
        if (ObjectUtils.isEmpty(dv)) {
            dv=getUpdateDefaultValue();
        }
        return dv;
    }
    public String getDefaultValue(String dv) {
        if(!ObjectUtils.isEmpty(dv)) {
            if (this.getDict() != null ) {
                dv = StringAdvUtils.pascalcase(dictCodeName) + "Dict.ENUM.V_" + dv.replace("(", "").replace(")", "")
                        .replace("（", "").replace("）", "")
                        .replace(":", "").replace("：", "")
                        .replace("、", "").replace(".", "")
                        .replace("。", "").replace(";", "")
                        .replace("；", "").replace("-", "")
                        .replace(",", "").replace("\\", "")
                        .replace("/", "").replace("，", "").replace("%","");
                if(!this.isSingleSelect())
                    return "";
            }
            else if(getType().isString())
                dv = "\""+dv+"\"";
        }
        return dv;
    }

    private String example;

    public String getExample() {
        if(example==null) {
            example = "";
            String dv="";
            if(!ObjectUtils.isEmpty(this.getPSDEFormItem().getCreateDV())) {
                if(ObjectUtils.isEmpty(this.getPSDEFormItem().getCreateDVT()))
                    dv=this.getPSDEFormItem().getCreateDV();
            }
            if(ObjectUtils.isEmpty(dv)) {
                if(!ObjectUtils.isEmpty(this.getPSDEFormItem().getUpdateDV())) {
                    if(ObjectUtils.isEmpty(this.getPSDEFormItem().getUpdateDVT()))
                        dv=this.getPSDEFormItem().getUpdateDV();
                }
            }
            if(!StringUtils.isEmpty(dv))
                example=dv.replace("\"","");
            else if (this.getDict() != null && !ObjectUtils.isEmpty(this.getDict().getOptions()))
            {
                example = this.getDict().getOptions().get(0).getValue().toString();
                if(!this.isSingleSelect()&&this.getDict().getOptions().size()>1)
                {
                    example+=this.getDict().getCodeList().getValueSeparator()==null?";":this.getDict().getCodeList().getValueSeparator();
                    example+= this.getDict().getOptions().get(1).getValue().toString();
                }
            }
        }

        return example;
    }

    private String columnName;

    public String getColumnName() {
        if(columnName==null) {
            columnName = "";
            if(getAppDEField()!=null) {
                if(appDEField.isPhisicalDEField())
                    columnName="["+appDEField.getEntity().getTableName()+"."+appDEField.getColumnName().toUpperCase()+"]";
                else if(appDEField.getDataEntityField().getDEFType()==5)
                    columnName="[TYYW_KG_XFJSDJZJB."+appDEField.getColumnName().toUpperCase()+"]";
                else if(!ObjectUtils.isEmpty(appDEField.getRefFieldName()))
                {
                    columnName="["+appDEField.getReference().getTableName()+"."+appDEField.getRefFieldName().toUpperCase()+"]";
                }
            }
        }
        return columnName;
    }

}
