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

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.orm.helper.QFilterCommonHelper;
import nckd.jxccl.swc.constants.MasConstant;
import nckd.jxccl.swc.constants.StmConstant;

import java.time.LocalDateTime;
import java.util.Date;

/**
* 集团本部工资总额预算申报
* 实体标识：nckd_grphqttlwgbgtsub
* @author W.Y.C
* @date 2025/12/14 19:17
* @version 1.0
*/
public class GrpHqTtlWgBgtSubFormPlugin 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 (StmConstant.NCKD_YEAR.equalsIgnoreCase(fieldKey)) {
            loadLastData();
        }
    }

    /**
     * 加载上年度执行情况
     * @param
     * @return: void
     * @author W.Y.C
     * @date: 2025/12/14 18:59
     */
    private void loadLastData(){
        BillShowParameter showParameter = (BillShowParameter) this.getView().getFormShowParameter();
        String formId = showParameter.getFormId();
        if(formId.equalsIgnoreCase(StmConstant.GRPHQTTLWGBGTSU_ENTITYID)) {
            Date year = this.getModel().getDataEntity(true).getDate(MasConstant.NCKD_YEAR);
            if (year != null) {
                // 清理现有数据
                DataEntityPropertyCollection currentProperties = this.getModel().getDataEntityType().getProperties();
                for (IDataEntityProperty property : currentProperties) {
                    String name = property.getName();
                    if (name.indexOf("nckd_") > -1 && (name.endsWith("lya") || name.endsWith("lye"))) {
                        this.getModel().setValue(name, null);
                    }
                }
                //ad -> lay
                //ex -> lye


                LocalDateTime lastYear = DateUtil.minusYears(DateUtil.toLocalDateTime(year), 1);

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

                LocalDateTime beginOfYear = DateUtil.beginOfYear(lastYear);
                LocalDateTime endOfYear = DateUtil.endOfYear(lastYear);

                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.GRPHQTTLWGBGTEXEC_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.GRPHQTTLWGBGTEXEC_ENTITYID);
                DynamicObject[] load = BusinessDataServiceHelper.load(new Long[]{id}, entityType);

                if (load == null || load.length == 0) {
                    this.getView().showTipNotification("未加载到数据，根据【年度】未加载到上年度\"集团本部工资总额执行情况\"数据！");
                    return;
                }

                DataEntityPropertyCollection properties = load[0].getDynamicObjectType().getProperties();
                for (IDataEntityProperty property : properties) {
                    String name = property.getName();
                    if (name.indexOf("nckd_") > -1  && (name.endsWith("ad") || name.endsWith("ex"))) {
                        String currentName = name.replace("ad", "lya").replace("ex", "lye");
                        if(this.getModel().getDataEntityType().getProperties().containsKey(currentName)) {
                            this.getModel().setValue(currentName, load[0].get(name));
                        }
                    }
                }
                this.getView().showSuccessNotification("成功加载上年度\"集团本部工资总额执行情况\"数据！");
            }
        }
    }
}