package nckd.jxccl.opmc.pm.plugin.form;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.dataentity.metadata.dynamicobject.DynamicSimpleProperty;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.ListField;
import kd.bos.entity.datamodel.events.GetEntityTypeEventArgs;
import kd.bos.entity.property.TextProp;
import kd.bos.exception.ErrorCode;
import kd.bos.exception.KDException;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.events.BeforeCreateListColumnsArgs;
import kd.bos.form.events.BeforeCreateListDataProviderArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.IListColumn;
import kd.bos.list.ListColumn;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.mvc.list.ListDataProvider;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import nckd.jxccl.base.common.utils.DateTimeUtils;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.opmc.pm.helper.KpiImportUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: ExaminProjectResultListPlugin
 * @Description: 绩效结果列表插件
 * @Author: PJJ
 * @Date: 2026/1/7 上午9:41
 * @Version: 1.0
 */
public class ExaminProjectResultListPlugin extends AbstractListPlugin {
//    private ExaminProjectResultBillList billList;
    private static final Log logger = LogFactory.getLog(ExaminProjectResultListPlugin.class);

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate source = (FormOperate) args.getSource();
        String operateKey = source.getOperateKey();
        if (StringUtils.equals(operateKey, "import")) {
            //打开自定义导入模板选择界面
            FormShowParameter fsp = new FormShowParameter();
            fsp.setFormId("nckd_kpi_import_select");
            fsp.setShowTitle(false);
            fsp.getOpenStyle().setShowType(ShowType.Modal);
            fsp.setCustomParam("importplan", this.getView().getFormShowParameter().getCustomParam("importplan"));
            fsp.setCustomParam("template", this.getView().getFormShowParameter().getCustomParam("template"));
            fsp.setCloseCallBack(new CloseCallBack(this, "importData"));
            this.getView().showForm(fsp);
        }else if( StringUtils.equals(operateKey, "update") ){
            FormShowParameter parentParameter = this.getView().getFormShowParameter();
            Object customParam = parentParameter.getCustomParam("importplan");
            DynamicObject importPlan = BusinessDataServiceHelper.loadSingle(customParam, "nckd_importplan");
            Date year = importPlan.getDate("nckd_year");
            Integer month = importPlan.getInt("nckd_month");
            LocalDateTime modifiedDate = DateUtil.toLocalDateTime(year).withMonth(month);
            List<DynamicObject> users = KpiImportUtils.querEmpposorgre(DateUtil.endOfMonth(modifiedDate));
            createData(users);
        }
    }

    private void createData(List<DynamicObject> users){
        ArrayList<DynamicObject> saveData = new ArrayList<>();
        DynamicObject importPlan = BusinessDataServiceHelper.loadSingle(this.getView().getFormShowParameter().getCustomParam("importplan"), "nckd_importplan");
        List<String> userNumber = users.stream().map(i -> i.getString("employee.empnumber")).collect(Collectors.toList());
        DynamicObject[] bos_ser = BusinessDataServiceHelper.load("bos_user", "id,number,name,entryentity.dpt,entryentity.ispartjob,entryentity.post", new QFilter[]{new QFilter("number", QCP.in, userNumber)});
        for (DynamicObject user : bos_ser) {
            DynamicObject newData = BusinessDataServiceHelper.newDynamicObject("nckd_examinproject_result");
            newData.set("enable", "1");
            newData.set("status", "A");
            newData.set("nckd_importplan", importPlan);
            DynamicObjectCollection entry = user.getDynamicObjectCollection("entryentity");
            List<DynamicObject> collect = entry.stream().filter(i -> !i.getBoolean("ispartjob")).collect(Collectors.toList());
            newData.set("group",collect.get(0).getLong("dpt.id"));
            newData.set("nckd_user",user.getPkValue());
            newData.set("nckd_org",collect.get(0).getLong("dpt.id"));
            newData.set("nckd_postbase",collect.get(0).getLong("post.id"));
            saveData.add(newData);
        }
        Object[] save = SaveServiceHelper.save(saveData.toArray(new DynamicObject[saveData.size()]));
        if( ObjectUtils.isNotEmpty(save) ){
            this.getView().showSuccessNotification("人员数据更新完毕!");
        }
        this.getView().invokeOperation("refresh");
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        if (StringUtils.equals(actionId, "importData")) {
            Object returnData = e.getReturnData();
            if (ObjectUtils.isNotEmpty(returnData)) {
                this.getView().showSuccessNotification("导入完毕");
                this.getView().invokeOperation("refresh");
            }else{
                this.getView().showErrorNotification("导入失败，请联系系统管理员。");
            }
        }


//        Map returnData;
//        if ("importData".equals(actionId)) {
//            returnData = (Map) e.getReturnData();
//            if (returnData == null) {
//                return;
//            }
//            if ((Boolean) returnData.get("isOk")) {
//                int totalCount = Integer.parseInt(returnData.get("totalCount").toString());
//                Long importTaskId = (Long) returnData.get("importTaskId");
//                String cacheKey = (String) returnData.get("cacheKey");
//                String caption = ResManager.loadKDString("导入看板", "ImportTaskGuideOpereateBillList_33", "swc-hsas-formplugin", new Object[0]);
//                this.openProgressPage(totalCount, importTaskId, "22", "importingData", caption, cacheKey);
//            }
//        } else if ("importingData".equals(actionId)) {
//            returnData = (Map) e.getReturnData();
//            if (returnData != null && !returnData.isEmpty()) {
//                this.openImportingView(returnData);
//            } else {
//                this.getView().invokeOperation("refresh");
//            }
//        } else {
//            this.getView().invokeOperation("refresh");
//        }
    }

    private void openProgressPage(int totalCount, Long importTaskId, String progressType, String closeCalBackId, String caption, String verifyId) {
        FormShowParameter formShowParameter = new FormShowParameter();
        formShowParameter.setFormId("hsas_datacheckprogress");
        formShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        formShowParameter.setCaption(caption);
        formShowParameter.setCustomParam("importTaskId", importTaskId);
        formShowParameter.setCustomParam("totalCount", totalCount);
        formShowParameter.setCustomParam("verifyId", verifyId);
        formShowParameter.setCustomParam("startTime", DateTimeUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        formShowParameter.setCustomParam("progressType", progressType);
        formShowParameter.setCloseCallBack(new CloseCallBack(this, closeCalBackId));
        this.getView().showForm(formShowParameter);
    }

    private void openImportingView(Map<String, Object> dataMap) {
        FormShowParameter formShowParameter = new FormShowParameter();
        formShowParameter.setFormId("hsas_taskguideimportret");
        formShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        formShowParameter.setCustomParam("importTaskId", dataMap.get("importTaskId"));
        formShowParameter.setCustomParam("successCout", dataMap.get("successCout"));
        formShowParameter.setCustomParam("failCout", dataMap.get("failCout"));
        formShowParameter.setCustomParam("cacheKey", dataMap.get("cacheKey"));
        formShowParameter.setCloseCallBack(new CloseCallBack(this, "importErrorData"));
        this.getView().showForm(formShowParameter);
    }

    /**
     * 创建列表列前触发
     *
     * @param args 创建列表前事件参数 {@link BeforeCreateListColumnsArgs}
     */
    @Override
    public void beforeCreateListColumns(BeforeCreateListColumnsArgs args) {
        super.beforeCreateListColumns(args);
        // 获取设计器预置的列集合
        List<IListColumn> columns = args.getListColumns();
        int seq = 6;
        Long templateId = this.getView().getFormShowParameter().getCustomParam("template");
        // 添加考勤项目列表字段
        DynamicObjectCollection dynamicObjects = queryData(templateId);
        for (DynamicObject obj : dynamicObjects) {
            DynamicObject item = obj.getDynamicObject("nckd_examine_dimension");
            String number = item.getString("number");
            if (StringUtils.equalsAny(number, "JT-00001", "JT-00002", "JT-00003", "JT-00004", "JT-00005", "JT-00006", "JT-00007", "JT-00018")) {
                continue;
            }
            columns.add(seq++, createListColumn(getItemPropKey(item), item.getString("name"), columns.get(0)));
        }
    }

    private String getItemPropKey(DynamicObject item) {
        return item.getString("number").toLowerCase();
    }

    /**
     * 创建列对象返回
     *
     * @param columnKey   新列映射的单据字段
     * @param columnName  新列列名
     * @param firstColumn 新列的父容器
     * @return
     */
    private ListColumn createListColumn(String columnKey, String columnName, IListColumn firstColumn) {
        ListColumn col = new ListColumn();
        // 设置映射字段
        col.setListFieldKey(columnKey);
        col.setKey(columnKey);
        col.setCaption(new LocaleString(columnName));
        col.setParent(firstColumn.getParent());
        col.setParentViewKey(firstColumn.getParent().getKey());
        col.setSeq(2);
        col.setVisible(11);
        return col;
    }


    @Override
    public void billListGetEntityType(GetEntityTypeEventArgs args) {
        super.billListGetEntityType(args);
        // 取原始的主实体
        MainEntityType oldMainType = args.getOriginalEntityType();
        // 复制主实体 单例对象不允许修改
        MainEntityType newMainType = null;
        try {
            newMainType = (MainEntityType) oldMainType.clone();
        } catch (CloneNotSupportedException exp) {
            throw new KDException(exp, new ErrorCode("ExaminProjectResultListPlugin", exp.getMessage()));
        }
        // 为自定义的文本字段，向主实体注册文本属性
        this.registDynamicProps(newMainType);
        // 回传主实体给系统
        args.setNewEntityType(newMainType);
    }


    /**
     * 向主实体注册动态添加的属性
     */
    private void registDynamicProps(MainEntityType newMainType) {
        // 添加考勤项目列表字段
        Long templateId = this.getView().getFormShowParameter().getCustomParam("template");
        DynamicObjectCollection dynamicObjects = queryData(templateId);
        for (DynamicObject obj : dynamicObjects) {
            DynamicObject item = obj.getDynamicObject("nckd_examine_dimension");
            // 向单据头动态注册一个新的文本属性
            TextProp textProp = new TextProp();

            textProp.setName(getItemPropKey(item)); // 标识
            textProp.setDisplayName(new LocaleString(item.getString("name")));     // 标题

            textProp.setDbIgnore(true);  // 此字段不需到物理表格取数
//            textProp.setAlias("F" + getItemPropKey(item));           // 物理字段名

            // 把新字段，注册到单据头
            newMainType.registerSimpleProperty(textProp);
        }
    }

    /**
     * 查询导入模板数据
     * @param template
     * @return
     */
    public static DynamicObjectCollection queryData(Long template){
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("nckd_import_kpi_template", "id,number,name,nckd_outimptplentry.nckd_examine_dimension", new QFilter[]{new QFilter("id", QCP.equals, template)});
        DynamicObjectCollection dynamicObjectCollection = dynamicObject.getDynamicObjectCollection("nckd_outimptplentry");
        return dynamicObjectCollection;
    }

    @Override
    public void beforeCreateListDataProvider(BeforeCreateListDataProviderArgs args) {
        super.beforeCreateListDataProvider(args);
        FormShowParameter formShowParameter = this.getView().getFormShowParameter();
        Long templateId = formShowParameter.getCustomParam("template");
        Long importPlanId = formShowParameter.getCustomParam("importplan");
        args.setListDataProvider(new ExaminProjectResultListPlugin.ImportItemDataResultImpl(templateId,importPlanId));
    }

    public class ImportItemDataResultImpl extends ListDataProvider {
        private Long templateId;
        private Long importPlanId;

        public ImportItemDataResultImpl(Long templateId,Long importPlanId) {
            this.templateId = templateId;
            this.importPlanId = importPlanId;
        }

        @Override
        public DynamicObjectCollection getData(int start, int limit) {
            // 隐藏动态添加字段（数据库中查不到）
            List<ListField> listFields = getListFields();
            List<ListField> newListFields = listFields.stream().filter(e -> !e.getKey().contains("jt-")).collect(Collectors.toList());
            setListFields(newListFields);

            DynamicObjectCollection rows = super.getData(start, limit);
            if (rows.isEmpty()) {
                return rows;
            }

            // 添加考核维度列表字段
            DynamicObjectCollection dynamicObjects = ExaminProjectResultListPlugin.this.queryData(templateId);

            // 注册属性
            DynamicObjectType dt = rows.getDynamicObjectType();
            for (DynamicObject obj : dynamicObjects) {
                DynamicObject item = obj.getDynamicObject("nckd_examine_dimension");
                String number = item.getString("number");
                if (StringUtils.equalsAny(number, "JT-00001", "JT-00002", "JT-00003", "JT-00004", "JT-00005", "JT-00006", "JT-00007", "JT-00018")) {
                    continue;
                }
                DynamicSimpleProperty property = new DynamicSimpleProperty(ExaminProjectResultListPlugin.this.getItemPropKey(item), String.class, null);
                dt.registerSimpleProperty(property);
            }

            DynamicObject[] load = BusinessDataServiceHelper.load("nckd_examinproject_result", "id,nckd_entryentity.nckd_examine_dimension,nckd_entryentity.nckd_result", new QFilter[]{new QFilter("nckd_importplan", QCP.equals, importPlanId)});

            // 设置值
            for (DynamicObject row : rows) {
                for (DynamicObject dynamicObject : load) {
                    long resultId = dynamicObject.getLong("id");
                    long rowId = row.getLong("id");
                    if( resultId == rowId ){
                        DynamicObjectCollection entry = dynamicObject.getDynamicObjectCollection("nckd_entryentity");
                        for (DynamicObject obj : entry) {
                            DynamicObject item = obj.getDynamicObject("nckd_examine_dimension");
                            String number = item.getString("number");
                            if (StringUtils.equalsAny(number, "JT-00001", "JT-00002", "JT-00003", "JT-00004", "JT-00005", "JT-00006", "JT-00007", "JT-00018")) {
                                continue;
                            }
                            row.set(number, obj.getString("nckd_result"));
                        }
                    }
                }
            }

            // 设置可见(不设置，则上述注册字段默认不展示）
            setVisibleSelectFieldList(listFields);
            return rows;
        }
    }
}
