package nckd.jxccl.swc.stm.plugin.form.ttlwg;

import kd.bos.bill.BillShowParameter;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.metadata.clr.DataEntityPropertyCollection;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.base.entity.helper.EntityHelper;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;
import nckd.jxccl.swc.constants.MasConstant;
import nckd.jxccl.swc.constants.StmConstant;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;
import java.util.stream.Stream;

/**
* 工资总额执行分解
* 实体标识：nckd_ttlwgexecdecomp
* @author W.Y.C
* @date 2025/12/15 18:39
* @version 1.0
*/
public class TtlWgExecDeCompFormPlugin extends AbstractFormPlugin implements Plugin {
    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String fieldKey = e.getProperty().getName();
        ChangeData[] changeSet = e.getChangeSet();
        Object oldValue = changeSet[0].getOldValue();
        Object newValue = changeSet[0].getNewValue();
        if (Stream.of(StmConstant.NCKD_YEAR,  StmConstant.NCKD_DEP)
                .anyMatch(op -> op.equalsIgnoreCase(fieldKey))) {
            if(!Objects.equals(oldValue, newValue)){
                loadData();
            }

        }
    }

    private void loadData(){
        BillShowParameter showParameter = (BillShowParameter) this.getView().getFormShowParameter();
        String formId = showParameter.getFormId();
        if(formId.equalsIgnoreCase(StmConstant.TTLWGEXECDECOMP_ENTITYID)) {
            Date year = this.getModel().getDataEntity(true).getDate(MasConstant.NCKD_YEAR);
            if (year != null) {
                // 清理现有数据
                clearExistingData();

                // 加载同年度同单位的预算申报数据
                QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                        .add(FormConstant.ID_KEY)
                        .orderDesc(FormConstant.CREATE_TIME_KEY);

                LocalDateTime beginOfYear = DateUtil.beginOfYear(DateUtil.toLocalDateTime(year));
                LocalDateTime endOfYear = DateUtil.endOfYear(DateUtil.toLocalDateTime(year));

                QFilter qFilter = new QFilter(StmConstant.NCKD_YEAR, QCP.large_equals, DateUtil.toDate(beginOfYear))
                        .and(StmConstant.NCKD_YEAR, QCP.less_equals, DateUtil.toDate(endOfYear))
                        .and(QFilterCommonHelper.getBillStatusFilter());

                DynamicObjectCollection unitStBudgetApplyColl = QueryServiceHelper.query(
                        StmConstant.TTLWGADJDECOMP_ENTITYID,
                        queryFieldBuilder.buildSelect(),
                        new QFilter[]{qFilter},
                        queryFieldBuilder.buildOrder());

                if (unitStBudgetApplyColl == null || unitStBudgetApplyColl.isEmpty()) {
                    this.getView().showTipNotification("未加载到数据，根据【年度】【填报部门】未加载到\"工资总额调整分解\"数据！");
                    return;
                }

                DynamicObject unitStBudgetApply = unitStBudgetApplyColl.get(0);
                long id = unitStBudgetApply.getLong(FormConstant.ID_KEY);
                MainEntityType entityType = EntityMetadataCache.getDataEntityType(StmConstant.TTLWGADJDECOMP_ENTITYID);
                DynamicObject[] load = BusinessDataServiceHelper.load(new Long[]{id}, entityType);

                if (load == null || load.length == 0) {
                    this.getView().showTipNotification("未加载到数据，根据【年度】【填报部门】未加载到\"工资总额调整分解\"数据！");
                    return;
                }

                copyBudgetData(load[0]);
                DynamicObject dynamicObject = EntityHelper.newEntity(StmConstant.TTLWGADJDECOMP_ENTITYID, load[0].getLong(StmConstant.ID_KEY));
                this.getModel().setValue(StmConstant.TTLWGADJDECOMP_ENTITYID, dynamicObject);
                this.getView().showSuccessNotification("数据加载成功！");
            }
        }
    }

    private void clearExistingData() {
        DataEntityPropertyCollection properties = this.getModel().getDataEntityType().getProperties();
        for (IDataEntityProperty property : properties) {
            String name = property.getName();
            if (name.indexOf("nckd_") > -1 && this.getModel().getDataEntityType().getProperties().containsKey(name)  && !name.endsWith("ex") && StmConstant.IGNORE_FIELDS.stream().noneMatch(ignoreField -> ignoreField.equalsIgnoreCase(name))) {
                this.getModel().setValue(name, null);
            }
        }
    }

    // 提取复制数据逻辑
    private void copyBudgetData(DynamicObject source) {
        DataEntityPropertyCollection properties = source.getDynamicObjectType().getProperties();
        for (IDataEntityProperty property : properties) {
            String name = property.getName();
            if (name.indexOf("nckd_") > -1 && this.getModel().getDataEntityType().getProperties().containsKey(name)  && !name.endsWith("ex") && StmConstant.IGNORE_FIELDS.stream().noneMatch(ignoreField -> ignoreField.equalsIgnoreCase(name))) {
                this.getModel().setValue(name, source.get(name));
            }
            if("nckd_wagetypead".equalsIgnoreCase( name)){
                this.getModel().setValue("nckd_wagetypeex", source.get(name));
            }else if("nckd_itemnamead".equalsIgnoreCase( name)){
                this.getModel().setValue("nckd_itemnameex", source.get(name));
            }
        }
    }
}