package nckd.jxccl.swc.mas.plugin.form.structappr;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.constant.StatusEnum;
import kd.bos.entity.datamodel.events.AfterAddRowEventArgs;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.enums.mas.ProjectCategoryEnum;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;
import nckd.jxccl.swc.constants.MasConstant;

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

/**
* 企业负责人个人年度薪酬标准核定表-表单插件
* 实体标识：nckd_entleaderanlsalstd
* @author W.Y.C
* @date 2025/11/30 14:54
* @version 1.0
*/
public class EntleaderAnlSalStdFormPlugin extends AbstractStructApprFormPlugin implements Plugin {

    @Override
    public void afterBindData(java.util.EventObject e) {
        DynamicObjectCollection entryCollection = this.getModel().getEntryEntity(FormConstant.NCKD_ENTRYENTITY);
        for (int rowIndex = 0; rowIndex < entryCollection.size(); rowIndex++) {
            DynamicObject entry = entryCollection.get(rowIndex);
            if(entry.get(MasConstant.NCKD_INSTALLMENTYEARS) != null) {
                if(entry.get(MasConstant.NCKD_INSTALLMENTYEARS) != null) {
                    int installmentYears = entry.getInt(MasConstant.NCKD_INSTALLMENTYEARS);
                    initOperateOption(installmentYears, rowIndex);
                }
            }
        }
    }

    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {
        super.afterAddRow(e);
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
    }

    @Override
    protected String getChangeEntityFormId() {
        return MasConstant.ENTLDRANLSALSTDCHG_ENTITYID;
    }

