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

import kd.bos.bill.BillShowParameter;
import kd.bos.dataentity.OperateOption;
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.datamodel.events.AfterAddRowEventArgs;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.validate.BillStatus;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.ConfirmTypes;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.MessageBoxClosedEvent;
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.bos.servicehelper.operation.SaveServiceHelper;
import kd.hr.hbp.common.util.HRDynamicObjectUtils;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.exception.ValidationException;
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.common.utils.ShowOperExecuteResult;
import nckd.jxccl.base.common.utils.StrFormatter;
import nckd.jxccl.base.entity.helper.EntityHelper;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;
import nckd.jxccl.swc.constants.MasConstant;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 结构化考核审批表单插件抽象基类
 * 用于提取子企业负责人薪酬标准核定相关表单插件的公共逻辑
 *
 * @author W.Y.C
 * @date 2025/12/03
 * @version 1.0
 */
public abstract class AbstractStructApprFormPlugin extends AbstractFormPlugin implements Plugin {

    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {
        initOperateOption(0, e.getInsertRow());
    }

    @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 (MasConstant.NCKD_INSTALLMENTYEARS.equalsIgnoreCase(fieldKey)) {
            if (!Objects.equals(oldValue, newValue)) {
                initOperateOption(ConvertUtil.toInt(newValue,0), rowIndex);
            }
        } else if (Stream.of(MasConstant.NCKD_PAYUNIT, MasConstant.NCKD_LAWENTITY, MasConstant.NCKD_YEAR)
                .anyMatch(op -> op.equalsIgnoreCase(fieldKey))) {
            if (!Objects.equals(oldValue, newValue)) {
                load();
            }
        } else if (MasConstant.NCKD_APPRSTD.equalsIgnoreCase(fieldKey)) {
            handleApprStdChanged(oldValue, newValue, rowIndex);
        }
    }

    /**
     * 处理核定标准字段变化事件
     *
     * @param oldValue 旧值
     * @param newValue 新值
     * @param rowIndex 行索引
     */
    protected void handleApprStdChanged(Object oldValue, Object newValue, int rowIndex) {
        DynamicObject payUnit = ConvertUtil.toDynamicObjectOrNull(this.getModel().getValue(MasConstant.NCKD_PAYUNIT));
        DynamicObject lawEntity = ConvertUtil.toDynamicObjectOrNull(this.getModel().getValue(MasConstant.NCKD_LAWENTITY));
        DynamicObject projectCategory = ConvertUtil.toDynamicObjectOrNull(this.getModel().getValue(MasConstant.NCKD_PROJECTCATEGORY));
        Date year = ConvertUtil.toDate(this.getModel().getValue(MasConstant.NCKD_YEAR));
        // 判断"核定标准"是否大于0
        BigDecimal apprStd = ConvertUtil.toBigDecimal(newValue);
        if (apprStd != null && apprStd.compareTo(BigDecimal.ZERO) > 0) {
            if (payUnit != null && lawEntity != null && year != null && projectCategory != null) {
                if (!Objects.equals(oldValue, newValue)) {
                    // 计算：延期支付总金额、支付年份1、支付年份1....
                    // ====================================== 获取延期支付比例 begin ======================================
                    LocalDateTime localDateTime = DateUtil.toLocalDateTime(year);
                    LocalDateTime beginOfYear = DateUtil.beginOfYear(localDateTime);
                    LocalDateTime endOfYear = DateUtil.endOfYear(localDateTime);

                    QueryFieldBuilder deferPayRatoConfQueryFieldBuilder = QueryFieldBuilder.create()
                            .add(MasConstant.NCKD_PROJECTCATEGORY)
                            .addIdNumberName(MasConstant.NCKD_PAYUNIT)
                            .addIdNumberName(MasConstant.NCKD_DEFERPAYMONEY)
                            .add(MasConstant.NCKD_DEFERPAYRATIO)
                            .add(MasConstant.NCKD_DEFERPAYRATIO)
                            .add(MasConstant.NCKD_PAYOUTTIMES)
                            .add(MasConstant.NCKD_YEAR)
                            .add(FormConstant.NCKD_ENTRYENTITY)
                            .add(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_TIMES)
                            .add(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_PAYOUTRATIO)
                            .add(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_PAYOUTMONEY)
                            .add(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_DEFERREDPAYITEM)
                            .add(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_DEFERREDPAYDESC)
                            .add(FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_TERMPAYDESC)
                            .orderDesc(MasConstant.CREATE_TIME_KEY)
                            .orderAsc(String.join(".", FormConstant.NCKD_ENTRYENTITY, MasConstant.NCKD_TIMES));
                    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 dbProjectCategory = obj.getDynamicObject(MasConstant.NCKD_PROJECTCATEGORY);
                                if (dbProjectCategory != null) {
                                    return dbProjectCategory.getString(FormConstant.NUMBER_KEY);
                                }
                                return ""; // 处理无项目分类的情况
                            }));
                    List<DynamicObject> dbDeferPayRatoConfList = dbDeferPayRatoConfMap.get(projectCategory.getString(FormConstant.NUMBER_KEY));

                    if (dbDeferPayRatoConfList != null && !dbDeferPayRatoConfList.isEmpty()) {
                        DynamicObject deferPayRatoConf = dbDeferPayRatoConfList.get(0);
                        // 延期支付比例（%）
                        BigDecimal deferPayRatio = deferPayRatoConf.getBigDecimal(MasConstant.NCKD_DEFERPAYRATIO);
                        // 延期支付金额
                        BigDecimal deferPayMoney = deferPayRatoConf.getBigDecimal(MasConstant.NCKD_DEFERPAYMONEY);
                        LocalDateTime beginYear = DateUtil.toLocalDateTime(deferPayRatoConf.getDate(MasConstant.NCKD_YEAR));
                        BigDecimal deferPayTotalAmt;
                        if (deferPayMoney != null && deferPayMoney.compareTo(BigDecimal.ZERO) > 0) {
                            // 优先使用【延期支付金额】
                            deferPayTotalAmt = deferPayMoney;
                        } else {
                            // 核算标准*延期支付比例/100
                            deferPayTotalAmt = apprStd.multiply(deferPayRatio.divide(new BigDecimal(100), 2, RoundingMode.DOWN));
                        }
                        this.getModel().setValue(MasConstant.NCKD_DEFERPAYTOTALAMT, deferPayTotalAmt, rowIndex);
                        DynamicObjectCollection entryColl = deferPayRatoConf.getDynamicObjectCollection(FormConstant.NCKD_ENTRYENTITY);
                        int i = 0;
                        for (DynamicObject entry : entryColl) {
                            int times = entry.getInt(MasConstant.NCKD_TIMES);
                            // 兑现比例（%）
                            BigDecimal payoutRatio = entry.getBigDecimal(MasConstant.NCKD_PAYOUTRATIO);
                            // 兑现金额
                            BigDecimal payoutMoney = entry.getBigDecimal(MasConstant.NCKD_PAYOUTMONEY);
                            BigDecimal payaMount;
                            if (payoutMoney != null && payoutMoney.compareTo(BigDecimal.ZERO) > 0) {
                                // 优先使用【兑现金额】
                                payaMount = payoutMoney;
                            } else {
                                // 延期支付总金额*兑现比例
                                payaMount = deferPayTotalAmt.multiply(payoutRatio.divide(new BigDecimal(100), 2, RoundingMode.DOWN));
                            }
                            if (i != 0) {
                                beginYear = DateUtil.addYears(beginYear, 1);
                            }
                            this.getModel().setValue(MasConstant.NCKD_PAYYEAR + (i + 1), DateUtil.toDate(beginYear), rowIndex);
                            this.getModel().setValue(MasConstant.NCKD_PAYAMOUNT + (i + 1), payaMount, rowIndex);
                            i++;
                        }

                    }
                    // ====================================== 获取延期支付比例 end ======================================

                }
            }
        } else {
            this.getModel().setValue(MasConstant.NCKD_DEFERPAYTOTALAMT, null);
        }
    }

    /**
     * 设置支付N锁定或解锁
     *
     * @param installmentYears 分期支付年
     * @param rowIndex         行索引
     */
    protected void initOperateOption(int installmentYears, int rowIndex) {
            if (rowIndex > -1) {
            for (int i = 1; i <= 10; i++) {
                this.getView().setEnable(false, rowIndex, MasConstant.NCKD_PAYYEAR + i);
                this.getView().setEnable(false, rowIndex, MasConstant.NCKD_PAYAMOUNT + i);
            }
            for (int i = 1; i <= installmentYears; i++) {
                this.getView().setEnable(true, rowIndex, MasConstant.NCKD_PAYYEAR + i);
                this.getView().setEnable(true, rowIndex, MasConstant.NCKD_PAYAMOUNT + i);
            }
            for (int i = installmentYears+1; i <= 10; i++) {
                this.getModel().setValue( MasConstant.NCKD_PAYYEAR + i,null,rowIndex);
                this.getModel().setValue( MasConstant.NCKD_PAYAMOUNT + i,null,rowIndex);
            }
        }
    }

    /**
     * 处理变更操作
     *
     * @param afterDoOperationEventArgs 操作事件参数
     * @param entityName 变更实体名
     * @param entityId 当前实体ID字段名
     * @param changeEntityId 变更单实体ID
     * @param changeEntityFormId 变更单表单ID
     */
    protected void handleDoChangeOperation(
            AfterDoOperationEventArgs afterDoOperationEventArgs,
            String entityName,
            String entityId,
            String changeEntityId,
            String changeEntityFormId) {
        
        if (afterDoOperationEventArgs.getOperationResult() != null && afterDoOperationEventArgs.getOperationResult().isSuccess()) {
            String operateKey = afterDoOperationEventArgs.getOperateKey();
            if (operateKey.equalsIgnoreCase("change")) {
                DynamicObject data = this.getModel().getDataEntity();
                // 校验有没有暂存或进行中的审批单
                QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                        .add(FormConstant.BILL_NO_KEY);
                QFilter filter = new QFilter(FormConstant.BILL_STATUS_KEY, QCP.not_equals, BillStatus.C.toString())
                        .and(String.join(".", entityName, FormConstant.ID_KEY), QCP.in, data.getLong(FormConstant.ID_KEY));
                DynamicObjectCollection query = QueryServiceHelper.query(changeEntityId, queryFieldBuilder.buildSelect(), new QFilter[]{filter});
                if (!query.isEmpty()) {
                    String number = query.get(0).getString(FormConstant.BILL_NO_KEY);
                    throw new ValidationException(StrFormatter.format("已存在暂存或进行中的变更单【单据号：{}】，请勿重复申请。", number));
                }

                DynamicObjectCollection entryColl = data.getDynamicObjectCollection(FormConstant.NCKD_ENTRYENTITY);
                DynamicObject newChangeEntity = EntityHelper.newEntity(changeEntityId);
                HRDynamicObjectUtils.copy(data, newChangeEntity);
                newChangeEntity.set(FormConstant.NCKD_DESCRIPTION, data.getString(FormConstant.DESCRIPTION_KEY));
                newChangeEntity.set(entityId, data);
                newChangeEntity.set(FormConstant.BILL_STATUS_KEY, BillStatus.A.toString());

                // 变更前
                DynamicObjectCollection newEntryColl = newChangeEntity.getDynamicObjectCollection(FormConstant.NCKD_ENTRYENTITY);
                DynamicObjectCollection newOldEntryColl = newChangeEntity.getDynamicObjectCollection("nckd_oldentryentity");
                for (DynamicObject newEntry : newEntryColl) {
                    // 设置源id
                    int seq = newEntry.getInt(FormConstant.SEQ_KEY);
                    List<DynamicObject> filteredEntries = entryColl.stream().filter(entry -> entry.getInt(FormConstant.SEQ_KEY) == seq).collect(Collectors.toList());
                    long originId = 0L;
                    if (!filteredEntries.isEmpty()) {
                        originId = filteredEntries.get(0).getLong(FormConstant.ID_KEY);
                    }
                    newEntry.set("nckd_originid", originId);

                    DynamicObject newOldEntry = newOldEntryColl.addNew();
                    DataEntityPropertyCollection properties = newOldEntry.getDynamicObjectType().getProperties();
                    for (IDataEntityProperty property : properties) {
                        String oldName = property.getName();
                        String name = oldName.replace("old", "");
                        newOldEntry.set(oldName, newEntry.get(name));
                    }
                    newOldEntry.set("nckd_originidold", originId);
                }
                OperationResult operationResult = SaveServiceHelper.saveOperate(changeEntityId, new DynamicObject[]{newChangeEntity}, OperateOption.create());
                if (!operationResult.isSuccess()) {
                    this.getView().showForm(ShowOperExecuteResult.getOperResultForm("载入党政职务履历",this.getView(), operationResult));
                    this.getView().invokeOperation(FormConstant.REFRESH_OP);
                } else {
                    // 自定义确认框按钮名称
                    Map<Integer, String> btnNameMaps = new HashMap<Integer, String>();
                    btnNameMaps.put(2, "我知道了");
                    btnNameMaps.put(6, "进入变更单");
                    ConfirmCallBackListener confirmCallBackListener =
                            new ConfirmCallBackListener("openchange", this);
                    List<Object> successPkIds = operationResult.getSuccessPkIds();
                    this.getPageCache().put("changeid", ConvertUtil.toStr(successPkIds.get(0)));
                    this.getView().showConfirm("提示", "发起暂存状态「变更单」成功，点击\"进入变更单\"按钮或在列表页面点击\"查看变更单\"即可进行数据变更并提交审批。", MessageBoxOptions.OKCancel, ConfirmTypes.Default, confirmCallBackListener, btnNameMaps);
                }
            }
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
        if ("openchange".equals(messageBoxClosedEvent.getCallBackId())
                && messageBoxClosedEvent.getResult() == MessageBoxResult.Yes) {
            String changeEntityFormId = getChangeEntityFormId();
            if (changeEntityFormId != null) {
                BillShowParameter billShowParameter = new BillShowParameter();
                billShowParameter.setFormId(changeEntityFormId);
                billShowParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                String id = this.getPageCache().get("changeid");
                // 设置单据主键ID（关键步骤）
                billShowParameter.setPkId(id);
                this.getView().showForm(billShowParameter);
            }
        }
    }

    /**
     * 获取变更单表单ID
     * 子类需要重写此方法提供具体的变更单表单ID
     *
     * @return 变更单表单ID
     */
    protected abstract String getChangeEntityFormId();

    /**
     * 加载数据
     * 子类必须实现此方法以提供具体的数据加载逻辑
     */
    protected abstract void load();
}