package nckd.jxccl.hr.psms.plugin.operate.contribution;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.operate.OperateOptionConst;
import kd.bos.entity.operate.interaction.InteractionConfirmResult;
import kd.bos.entity.operate.interaction.InteractionContext;
import kd.bos.entity.operate.interaction.KDInteractionException;
import kd.bos.entity.operate.result.OperateErrorInfo;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.entity.validate.ErrorLevel;
import kd.bos.form.MessageBoxResult;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.enums.psms.ScoreItemEnum;
import nckd.jxccl.base.common.utils.StrFormatter;
import nckd.jxccl.hr.psms.common.ContributionConstant;
import nckd.jxccl.hr.psms.helper.ContributionHelper;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.Map;

/**
 * 年度积分贡献单据保存/提交插件
 * 实体标识：nckd_contribbill
 * @author W.Y.C
 * @date 2025/10/26 20:17
 * @version 1.0
 */
public class ContribBillOpPlugin extends AbstractOperationServicePlugIn implements Plugin {

    private final static String INTERACTION_SPONORE = ContribBillOpPlugin.class.getName();

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        e.addValidator(new AbstractValidator() {

            @Override
            public void validate() {
                //校验参与人数
                Map<String, BigDecimal> scoreConf = ContributionHelper.getScoreConf();
                for (ExtendedDataEntity dataEntity : this.getDataEntities()) {
                    DynamicObject data = dataEntity.getDataEntity();
                    int participants = data.getInt(ContributionConstant.NCKD_PARTICIPANTS);
                    if (participants < 1) {
                        this.addMessage(dataEntity, "参与人数不能小于1；");
                    }else{
                        DynamicObjectCollection entryEntity = data.getDynamicObjectCollection(FormConstant.NCKD_ENTRYENTITY);
                        if(entryEntity.isEmpty()){
                            this.addMessage(dataEntity, "请添加参与人明细；");
                        }else{
                            //校验积分是否超出限制
                            Long id = data.getLong(FormConstant.ID_KEY);
                            Date date = data.getDate(ContributionConstant.NCKD_YEAR);
                            DynamicObject scoreItem = data.getDynamicObject(ContributionConstant.NCKD_SCOREITEM);
                            DynamicObject scoreItemSub = data.getDynamicObject(ContributionConstant.NCKD_SCOREITEMSUB);
                            DynamicObject scoreItemRank = data.getDynamicObject(ContributionConstant.NCKD_SCOREITEMRANK);
                            String scoreItemNumber = scoreItem.getString(FormConstant.NUMBER_KEY);
                            if(ScoreItemEnum.RESEARCH_SCORE.getCode().equalsIgnoreCase(scoreItemNumber)){
                                String key = scoreItem.getLong(FormConstant.ID_KEY)+"-"+scoreItemSub.getLong(FormConstant.ID_KEY)+"-"+scoreItemRank.getLong(FormConstant.ID_KEY);
                                if(!scoreConf.isEmpty() && scoreConf.containsKey(key)) {
                                    BigDecimal maxScore = scoreConf.get(key);
                                    if (maxScore != null && maxScore.compareTo(BigDecimal.ZERO) > 0){
                                        BigDecimal sumScore = BigDecimal.ZERO;
                                        for (DynamicObject entry : entryEntity) {
                                            DynamicObject person = entry.getDynamicObject(ContributionConstant.NCKD_PERSON);
                                            long personId = person.getLong(FormConstant.ID_KEY);
                                            BigDecimal oriScore = entry.getBigDecimal(ContributionConstant.NCKD_ORISCORE);
                                            BigDecimal score = entry.getBigDecimal(ContributionConstant.NCKD_SCORE);
                                            sumScore = sumScore.add(oriScore);
                                        }
                                        if(sumScore.compareTo(maxScore) > 0) {
                                            this.addFatalErrorMessage(dataEntity, StrFormatter.format("当前单据总积分【{}】超出限制积分【{}】。请重新填写；",
                                                    sumScore.setScale(2, RoundingMode.HALF_UP),
                                                    maxScore.setScale(2, RoundingMode.HALF_UP)));
                                        }
                                    }
                                }
                            }


                           /* List<ContributionHelper.ScoreItemValidScore> scoreItemValidScoreList = new ArrayList<>(entryEntity.size());
                            for (DynamicObject entry : entryEntity) {
                                DynamicObject person = entry.getDynamicObject(ContributionConstant.NCKD_PERSON);
                                BigDecimal oriScore = entry.getBigDecimal(ContributionConstant.NCKD_ORISCORE);
                                ContributionHelper.ScoreItemValidScore scoreItemValidScore = new ContributionHelper.ScoreItemValidScore(
                                        person.getLong(FormConstant.ID_KEY),
                                        scoreItem.getLong(FormConstant.ID_KEY),
                                        scoreItemSub.getLong(FormConstant.ID_KEY),
                                        scoreItemRank != null ? scoreItemRank.getLong(FormConstant.ID_KEY) : null);
                                scoreItemValidScore.setCurrentScore(oriScore);
                                scoreItemValidScoreList.add(scoreItemValidScore);
                            }
                            if (!scoreItemValidScoreList.isEmpty()) {
                                ContributionHelper.getScoreItemValidScore(scoreItemValidScoreList, date, id);
                                for (DynamicObject entry : entryEntity) {
                                    DynamicObject person = entry.getDynamicObject(ContributionConstant.NCKD_PERSON);
                                    long personId = person.getLong(FormConstant.ID_KEY);
                                    BigDecimal oriScore = entry.getBigDecimal(ContributionConstant.NCKD_ORISCORE);
                                    BigDecimal score = entry.getBigDecimal(ContributionConstant.NCKD_SCORE);
                                    for (ContributionHelper.ScoreItemValidScore scoreItemValidScore : scoreItemValidScoreList) {
                                        if(Objects.equals(scoreItemValidScore.getPersonId(),personId)){
                                            if(scoreItemValidScore.getValidScore() != null){
                                                if(score.compareTo(scoreItemValidScore.getValidScore()) > 0){
                                                    this.addMessage(dataEntity, StrFormatter.format("参与人【{}】的录入积分【{}】超出限制积分【{}】。请重新填写“原始积分”，系统将会自动重算“录入积分”；",
                                                            person.getString(FormConstant.NAME_KEY),
                                                            score.setScale(2, RoundingMode.HALF_UP),
                                                            scoreItemValidScore.getValidScore().setScale(2, RoundingMode.HALF_UP)));
                                                }
                                            }
                                        }
                                    }
                                }
                            }*/
                        }
                    }
                }
            }
        });
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        //来源导入
        String variableValue = this.getOption().getVariableValue("importtype", StringUtils.EMPTY);
        if(StringUtils.isBlank(variableValue)) {
            for (DynamicObject data : e.getDataEntities()) {
                int participants = data.getInt(ContributionConstant.NCKD_PARTICIPANTS);
                DynamicObjectCollection dynamicObjectCollection = data.getDynamicObjectCollection(FormConstant.NCKD_ENTRYENTITY);
                if (participants != dynamicObjectCollection.size()) {
                    e.cancel = !this.showInteractionMessage(participants, dynamicObjectCollection.size());
                }
            }
        }
    }


    private boolean showInteractionMessage(int participants,int size) {
        //交互式操作提示
        // 检查是否为回调：避免死循环
        String confirmResultString = this.getOption().getVariableValue(OperateOptionConst.INTERACTIONCONFIRMRESULT, "");
        InteractionConfirmResult confirmResult = InteractionConfirmResult.fromJsonString(confirmResultString);
        if (confirmResult.getResults().containsKey(INTERACTION_SPONORE)) {
            // 已是回调，直接返回结果
            MessageBoxResult result = MessageBoxResult.valueOf(confirmResult.getResults().get(INTERACTION_SPONORE));
            return result == MessageBoxResult.Yes;
        }

        // 首次执行：抛出交互异常
        InteractionContext interactionContext = new InteractionContext();
        interactionContext.setSimpleMessage("参与人数不一致");
        OperateErrorInfo errorInfo = new OperateErrorInfo();
        errorInfo.setMessage(StrFormatter.format("参与人数【{}】与参与人明细【{}】不匹配", participants,size));
        errorInfo.setLevel(ErrorLevel.Warning);
        interactionContext.addOperateInfo(errorInfo);
        throw new KDInteractionException(INTERACTION_SPONORE, interactionContext);
    }
}