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

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.ILocaleString;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.entity.BasedataEntityType;
import kd.bos.entity.constant.StatusEnum;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.IDataModelChangeListener;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.property.BasedataProp;
import kd.bos.entity.property.MulBasedataProp;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.AfterBindingDataEvent;
import kd.bos.form.field.events.BasedataEditListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.swc.constants.MasConstant;

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

/**
* 企业负责人单项考核工资核定表-表单插件
* 实体标识：nckd_entldritemwageappr
* @author W.Y.C
* @date 2025/11/30 16:05
* @version 1.0
*/
public class EntLdrItemWageApprFormPlugin  extends AbstractFormPlugin implements BasedataEditListener, IDataModelChangeListener {

    @Override
    public void initialize() {
        this.getModel().addDataModelChangeListener(this);
        BasedataEdit mulEdit = this.getControl(MasConstant.NCKD_SUBCORPSALARYENTRY);
        mulEdit.addBasedataEditListener(this);
    }

    @Override
    public void afterBindingData(AfterBindingDataEvent evt) {
        //修改"单项奖项目"，F7显示字段
        BasedataEdit edit = (BasedataEdit) evt.getSource();
        Object v = evt.getDataEntity();
        Object editSearchProp = null;
        Object displayProp = "";
        if (v == null) {
            return;
        }

        BasedataEntityType dt;
        if (((DynamicObject) v).getDataEntityType() instanceof BasedataEntityType) {
            dt = (BasedataEntityType) ((DynamicObject) v).getDataEntityType();
        } else {
            dt = (BasedataEntityType) ((BasedataProp) edit.getProperty()).getComplexType();
        }

        //获取数据包中的名称字段值
        String nameKey = dt.getNameProperty();
        IDataEntityProperty p2 = dt.findProperty(nameKey);
        if (p2 != null) {
            displayProp = p2.getValueFast(v);
            if (displayProp instanceof ILocaleString) {
                displayProp = displayProp.toString();
            }
        }

        //动态修改多选基础资料的显示属性为名称(部门)
        if (MasConstant.NCKD_SUBCORPSALARYENTRY.equals(edit.getKey())) {
            nameKey = MasConstant.NCKD_SALARYITEM;
        }
        IDataEntityProperty p4 = dt.findProperty(nameKey);
        if (p4 != null) {
            Object valueFast = p4.getValueFast(v);
            if(valueFast instanceof DynamicObject){
                displayProp = ConvertUtil.toDynamicObjectOrNull(valueFast).getString(FormConstant.NAME_KEY);
                editSearchProp = ConvertUtil.toDynamicObjectOrNull(valueFast).getString(FormConstant.NUMBER_KEY);

            }
        }

        //设置显示属性
        evt.setDisplayProp(displayProp.toString());
        //设置编辑显示属性
        evt.setEditSearchProp(editSearchProp == null ? "" : editSearchProp.toString());
    }

    /**
     * 获取配置的编辑显示属性
     *
     * @param property
     * @return
     */
    private String getEditSearchProp(IDataEntityProperty property) {
        BasedataProp basedataProp = null;

        if ((property instanceof BasedataProp)) {
            basedataProp = (BasedataProp) property;
        } else if (property instanceof MulBasedataProp) {
            basedataProp = (BasedataProp) ((MulBasedataProp) property).getRefBaseProp();
        }

        return basedataProp.getEditSearchProp();
    }


    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String fieldKey = e.getProperty().getName();
        ChangeData[] changeSet = e.getChangeSet();
        int rowIndex = changeSet[0].getRowIndex();
        Object oldValue = changeSet[0].getOldValue();
        Object newValue = changeSet[0].getNewValue();
        if(Stream.of(MasConstant.NCKD_PAYUNIT, MasConstant.NCKD_LAWENTITY, MasConstant.NCKD_YEAR)
                .anyMatch(op -> op.equalsIgnoreCase(fieldKey))){
            if(!Objects.equals(oldValue, newValue)){
                DynamicObjectCollection entryEntities = getModel().getEntryEntity(FormConstant.NCKD_ENTRYENTITY);
                load();
            }
        }
    }


    private 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)
                    .add(MasConstant.NCKD_SALCALCPOST);
            DynamicObject[] dbSubCoHeadServiceArray = BusinessDataServiceHelper.load(MasConstant.SUBCOHEADSERVICE_ENTITYID, subCoHeadServiceQueryFieldBuilder.buildSelect(), new QFilter[]{filter});
            if(dbSubCoHeadServiceArray == null || dbSubCoHeadServiceArray.length == 0){
                this.getView().showTipNotification("未加载到数据，根据【所属二级单位】、【法人组织】及【年度】未加载到对应\"子企业负责人任职情况\"数据！");
            }
            //====================================== 获取子企业负责人任职情况 end ======================================

            DynamicObjectCollection entryEntities = getModel().getEntryEntity(FormConstant.NCKD_ENTRYENTITY);
            entryEntities.clear();
            //====================================== 构建分录数据 begin ======================================
            if((dbSubCoHeadServiceArray != null && dbSubCoHeadServiceArray.length > 0) ) {
                for (DynamicObject dbSubCoHeadService : dbSubCoHeadServiceArray) {
                    DynamicObject entry = entryEntities.addNew();
                    entry.set(MasConstant.NCKD_EMPLOYEE, dbSubCoHeadService.get(MasConstant.NCKD_EMPLOYEE));
                    entry.set(MasConstant.NCKD_POSNAME, dbSubCoHeadService.get(MasConstant.NCKD_POSNAME));
                    entry.set(MasConstant.NCKD_SALCALCPOST, dbSubCoHeadService.get(MasConstant.NCKD_SALCALCPOST));
                }
                this.getView().showSuccessNotification("数据加载成功！");
            }
            //====================================== 构建分录数据 end ======================================
            getModel().updateEntryCache(entryEntities);
            getView().updateView(FormConstant.NCKD_ENTRYENTITY);

        }
    }
}