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

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.constant.StatusEnum;
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.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.swc.constants.MasConstant;

import java.util.Objects;
import java.util.stream.Stream;

/**
 * 激励核定表单插件抽象基类
 *
 * @author W.Y.C
 * @date 2025/12/03
 */
public abstract class AbstractIncentiveApprFormPlugin extends AbstractFormPlugin implements Plugin {

    /**
     * 获取提示信息文本
     * @return 提示信息
     */
    protected abstract String getNotificationMessage();

    /**
     * 初始化行选项（如果需要）
     * @param installmentYears 分期年数
     * @param rowIndex 行索引
     */
    protected void initOperateOption(int installmentYears, int rowIndex) {
        // 默认空实现，子类可根据需要重写
    }

    @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 (isTriggerField(fieldKey) && !Objects.equals(oldValue, newValue)) {
            load();
        }
    }

    /**
     * 判断是否为触发加载数据的字段
     * @param fieldKey 字段名
     * @return 是否为触发字段
     */
    protected boolean isTriggerField(String fieldKey) {
        return Stream.of(MasConstant.NCKD_PAYUNIT, MasConstant.NCKD_LAWENTITY, MasConstant.NCKD_TERM)
                .anyMatch(op -> op.equalsIgnoreCase(fieldKey));
    }

    protected void load() {
        DynamicObject payUnit = ConvertUtil.toDynamicObjectOrNull(this.getModel().getValue(MasConstant.NCKD_PAYUNIT));
        DynamicObject lawEntity = ConvertUtil.toDynamicObjectOrNull(this.getModel().getValue(MasConstant.NCKD_LAWENTITY));
        DynamicObject term = ConvertUtil.toDynamicObjectOrNull(this.getModel().getValue(MasConstant.NCKD_TERM));

        if (payUnit != null && lawEntity != null && term != null) {
            QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                    .addIdNumberName(MasConstant.NCKD_PAYUNIT)
                    .addIdNumberName(MasConstant.NCKD_LAWENTITY)
                    .addIdNumberName(MasConstant.NCKD_TERM)
                    .addIdNumberName(MasConstant.NCKD_EMPLOYEE)
                    .add(FormConstant.NCKD_STARTDATE)
                    .add(FormConstant.NCKD_ENDDATE)
                    .add(MasConstant.NCKD_POSNAME)
                    .add(MasConstant.NCKD_SERVICEMONTHS);

            QFilter qFilter = 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_TERM, QCP.equals, term.getLong(FormConstant.ID_KEY))
                    .and(FormConstant.STATUS, QCP.in, new String[]{StatusEnum.C.toString(), StatusEnum.B.toString()});
                    
            DynamicObject[] tenurePersonList = BusinessDataServiceHelper.load(
                    MasConstant.TENUREPERSONLIST_ENTITYID, 
                    queryFieldBuilder.buildSelect(), 
                    new QFilter[]{qFilter});
                    
            DynamicObjectCollection entryEntities = getModel().getEntryEntity(FormConstant.NCKD_ENTRYENTITY);
            entryEntities.clear();
            
            if (tenurePersonList != null && tenurePersonList.length > 0) {
                for (DynamicObject person : tenurePersonList) {
                    DynamicObject entry = entryEntities.addNew();
                    entry.set(MasConstant.NCKD_EMPLOYEE, person.get(MasConstant.NCKD_EMPLOYEE));
                    entry.set(MasConstant.NCKD_POSNAME, person.get(MasConstant.NCKD_POSNAME));
                    entry.set(MasConstant.NCKD_STARTDATE, person.get(MasConstant.NCKD_STARTDATE));
                    entry.set(MasConstant.NCKD_ENDDATE, person.get(MasConstant.NCKD_ENDDATE));
                    entry.set(MasConstant.NCKD_SERVICEMONTHS, person.get(MasConstant.NCKD_SERVICEMONTHS));
                }
                this.getView().showSuccessNotification("数据加载成功！");
            } else {
                this.getView().showTipNotification(getNotificationMessage());
            }
            
            // 初始化行选项（如果有需要）
            for (int rowIndex = 0; rowIndex < entryEntities.size(); rowIndex++) {
                DynamicObject entry = entryEntities.get(rowIndex);
                if(entry.getDataEntityType().getProperties().containsKey(MasConstant.NCKD_INSTALLMENTYEARS)) {
                    if(entry.get(MasConstant.NCKD_INSTALLMENTYEARS) != null) {
                        int installmentYears = entry.getInt(MasConstant.NCKD_INSTALLMENTYEARS);
                        initOperateOption(installmentYears, rowIndex);
                    }
                }
            }
            
            getModel().updateEntryCache(entryEntities);
            getView().updateView(FormConstant.NCKD_ENTRYENTITY);
        }
    }
}