package cc.smtweb.biz.mztb.web.base.partyDataFill;

import cc.smtweb.biz.mztb.web.base.*;
import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.db.EntityHelper;
import cc.smtweb.framework.core.db.cache.DictsCache;
import cc.smtweb.framework.core.db.impl.DefaultEntity;
import cc.smtweb.framework.core.util.DateUtil;
import cc.smtweb.framework.core.util.StringUtil;
import cc.smtweb.system.bpm.web.engine.dynPage.DynRetBean;
import cc.smtweb.system.bpm.web.engine.model.common.ModelListHandler;
import cc.smtweb.system.bpm.web.engine.model.listcard.lcms.LCMsLoadHandler;
import cc.smtweb.system.bpm.web.engine.model.listcard.lcms.LCMsSaveHandler;
import cc.smtweb.system.bpm.web.sys.user.user.UserCache;

import java.util.List;
import java.util.Map;

public class PartyDataFillHandler {

    protected static FinanceInfo financeInfo;
    protected static YearEndPersons yearEndPersons;
    protected static BusinessInfo businessInfo;
//    protected static PartyInfo partyInfo;

    protected static final String YEAR_END_PERSONS_DS_NAME = "yearEndPersonsForm";
    protected static final String FINANCE_DS_NAME = "financeForm";
    protected static final String BUSINESS_DS_NAME = "businessForm";
//    protected static final String PARTY_DS_NAME = "partyForm";

    static class PartyDataFillModelSaveHandler extends LCMsSaveHandler<FillOut> {
        @Override
        public void readFromPage(SwMap pageData, SwMap filter) {
            super.readFromPage(pageData, filter);
            if(bean.getType() == 2) {
                yearEndPersons = readBeanFromPage(YEAR_END_PERSONS_DS_NAME, pageData, filter);// yearEndPersonsForm
            }
            financeInfo = readBeanFromPage(FINANCE_DS_NAME, pageData, filter);
            businessInfo = readBeanFromPage(BUSINESS_DS_NAME, pageData, filter);
//            partyInfo = readBeanFromPage(PARTY_DS_NAME, pageData, filter);
        }

        @Override
        public void doSave() {
            super.doSave();
            if(bean.getType() == 2) {
                saveBean(yearEndPersons);
            }
            saveBean(financeInfo);
            saveBean(businessInfo);
//            saveBean(partyInfo);
        }
    }

    static class PartyDataFillModelLoadHandler extends LCMsLoadHandler<FillOut> {
        @Override
        protected void localLoad(SwMap filter) {
            super.localLoad(filter);
            if(bean.getType() == 2) {
                loadViewBean(retMap,YEAR_END_PERSONS_DS_NAME,YearEndPersons.class," yep_fo_id = ?");
            }
            loadViewBean(retMap, FINANCE_DS_NAME,FinanceInfo.class," fi_fo_id = ?");
            loadViewBean(retMap, BUSINESS_DS_NAME,BusinessInfo.class," bi_fo_id = ?");
//            loadViewBean(retMap,filter, PARTY_DS_NAME,"");
        }

        // 自己处理页面数据加载
        private void loadViewBean(SwMap retMap,String dsName, Class entityClass, String sqlWhere) {
            Object o = DbEngine.getInstance().findDao(entityClass).queryEntityWhere(sqlWhere, bean.getId());
            retMap.put(dsName,o);
        }

        @Override
        protected void afterLoad(SwMap ret) {
            super.afterLoad(ret);
            Object card = ret.get("card");
            SwMap beanData = this.bean.getData();// fo_task
            ((DynRetBean) card).getForm().put("fo_task_text",beanData.readString("fo_task").contains("99")
                    ? beanData.readString("fo_task").replace("99","年")
                    : String.format("%d年%02d月",beanData.readLong("fo_task") / 100, beanData.readLong("fo_task") % 100));
            SwMap businessForm = ((DynRetBean) ret.get("businessForm")).getForm();
            businessForm.put("bi_type_text", DictsCache.getInstance().getItemName("tbBusinessType",businessForm.readString("bi_type")));
            businessForm.put("bi_property_text",DictsCache.getInstance().getItemName("tbNature",businessForm.readString("bi_property")));
            businessForm.put("bi_initiate_text",DictsCache.getInstance().getItemName("tbSubject",businessForm.readString("bi_initiate")));
            businessForm.put("bi_execute_regimen_text",DictsCache.getInstance().getItemName("tbKJZD",businessForm.readString("bi_execute_regimen")));
        }

