package nckd.jxccl.sit.hcsi.formplugin.web.file.attach;

import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.entity.datamodel.AbstractFormDataModel;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.TableValueSetter;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.sit.hcsi.business.file.attach.AdjustSIBaseService;
import nckd.jxccl.sit.hcsi.common.constant.SitConstant;

import java.util.*;

/**
 * 动态表单插件
 */
public class AdjustSIBaseFormPlugin extends AbstractFormPlugin implements Plugin {

    private static Map<String, String> fieldMap = new HashMap<String, String>();
    static {
        fieldMap.put("nckd_welfaretype","welfaretype");
        fieldMap.put("nckd_paybaseofemployee","paybaseofemployee");
        fieldMap.put("nckd_paybaseofcompany","paybaseofcompany");
        fieldMap.put("nckd_startdate","startdate");
        fieldMap.put("nckd_enddate","enddate");
        fieldMap.put("nckd_description","description");
        fieldMap.put("nckd_sinsurdimension","nckd_sinsurdimension");
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate formOperate = (FormOperate)args.getSource();
        String opKey = formOperate.getOperateKey();
        switch (opKey) {
            case "donothing_query":
                queryVerify(args);
                break;
            case "donothing_adjust":
                adjustVerify(args);
                break;
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        super.afterDoOperation(afterDoOperationEventArgs);
        String opKey = afterDoOperationEventArgs.getOperateKey();
        switch(opKey) {
            case "donothing_query":
                doQuery();
                break;
            case "donothing_adjust":
                if(afterDoOperationEventArgs.getOperationResult().isSuccess()) {
                    doAdjust();
                }
        }
    }

    /**
     * 执行查询方法
     */
    public void doQuery() {
        IDataModel model = this.getModel();
        DynamicObject dyn = model.getDataEntity(true);
        DynamicObject welfarePayer = dyn.getDynamicObject("nckd_welfarepayer");
        Date year = dyn.getDate("nckd_year");
        // 删除分录
        this.getModel().deleteEntryData("nckd_entryentity");

        AdjustSIBaseService service = new AdjustSIBaseService(welfarePayer, year);
        DataSet dataSet = service.query();
        handleData(dataSet);
    }

    public void handleData(DataSet dataSet) {
        TableValueSetter setter = new TableValueSetter();
        int rowIndex = 0;
        AbstractFormDataModel model = (AbstractFormDataModel) this.getModel();
        while(dataSet.hasNext()) {
            Row rowData = dataSet.next();
            setter.set("nckd_sinsurfile", rowData.getLong("sinsurfileId"), rowIndex);
            setter.set("nckd_employee", rowData.getLong("employeeId"), rowIndex);
            setter.set("nckd_welfaretype", rowData.getLong("welfaretypeId"), rowIndex);
            setter.set("nckd_yearamount", rowData.getBigDecimal("totalamount"), rowIndex);
            setter.set("nckd_paybaseofemployee", rowData.getBigDecimal("paybaseofemployee"), rowIndex);
            setter.set("nckd_paybaseofcompany", rowData.getBigDecimal("paybaseofcompany"), rowIndex);
            setter.set("nckd_sinsurdimension", rowData.getLong("sinsurdimensionId"), rowIndex);
            rowIndex++;
        }
        model.beginInit();
        model.batchCreateNewEntryRow("nckd_entryentity", setter);
        model.endInit();
        this.getView().updateView("nckd_entryentity");
    }

    /**
     * 执行调整方法
     */
    public void doAdjust() {
        IDataModel model = this.getModel();
        DynamicObject dyn = model.getDataEntity(true);
        DynamicObjectCollection entryCols = dyn.getDynamicObjectCollection("nckd_entryentity");
        if(entryCols.size() > 0) {
            DynamicObjectCollection sibaseCols = new DynamicObjectCollection();
            for(DynamicObject entry : entryCols) {
                DynamicObject bill = BusinessDataServiceHelper.newDynamicObject(SitConstant.SIBASE_HELPER.getEntityName());
                bill.set("welfarepayer", dyn.getDynamicObject("nckd_welfarepayer"));
                bill.set("welfaretype", entry.getDynamicObject("nckd_welfaretype"));
                bill.set("sinsurfile", entry.getDynamicObject("nckd_sinsurfile"));
                bill.set("employee", entry.getDynamicObject("nckd_employee"));
                bill.set("insured", true);
                bill.set("startdate", entry.getDate("nckd_effectdate"));
                bill.set("enddate", entry.getDate("nckd_effectdate"));
                bill.set("nckd_sinsurdimension", entry.getDynamicObject("nckd_sinsurdimension"));
                bill.set("paybaseofemployee", entry.getBigDecimal("nckd_yearamount"));
                bill.set("paybaseofcompany", entry.getBigDecimal("nckd_yearamount"));
                //bill.set("id", Uuid.create());
                sibaseCols.add(bill);
            }
            OperationResult result = SaveServiceHelper.saveOperate(SitConstant.SIBASE_HELPER.getEntityName(), sibaseCols.stream().toArray(DynamicObject[]::new), OperateOption.create());
            if(result.isSuccess()) {
                this.getView().showTipNotification("调整成功！",3000);
            }
            else {
                this.getView().showMessage("调整出错：" + result.getMessage());
            }
        }
    }

    /**
     * 查询前校验
     * @param args
     */
    public void queryVerify(BeforeDoOperationEventArgs args) {
        IDataModel model = this.getModel();
        Object welfarepayer = model.getValue("nckd_welfarepayer");
        Object year = model.getValue("nckd_year");
        if(ObjectUtils.isEmpty(welfarepayer)) {
            this.getView().showTipNotification("请选择参保单位!",3000);
            args.setCancel(true);
        }
        if(ObjectUtils.isEmpty(year)) {
            this.getView().showTipNotification("请选择收入年度!", 3000);
            args.setCancel(true);
        }
    }

    /**
     * 调整前校验
     * @param args
     */
    public void adjustVerify(BeforeDoOperationEventArgs args) {
        IDataModel model = this.getModel();
        int rowCount = model.getEntryRowCount("nckd_entryentity");
        if(rowCount == 0) {
            this.getView().showTipNotification("不存在调整的数据",3000);
            args.setCancel(true);
        }
    }



}