package nckd.jxccl.hr.hstu.plugin.form;

import kd.bos.bill.BillShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.OperateOptionConst;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.Toolbar;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.enums.PerfPlanRoleEnum;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.hr.hstu.business.CreateEvalQuestService;
import nckd.jxccl.hr.hstu.common.HonorStudentConstant;

import java.util.ArrayList;
import java.util.Date;
import java.util.EventObject;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 综合测评问卷-表单插件
 * @author W.Y.C
 * @date 2025/7/13 16:24
 * @version 1.0
 */
public class EvalQuestFormPlugin extends AbstractFormPlugin implements Plugin {

    private final static Log logger = LogFactory.getLog(EvalQuestFormPlugin.class);

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        BillShowParameter bsp = (BillShowParameter) this.getView().getFormShowParameter();
        if (bsp.getStatus() == OperationStatus.EDIT) {
            //查看状态下不会触发业务规则，需要手动处理业务规则的逻辑
            DynamicObject evaluationRule = (DynamicObject)this.getModel().getValue(HonorStudentConstant.NCKD_EVALUATIONRULE);
            Date date = evaluationRule.getDate(HonorStudentConstant.NCKD_BIZYEAR);
            //initValue 方法赋值可避免触发值更新事件（例：检测到您有更改内容，是否不保存直接退出？的检测）
            this.getModel().initValue(HonorStudentConstant.NCKD_BIZYEAR, DateUtil.getYear(date));
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        Toolbar toolbar = this.getView().getControl(FormConstant.NCKD_TOOLBARAP);
        toolbar.addItemClickListener(this);
    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        String itemKey = evt.getItemKey();
        String operationKey = evt.getOperationKey();
        if(HonorStudentConstant.OP_NCKD_REFRESHPEERS.equalsIgnoreCase(itemKey)){
            //刷新同级人员
            DynamicObject dataEntity = this.getModel().getDataEntity();
            DynamicObjectCollection dynamicObjectCollection = dataEntity.getDynamicObjectCollection(HonorStudentConstant.NCKD_MULSELECTORG);
            //弹出选择组织窗口
            FormShowParameter showParameter = new FormShowParameter();
            showParameter.setFormId(HonorStudentConstant.NCKD_EVALQUEST_SELECTORG);
            showParameter.getOpenStyle().setShowType(ShowType.Modal);
            showParameter.setCloseCallBack(new CloseCallBack(this, HonorStudentConstant.NCKD_EVALQUEST_SELECTORG));

            showParameter.setCaption("同级评分人组织范围选择");
            this.getView().showForm(showParameter);
        }
        System.out.println();
    }


    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        String actionId = closedCallBackEvent.getActionId();
        if(HonorStudentConstant.NCKD_EVALQUEST_SELECTORG.equalsIgnoreCase(actionId)){
            //------------- 刷新同级人员 begin -------------
            //获取子页面选择的组织范围
            DynamicObjectCollection mulSelectOrg = (DynamicObjectCollection)closedCallBackEvent.getReturnData();
            if(mulSelectOrg != null) {
                //获取评价规则
                DynamicObject dataEntity = this.getModel().getDataEntity();
                DynamicObject evaluationRule = dataEntity.getDynamicObject(HonorStudentConstant.NCKD_EVALUATIONRULE);
                evaluationRule = BusinessDataServiceHelper.loadSingle(evaluationRule.getLong(HonorStudentConstant.ID_KEY), HonorStudentConstant.EVALUATIONRULE_ENTITYID);

                //获取评价对象
                DynamicObject person = dataEntity.getDynamicObject(HonorStudentConstant.NCKD_EVALPERSON);
                int proportion = evaluationRule.getInt(HonorStudentConstant.NCKD_PROPORTION);
                int upper = evaluationRule.getInt(HonorStudentConstant.NCKD_UPPER);
                int lower = evaluationRule.getInt(HonorStudentConstant.NCKD_LOWER);
                //根据比例计算出的其他部门同级评分人的最小人数（同级评分人下限人数*其他同级评分人比例/100=其他同级评分人下限人数）
                int otherLower = (lower * proportion) / 100;

                //获取当前分录的数据
                DynamicObjectCollection entryColl = this.getModel().getEntryEntity(HonorStudentConstant.NCKD_EVALQUESTENTRY);
                //排除当前已有的领导和上级（避免评分人员重复）
                List<Long> excludePersonList = entryColl.stream().filter(entry -> !entry.getString(HonorStudentConstant.NCKD_PERFPLANROLE).equals(PerfPlanRoleEnum.PEERS.getCode()))
                        .map(entry -> entry.getDynamicObject(HonorStudentConstant.NCKD_PERSON).getLong(FormConstant.ID_KEY)).collect(Collectors.toList());

                //获取同级打分人员
                DynamicObjectCollection freshPeers = CreateEvalQuestService.fetchExpectedScorers(person, mulSelectOrg, excludePersonList, proportion, upper, lower, otherLower, Boolean.FALSE);

                //删除原同级人员
                entryColl.removeIf(dynamicObject -> dynamicObject.getString(HonorStudentConstant.NCKD_PERFPLANROLE).equals(PerfPlanRoleEnum.PEERS.getCode()));
                //添加新生成的同级人员
                entryColl.addAll(freshPeers);
                //将选择的组织范围持久化到表头中（可以追随从什么组织范围选定的人员）
                Object[] mulSelectOrgIds = new Object[mulSelectOrg.size()];
                for (int i = 0; i < mulSelectOrg.size(); i++) {
                    DynamicObject dynamicObject = mulSelectOrg.get(i);
                    DynamicObject baseData = dynamicObject.getDynamicObject(FormConstant.BASEDATAID_KEY);
                    mulSelectOrgIds[i] = baseData.getLong(FormConstant.ID_KEY);
                }
                //多选基础资料赋值
                this.getModel().setValue(HonorStudentConstant.NCKD_MULSELECTORG, mulSelectOrgIds);
                this.getView().updateView(HonorStudentConstant.NCKD_MULSELECTORG);



                // 提前同步缓存（平台不建议调用updateEntryCache，因为苍穹平台默认会在所有action请求结束后自动调用updateCache方法，手动调用可能会引发性能问题）。
                // 但是这里需要提前刷新缓存，确保执行保存前（invokeOperation("save")）数据被刷新能正确保存。该分录数据量不大，出现性能问题的概率不大
                this.getModel().updateEntryCache(entryColl);
                //刷新前端分录数据（一定要在刷新缓存后调用，不然会出现数据不一致的问题）
                this.getView().updateView(HonorStudentConstant.NCKD_EVALQUESTENTRY);


                //持久化到数据库
                OperateOption option = OperateOption.create();
                option.setVariableValue(OperateOptionConst.ISSHOWMESSAGE, Boolean.FALSE+"");
                OperationResult operationResult = this.getView().invokeOperation(FormConstant.SAVE_OP,option);
                if(operationResult.isSuccess()){
                    this.getView().showSuccessNotification("刷新同级人员并保存成功，本次更新人员以蓝色标识");

                    //选中以颜色标识，增加体验性
                    List<Integer> selectRows = new ArrayList<>();
                    for (int i = 0; i < entryColl.size(); i++) {
                        DynamicObject dynamicObject = entryColl.get(i);
                        if(dynamicObject.getLong(FormConstant.ID_KEY) < 1){
                            selectRows.add(i);
                        }
                    }
                    //更新人员以蓝色背景色标识
                    EntryGrid entryGrid = this.getControl(HonorStudentConstant.NCKD_EVALQUESTENTRY);
                    int[] selectedRowArray = selectRows.stream().mapToInt(Integer::intValue).toArray();
                    entryGrid.setRowBackcolor("#add4ff", selectedRowArray);
                }
            }
            //------------- 刷新同级人员 end -------------
        }
    }

}