    @Override
    protected void load(){
        DynamicObject payUnit = ConvertUtil.toDynamicObjectOrNull(this.getModel().getValue(MasConstant.NCKD_PAYUNIT));
        DynamicObject lawEntity =  ConvertUtil.toDynamicObjectOrNull(this.getModel().getValue(MasConstant.NCKD_LAWENTITY));
        Date year = ConvertUtil.toDate(this.getModel().getValue(MasConstant.NCKD_YEAR));
        if(payUnit != null && lawEntity != null && year != null){
            LocalDateTime localDateTime = DateUtil.toLocalDateTime(year);
            LocalDateTime beginOfYear = DateUtil.beginOfYear(localDateTime);
            LocalDateTime endOfYear = DateUtil.endOfYear(localDateTime);

            QFilter filter = new QFilter(MasConstant.NCKD_PAYUNIT, QCP.equals, payUnit.getLong(FormConstant.ID_KEY))
                    .and(MasConstant.NCKD_LAWENTITY, QCP.equals, lawEntity.getLong(FormConstant.ID_KEY))
                    .and(MasConstant.NCKD_YEAR, QCP.large_equals, DateUtil.toDate(beginOfYear))
                    .and(MasConstant.NCKD_YEAR, QCP.less_equals, DateUtil.toDate(endOfYear))
                    .and(FormConstant.STATUS, QCP.in, new String[]{StatusEnum.C.toString(), StatusEnum.B.toString()});

            //====================================== 获取子企业负责人任职情况 begin ======================================
            QueryFieldBuilder subCoHeadServiceQueryFieldBuilder = QueryFieldBuilder.create()
                    .add(MasConstant.NCKD_EMPLOYEE)
                    .add(MasConstant.NCKD_POSNAME)
                    .add(MasConstant.NCKD_SERVICEMONTHS)
                    .add(MasConstant.NCKD_ISDIRCADRE)
                    .add(MasConstant.NCKD_ISPROFMAN)
                    .add(MasConstant.NCKD_ISMANAGER)
                    .add(MasConstant.NCKD_MGTLVLDTL)
                    .add(MasConstant.NCKD_SALNEGOT);
            DynamicObject[] dbSubCoHeadServiceArray = BusinessDataServiceHelper.load(MasConstant.SUBCOHEADSERVICE_ENTITYID, subCoHeadServiceQueryFieldBuilder.buildSelect(), new QFilter[]{filter});
            if(dbSubCoHeadServiceArray == null || dbSubCoHeadServiceArray.length == 0){
                this.getView().showTipNotification("未加载到数据，根据【所属二级单位】、【法人组织】及【年度】未加载到对应\"子企业负责人任职情况\"数据！");
            }
            //====================================== 获取子企业负责人任职情况 end ======================================


            //====================================== 获取子企业负责人薪酬结构 begin ======================================
            QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                    .addIdNumberName(MasConstant.NCKD_PAYUNIT)
                    .addIdNumberName(MasConstant.NCKD_LAWENTITY)
                    .add(MasConstant.NCKD_YEAR)
                    .add(FormConstant.NCKD_ENTRYENTITY)
                    .add(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_PROJECTCATEGORY)
                    .add(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_PROJECTCATEGORY,FormConstant.PARENT_KEY)
                    .addIdNumberName(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_PROJECTCATEGORY)
                    .addIdNumberName(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_PROJECTCATEGORY,MasConstant.PARENT_KEY)
                    .add(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_SALARYITEM)
                    .add(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_DEFERREDPAYITEM)
                    .add(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_DEFERREDPAYDESC)
                    .add(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_TERMPAYDESC);
            DynamicObject[] dbSubCorpSalaryArray = BusinessDataServiceHelper.load(MasConstant.SUBCORPSALARY_ENTITYID, queryFieldBuilder.buildSelect(), new QFilter[]{filter});
            if(dbSubCorpSalaryArray == null || dbSubCorpSalaryArray.length == 0){
                this.getView().showTipNotification("未加载到数据，根据【所属二级单位】、【法人组织】及【年度】未加载到对应\"子企业负责人薪酬结构\"数据！");
            }
            //====================================== 获取子企业负责人薪酬结构 end ======================================
            //====================================== 获取延期支付比例 begin ======================================
            QueryFieldBuilder deferPayRatoConfQueryFieldBuilder = QueryFieldBuilder.create()
                    .addIdNumberName(MasConstant.NCKD_PROJECTCATEGORY)
                    .addIdNumberName(MasConstant.NCKD_PAYUNIT)
                    .addIdNumberName(MasConstant.NCKD_LAWENTITY)
                    .add(MasConstant.NCKD_DEFERPAYRATIO)
                    .add(MasConstant.NCKD_PAYOUTTIMES)
                    .add(MasConstant.NCKD_YEAR)
                    .orderDesc(MasConstant.CREATE_TIME_KEY);
            QFilter deferPayRatoConfFilter = new QFilter(MasConstant.NCKD_PAYUNIT, QCP.equals, payUnit.getLong(FormConstant.ID_KEY))
                    .and(MasConstant.NCKD_LAWENTITY, QCP.equals, lawEntity.getLong(FormConstant.ID_KEY))
                    .and(MasConstant.NCKD_YEAR, QCP.large_equals, DateUtil.toDate(beginOfYear))
                    .and(MasConstant.NCKD_YEAR, QCP.less_equals, DateUtil.toDate(endOfYear))
                    .and(QFilterCommonHelper.getEnableFilter());
            DynamicObject[] dbDeferPayRatoConfArray = BusinessDataServiceHelper.load(MasConstant.DEFERPAYRATOCONF_ENTITYID, deferPayRatoConfQueryFieldBuilder.buildSelect(), new QFilter[]{deferPayRatoConfFilter});
            Map<String, List<DynamicObject>> dbDeferPayRatoConfMap = Arrays.stream(dbDeferPayRatoConfArray)
                    .collect(Collectors.groupingBy(obj -> {
                        DynamicObject projectCategory = obj.getDynamicObject(MasConstant.NCKD_PROJECTCATEGORY);
                        if (projectCategory != null) {
                            return projectCategory.getString(FormConstant.NUMBER_KEY);
                        }
                        return ""; // 处理无项目分类的情况
                    }));
            //====================================== 获取延期支付比例 end ======================================


            DynamicObjectCollection entryEntities = getModel().getEntryEntity(FormConstant.NCKD_ENTRYENTITY);
            entryEntities.clear();
            //====================================== 构建分录数据 begin ======================================
            if((dbSubCoHeadServiceArray != null && dbSubCoHeadServiceArray.length > 0) && (dbSubCorpSalaryArray != null && dbSubCorpSalaryArray.length > 0)) {
                for (DynamicObject dbSubCoHeadService : dbSubCoHeadServiceArray) {
                    for (DynamicObject dbSubCorpSalary : dbSubCorpSalaryArray) {
                        DynamicObjectCollection dbEntryColl = dbSubCorpSalary.getDynamicObjectCollection(MasConstant.NCKD_ENTRYENTITY);
                        for (DynamicObject dbEntryEntity : dbEntryColl) {
                            DynamicObject projectCategory = dbEntryEntity.getDynamicObject(MasConstant.NCKD_PROJECTCATEGORY);
                            DynamicObject parent = null;
                            if(projectCategory.containsProperty("parent")) {
                                parent = projectCategory.getDynamicObject("parent");
                            }
                            String projectCategoryNumber = projectCategory.getString(FormConstant.NUMBER_KEY);
                            //只取分类为"年度薪酬"的数据
                            if(projectCategoryNumber.equalsIgnoreCase(ProjectCategoryEnum.YEARLY_SALARY.getCode()) || (parent != null && (parent.getString(FormConstant.NUMBER_KEY).equalsIgnoreCase(ProjectCategoryEnum.YEARLY_SALARY.getCode())))) {
                                DynamicObject entry = entryEntities.addNew();
                                boolean deferredPayItem = dbEntryEntity.getBoolean(MasConstant.NCKD_DEFERREDPAYITEM);
                                entry.set(MasConstant.NCKD_PROJECTCATEGORY, dbEntryEntity.getDynamicObject(MasConstant.NCKD_PROJECTCATEGORY));
                                entry.set(MasConstant.NCKD_EMPLOYEE, dbSubCoHeadService.get(MasConstant.NCKD_EMPLOYEE));
                                entry.set(MasConstant.NCKD_POSNAME, dbSubCoHeadService.get(MasConstant.NCKD_POSNAME));
                                entry.set(MasConstant.NCKD_SERVICEMONTHS, dbSubCoHeadService.get(MasConstant.NCKD_SERVICEMONTHS));
                                entry.set(MasConstant.NCKD_ISDIRCADRE, dbSubCoHeadService.get(MasConstant.NCKD_ISDIRCADRE));
                                entry.set(MasConstant.NCKD_ISPROFMAN, dbSubCoHeadService.get(MasConstant.NCKD_ISPROFMAN));
                                entry.set(MasConstant.NCKD_ISMANAGER, dbSubCoHeadService.get(MasConstant.NCKD_ISMANAGER));
                                entry.set(MasConstant.NCKD_MGTLVLDTL, dbSubCoHeadService.get(MasConstant.NCKD_MGTLVLDTL));
                                entry.set(MasConstant.NCKD_SALNEGOT, dbSubCoHeadService.get(MasConstant.NCKD_SALNEGOT));
                                entry.set(MasConstant.NCKD_SALARYITEM, dbEntryEntity.get(MasConstant.NCKD_SALARYITEM));
                                entry.set(MasConstant.NCKD_DEFERREDPAYITEM, deferredPayItem);
                                //根据【项目分类】获取延期支付比例配置
                                if(deferredPayItem) {
                                    List<DynamicObject> dbDeferPayRatoConfList = dbDeferPayRatoConfMap.get(projectCategoryNumber);
                                    if (dbDeferPayRatoConfList != null && !dbDeferPayRatoConfList.isEmpty()) {
                                        DynamicObject dbDeferPayRatoConf = dbDeferPayRatoConfList.get(0);
                                        entry.set(MasConstant.NCKD_INSTALLMENTYEARS, dbDeferPayRatoConf.getInt(MasConstant.NCKD_PAYOUTTIMES));
                                    }
                                }else{
                                    entry.set(MasConstant.NCKD_INSTALLMENTYEARS, 0);
                                }
                            }
                        }

                    }
                }
                this.getView().showSuccessNotification("数据加载成功！");
            }
            //====================================== 构建分录数据 end ======================================

            getModel().updateEntryCache(entryEntities);
            getView().updateView(FormConstant.NCKD_ENTRYENTITY);

            for (int rowIndex = 0; rowIndex < entryEntities.size(); rowIndex++) {
                DynamicObject entry = entryEntities.get(rowIndex);
                if(entry.get(MasConstant.NCKD_INSTALLMENTYEARS) != null) {
                    int installmentYears = entry.getInt(MasConstant.NCKD_INSTALLMENTYEARS);
                    initOperateOption(installmentYears, rowIndex);
                }
            }

        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        handleDoChangeOperation(afterDoOperationEventArgs,
                              MasConstant.ENTLEADERANLSALSTD_ENTITYID,
                              MasConstant.ENTLEADERANLSALSTD_ENTITYID,
                              MasConstant.ENTLDRANLSALSTDCHG_ENTITYID,
                              MasConstant.ENTLDRANLSALSTDCHG_ENTITYID);
    }
}