        @Override
        protected void localAdd() {
            super.localAdd();
            bean.setDate(DateUtil.nowDateLong());
            bean.setPartyId(params.readLong("CUR_PARTY_ID"));
            bean.setUser(UserCache.getInstance().getNameById(us.getUserId()));
            DbEngine instance = DbEngine.getInstance();
            // 将机构表数据同步到填报主表机构信息中
            PartyInfo partyInfo = instance.queryEntity(PartyInfo.class, params.readLong("CUR_PARTY_ID"));
            SwMap partyInfoData = partyInfo.getData();
            partyInfoData.remove("pi_update_at");
            partyInfoData.remove("pi_sys_party_id");
            partyInfoData.remove("_def_table_name");
            SwMap partyInfoFillOutData = new SwMap();
            // 处理字段
            for (Map.Entry<String, Object> entry : partyInfoData.entrySet()) {
                partyInfoFillOutData.put("fo_"+entry.getKey(),partyInfoData.readString(entry.getKey()));
            }
            bean.getData().putAll(partyInfoFillOutData);

//            bean.setUser(us.getUserId());
            if(params.readString("outOldData").equals("1")) { // 如果带出上期数据,并且能找到最近的数据 就不执行初始化
                // 通过填报类型 已推送 找到当前机构最近填报的一条数据，
                int state  = params.readInt("type") == 1 ? 1 : 2;
                String foIdStr = instance.queryString("select fo_id from "
                        + EntityHelper.getSchemaTableName(FillOut.ENTITY_NAME)
                        + " where fo_type = ? and fo_state = 2 and fo_party_id=? order by fo_date desc limit 1",state,params.readLong("CUR_PARTY_ID"));
                // 查询 关联表的数据
                if(StringUtil.isEmpty(foIdStr)) { // 如果未找到同类型的填报数据 直接构建初始化数据
                    initPageDateset();
                    return;
                }
                long foId = Long.parseLong(foIdStr);
                // 将关联表数据返回到页面
                if(state == 2) {
                    yearEndPersons = addViewBean(retMap,YEAR_END_PERSONS_DS_NAME,new YearEndPersons(),foId," yep_fo_id = ? ");
                    yearEndPersons.setFoId(bean.getId());
                }
                financeInfo = addViewBean(retMap,FINANCE_DS_NAME, new FinanceInfo(),foId," fi_fo_id = ? ");
                financeInfo.setFoId(bean.getId());
                businessInfo = addViewBean(retMap,BUSINESS_DS_NAME,new BusinessInfo(), foId," bi_fo_id = ? ");
                businessInfo.setFoId(bean.getId());
                // 页面下拉字段转换
                businessInfo.getData().put("bi_type_text",DictsCache.getInstance().getItemName("tbBusinessType",businessInfo.getType()));
                businessInfo.getData().put("bi_property_text",DictsCache.getInstance().getItemName("tbNature",businessInfo.getProperty()));
                businessInfo.getData().put("bi_initiate_text",DictsCache.getInstance().getItemName("tbSubject",businessInfo.getInitiate()));
                businessInfo.getData().put("bi_execute_regimen_text",DictsCache.getInstance().getItemName("tbKJZD",businessInfo.getExecuteRegimen()));
                return;
            }
            initPageDateset();
        }

        private void initPageDateset() {
            if(params.readInt("type") == 2) {
                yearEndPersons = addBean(YEAR_END_PERSONS_DS_NAME, true);
                yearEndPersons.setFoId(bean.getId());
            }
            financeInfo = addBean(FINANCE_DS_NAME, true);
            financeInfo.setFoId(bean.getId());
            businessInfo = addBean(BUSINESS_DS_NAME, true);
            businessInfo.setFoId(bean.getId());
        }

        // 选择带出数据时，自己构建初始化数据
        protected   <E extends DefaultEntity> E addViewBean(SwMap retMap,String dsName,E cla ,long id,String whereSql) {
            DefaultEntity entity = DbEngine.getInstance().findDao(cla.getClass()).queryEntityWhere(whereSql,id);
            entity.setEntityId(DbEngine.getInstance().nextId());
            entity.setIsNew(true);
            retMap.put(dsName,entity);
            return (E) entity;
        }

    }



    public static class PartyDataFillModelListHandler extends ModelListHandler {
        @Override
        protected void afterQuery(List<SwMap> listData) {
            listData.forEach(temp -> {
                int anInt = temp.readInt("fo_type");
                temp.put("fo_type_text",anInt == 1 ? "月报": "年报");
                temp.put("fo_task_text",temp.readString("fo_task").contains("99") ? temp.readString("fo_task").replace("99","年（年报）")
                        : String.format("%d年%02d月 （月报）",temp.readLong("fo_task") / 100, temp.readLong("fo_task") % 100));
                temp.put("fo_state_text",temp.readInt("fo_state") == 0 ? "待确认" : temp.readInt("fo_state") == 1 ? "已确认" : "已推送");
            });
        }
    }
}
