package cn.ibizlab.codegen.model;

import cn.ibizlab.codegen.utils.Inflector;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import net.ibizsys.model.app.dataentity.IPSAppDataEntity;

import java.util.*;
import java.util.stream.Collectors;

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

    public AppEntityModel(AppModel appModel,IPSAppDataEntity appDataEntity)
    {
        this.opt=appDataEntity;
        this.app=appModel;
        this.setCodeName(appDataEntity.getCodeName());
        this.setName(appDataEntity.getName());
        this.setId(String.format("%1$s-%2$s",app.getCodeName(),appDataEntity.getCodeName()));

        // 初始化应用实体资源数据
        if(getAppDataEntity().getMinorPSAppDERSs() != null){
            // 遍历多个主从关系
            getAppDataEntity().getMinorPSAppDERSs().forEach(appDERS ->{
                JSONObject appEntityResource = new JSONObject();
                String majorCodeName = appDERS.getMajorPSAppDataEntity().getCodeName();
                String minorCodeName = appDERS.getMinorPSAppDataEntity().getCodeName();
                String path = String.format("%1$s/:%2$s?/%3$s/:%4$s?", Inflector.getInstance().pluralize(majorCodeName),majorCodeName,Inflector.getInstance().pluralize(minorCodeName),minorCodeName).toLowerCase();
                appEntityResource.put("majorCodeName",majorCodeName.toLowerCase());
                appEntityResource.put("curCodeName",minorCodeName.toLowerCase());
                appEntityResource.put("path",path);
                // 实体关系路径集合
                List deResPaths = new JSONArray();
                // 主关系路径节点
                JSONObject majorResNode = new JSONObject();
                majorResNode.put("pathName", Inflector.getInstance().pluralize(majorCodeName).toLowerCase());
                majorResNode.put("parameterName", majorCodeName.toLowerCase());
                deResPaths.add(majorResNode);
                // 从关系路径节点
                JSONObject minorResNode = new JSONObject();
                minorResNode.put("pathName", Inflector.getInstance().pluralize(minorCodeName).toLowerCase());
                minorResNode.put("parameterName", minorCodeName.toLowerCase());
                deResPaths.add(minorResNode);
                appEntityResource.put("deResPaths", deResPaths);
                appEntityResources.add(appEntityResource);
            });
        }
        // 本身路径
        JSONObject appEntityResource = new JSONObject();
        appEntityResource.put("curCodeName",appDataEntity.getCodeName().toLowerCase());
        appEntityResource.put("path",String.format("%1$s/:%2$s?",Inflector.getInstance().pluralize(appDataEntity.getCodeName()),appDataEntity.getCodeName()).toLowerCase());
        // 路由关系路径集合
        List deResPaths = new JSONArray();
        // 实体本身关系路径节点
        JSONObject curResNode = new JSONObject();
        curResNode.put("pathName", Inflector.getInstance().pluralize(appDataEntity.getCodeName()).toLowerCase());
        curResNode.put("parameterName", appDataEntity.getCodeName().toLowerCase());
        deResPaths.add(curResNode);
        appEntityResource.put("deResPaths", deResPaths);
        appEntityResource.put("deResPathsString", deResPaths.toString());
        appEntityResources.add(appEntityResource);

        // 初始化界面行为
        try {
            keyField = getAppDataEntity().getPSDataEntity().getKeyPSDEField().getCodeName();
            majorField = getAppDataEntity().getPSDataEntity().getMajorPSDEField().getCodeName();
        }catch (Exception e){


        }
        if(getAppDataEntity().getAllPSAppDEUIActions() != null){
            getAppDataEntity().getAllPSAppDEUIActions().forEach(appDEUIAction ->{
                JSONObject actionJson = new JSONObject();
                actionJson.put("codeName",appDEUIAction.getCodeName());
                actionJson.put("uIActionTag",appDEUIAction.getUIActionTag());
                actionJson.put("UIActionMode",appDEUIAction.getUIActionMode());
                actionJson.put("actionTarget",appDEUIAction.getActionTarget());
                actionJson.put("caption",appDEUIAction.getCaption());
                actionJson.put("frontProcessType",appDEUIAction.getFrontProcessType());
                actionJson.put("htmlPageUrl",appDEUIAction.getHtmlPageUrl());
                actionJson.put("refreshMode",appDEUIAction.getRefreshMode());
                actionJson.put("uILogicAttachMode",appDEUIAction.getUILogicAttachMode());
                StringBuffer navContexts = new StringBuffer();
                navContexts.append("{");
                if(appDEUIAction.getPSNavigateContexts() != null){
                    appDEUIAction.getPSNavigateContexts().forEach(context ->{
                        navContexts.append(context.getName().toLowerCase() + ":'"+(context.isRawValue()?"":"%") +context.getValue()+(context.isRawValue()?"":"%")+"',");
                    });
                }
                navContexts.append("}");
                actionJson.put("navContexts",navContexts);
                StringBuffer navParams = new StringBuffer();
                navParams.append("{");
                if(appDEUIAction.getPSNavigateParams() != null){
                    appDEUIAction.getPSNavigateParams().forEach(param ->{
                        navParams.append(param.getName().toLowerCase() + ":'"+(param.isRawValue()?"":"%")+param.getValue()+(param.isRawValue()?"":"%")+"',");
                    });
                }
                navParams.append("}");
                actionJson.put("navParams",navParams);
                if(appDEUIAction.getPSAppDEMethod() != null){
                    actionJson.put("methodCodeName",appDEUIAction.getPSAppDEMethod().getCodeName());
                }
//                后续行为标识拿不到
//                if(appDEUIAction.getNextPSUIAction() != null){
//                    actionJson.put("nextActionCodeName",appDEUIAction.getNextPSUIAction().getCodeName());
//                }
                if(appDEUIAction.getFrontPSAppView() != null){
                    actionJson.put("frontPSAppView", appDEUIAction.getFrontPSAppView().getCodeName());
                }
                appDEUIActions.add(actionJson);
            });
        }
    }
    // 主键属性名称
    public String keyField = "";
    // 主信息属性名称
    public String majorField = "";

    public IPSAppDataEntity getAppDataEntity()
    {
        return (IPSAppDataEntity)opt;
    }

    private AppModel app;

    public Map<String,CtrlModel> ctrlsMap=new LinkedHashMap();

    public AppEntityModel addCtrl(String codeName,CtrlModel ctrlModel)
    {
        if(!ctrlsMap.containsKey(codeName))
            ctrlsMap.put(codeName,ctrlModel);
        return this;
    }

    private EntityModel entity;
    public EntityModel getEntity()
    {
        if(entity==null)
        {
            if(getAppDataEntity().getPSDataEntity()==null)
                entity = app.getSystem().getEntity(getAppDataEntity().getCodeName());
            else
                entity = app.getSystem().getEntity(getAppDataEntity().getPSDataEntity().getCodeName());
        }
        return entity;
    }

    private String serviceId;

    public String getServiceId()
    {
        if(serviceId==null)
        {
            String sybSysServiceType="DEFAULT";
            if(getEntity().getDataEntity().getPSSubSysServiceAPI()!=null)
                sybSysServiceType=getEntity().getDataEntity().getPSSubSysServiceAPI().getServiceType();
            if(getEntity().getDataEntity().getStorageMode()==4 && (!"MIDDLEPLATFORM".equals(sybSysServiceType)) && (!"MASA".equals(sybSysServiceType)))
                serviceId = getEntity().getDataEntity().getPSSubSysServiceAPI().getServiceCodeName();
            else if (getAppDataEntity().getPSSysServiceAPI()!=null)
                serviceId = app.getSystem().getDeploySysId().toLowerCase()+"-"+ getAppDataEntity().getPSSysServiceAPI().getCodeName().toLowerCase();
        }
        return serviceId;
    }

    public String getRefServiceId() {
        if (getServiceId() != null)
        {
            return "${ibiz.ref.service."+serviceId+":"+serviceId+"}";
        }
        return null;
    }

    public Collection<CtrlModel> getCtrls()
    {
        return ctrlsMap.values();
    }

    /**
     * 应用实体资源数据
     */
    private List<JSONObject> appEntityResources =new ArrayList<>();

    /**
     * 实体界面行为集合
     */
    public List<JSONObject> appDEUIActions = new ArrayList<>();

    public Collection<CtrlModel> getForms() {
        return ctrlsMap.values().stream().filter(item->item.getControl().getControlType().equals("FORM")).collect(Collectors.toList());
    }

}
