package nckd.jxccl.hr.hdm.plugin.form.transfer;


import kd.bos.bill.OperationStatus;
import kd.bos.coderule.api.CodeRuleInfo;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.QueryEntityType;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.ConfirmTypes;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.MetadataServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.hr.hbp.business.servicehelper.HRQueryEntityHelper;
import kd.hr.hbp.common.util.HRDynamicObjectUtils;
import kd.hr.hbp.common.util.HRObjectUtils;
import kd.hr.hbp.common.util.HRStringUtils;
import kd.sdk.hr.hdm.common.enums.reg.RegBillStatusEnum;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.hr.hdm.common.transfer.TransferApplyBillConstant;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;

/**
 * 调动基础单据表单插件
 * @entity: nckd_hdm_transferbase_ext
 * @author: jtd
 * @date: 2026/1/4 15:34
 */
public class TransferApplyBillFormPlugin extends AbstractFormPlugin {
    Log log = LogFactory.getLog(TransferApplyBillFormPlugin.class);

    private static final HRBaseServiceHelper transferApplyHelper = HRBaseServiceHelper.create(TransferApplyBillConstant.HDM_TRANSFERAPPLY);
    private static final HRBaseServiceHelper chgActionHelper = HRBaseServiceHelper.create(TransferApplyBillConstant.HPFS_CHGACTION_ENTITY);

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);

        DynamicObject dataEntity = getModel().getDataEntity();
        String billStatus = dataEntity.getString(TransferApplyBillConstant.BILL_STATUS_KEY);
        // 如果不是已提交或审批中
        if (!HRStringUtils.equalsAny(billStatus, RegBillStatusEnum.ALREADYSUBMIT.getCode(), RegBillStatusEnum.APPROVING.getCode())) {
            return;
        }

        // 获取当前登录用户
        long currentUserId = UserServiceHelper.getCurrentUserId();
        String selectFields = QueryFieldBuilder.create()
                .add(TransferApplyBillConstant.ID_KEY)
                .add(TransferApplyBillConstant.NCKD_TRANSFERADDR_KEY)
                .add(TransferApplyBillConstant.NCKD_TRANSFERZIP_KEY)
                .add(TransferApplyBillConstant.NCKD_TRANSFERCONT_KEY)
                .add(TransferApplyBillConstant.NCKD_TRANSFERTEL_KEY)
                .buildSelect();
        // 查询最近一笔调动单修改人是该用户的数据
        DynamicObject transferApplyDy = transferApplyHelper.queryOriginalOne(selectFields, new QFilter[]{new QFilter(TransferApplyBillConstant.BILL_STATUS_KEY, QCP.equals, RegBillStatusEnum.APPROVEPASSED.getCode()).and(TransferApplyBillConstant.MODIFIER_KEY, QCP.equals, currentUserId)}, String.format("%s desc", TransferApplyBillConstant.MODIFY_TIME_KEY));
        if (HRObjectUtils.isEmpty(transferApplyDy)) {
            return;
        }

        getModel().setValue(TransferApplyBillConstant.NCKD_TRANSFERADDR_KEY, transferApplyDy.get(TransferApplyBillConstant.NCKD_TRANSFERADDR_KEY));
        getModel().setValue(TransferApplyBillConstant.NCKD_TRANSFERZIP_KEY, transferApplyDy.get(TransferApplyBillConstant.NCKD_TRANSFERZIP_KEY));
        getModel().setValue(TransferApplyBillConstant.NCKD_TRANSFERCONT_KEY, transferApplyDy.get(TransferApplyBillConstant.NCKD_TRANSFERCONT_KEY));
        getModel().setValue(TransferApplyBillConstant.NCKD_TRANSFERTEL_KEY, transferApplyDy.get(TransferApplyBillConstant.NCKD_TRANSFERTEL_KEY));
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);

        String operateKey = getView().getFormShowParameter().getCustomParam("OperateKey");
        if (HRStringUtils.isNotBlank(operateKey)) {
            switch (operateKey) {
                case TransferApplyBillConstant.SECONDARY_UNIT_TRANSFER_OP:
                    // 二级单位内调拨
                    getModel().setValue(TransferApplyBillConstant.AFFACTION_KEY, chgActionHelper.loadOne(new QFilter[]{new QFilter(TransferApplyBillConstant.NUMBER_KEY, QCP.equals, "1020_JT")}));
                    break;
                case TransferApplyBillConstant.CROSS_SECONDARY_UNIT_TRANSFER_OP:
                    // 跨二级单位调动
                    getModel().setValue(TransferApplyBillConstant.AFFACTION_KEY, chgActionHelper.loadOne(new QFilter[]{new QFilter(TransferApplyBillConstant.NUMBER_KEY, QCP.equals, "1010_JT")}));

            }
        }

        // 获取当前登录用户
        long currentUserId = UserServiceHelper.getCurrentUserId();
        // 查询最近一笔调动单创建人是该用户的数据
        DynamicObject transferApplyDy = transferApplyHelper.queryOriginalOne(String.join(",", TransferApplyBillConstant.ID_KEY, TransferApplyBillConstant.NCKD_TRANSFERNO_KEY), new QFilter[]{new QFilter(TransferApplyBillConstant.BILL_STATUS_KEY, QCP.equals, RegBillStatusEnum.APPROVEPASSED.getCode()).and(TransferApplyBillConstant.CREATOR_KEY, QCP.equals, currentUserId)}, String.format("%s desc", TransferApplyBillConstant.MODIFY_TIME_KEY));
        if (HRObjectUtils.isEmpty(transferApplyDy)) {
            return;
        }

        // 设置调令号
        getModel().setValue(TransferApplyBillConstant.NCKD_TRANSFERNO_KEY, transferApplyDy.get(TransferApplyBillConstant.NCKD_TRANSFERNO_KEY));
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);

        FormOperate formOperate = (FormOperate) args.getSource();
        String operateKey = formOperate.getOperateKey();
        switch (operateKey){
            case TransferApplyBillConstant.SAVE_OP:
                if (!HRStringUtils.equals(Boolean.TRUE.toString(), getView().getPageCache().get(TransferApplyBillConstant.FAMILY_RELATION_CONFIRM_PAGE_CACHE))) {
                    validateFamilyRelation(args);
                }

                List<Boolean> booleanList = new ArrayList<>();
                if (OperationStatus.ADDNEW.equals(getView().getFormShowParameter().getStatus())) {
                    // 如果是新增
                    booleanList.add(true);
                } else {
                    // 判断变更的属性是否影响调令顺序号生成
                    DynamicObject transferApplyDy = transferApplyHelper.loadOne(String.join(",", TransferApplyBillConstant.PLANDATE_KEY, TransferApplyBillConstant.NCKD_TRANSFERNO_KEY), getModel().getValue(TransferApplyBillConstant.ID_KEY));
                    boolean isChange;
                    Object oldPlanDate = transferApplyDy.get(TransferApplyBillConstant.PLANDATE_KEY);
                    Object newPlanDate = getModel().getValue(TransferApplyBillConstant.PLANDATE_KEY);
                    isChange = compareValues(oldPlanDate, newPlanDate);
                    booleanList.add(isChange);

                    Object oldTransferNo = transferApplyDy.get(TransferApplyBillConstant.NCKD_TRANSFERNO_KEY);
                    Object newTransferNo = getModel().getValue(TransferApplyBillConstant.NCKD_TRANSFERNO_KEY);
                    isChange = isChange || compareValues(oldTransferNo, newTransferNo);
                    booleanList.add(isChange);
                }

                if (booleanList.stream().allMatch(Boolean::booleanValue)) {
                    getModel().setValue(TransferApplyBillConstant.NCKD_GEN_SERIALNO_KEY, true);
                } else {
                    getModel().setValue(TransferApplyBillConstant.NCKD_GEN_SERIALNO_KEY, false);
                }
        }
    }

    private Boolean compareValues(Object newValue, Object oldValue) {
        if (HRObjectUtils.isEmpty(oldValue) && HRObjectUtils.isEmpty(newValue)) {
            return false;
        } else if ((HRObjectUtils.isEmpty(oldValue) && !HRObjectUtils.isEmpty(newValue)) || (!HRObjectUtils.isEmpty(oldValue) && HRObjectUtils.isEmpty(newValue))) {
            return true;
        } else {
            return !HRDynamicObjectUtils.compareValues(oldValue, newValue);
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        super.afterDoOperation(afterDoOperationEventArgs);

        String operateKey = afterDoOperationEventArgs.getOperateKey();
        switch (operateKey){
            case TransferApplyBillConstant.SAVE_OP:
                OperationResult operationResult = afterDoOperationEventArgs.getOperationResult();
                if (!operationResult.isSuccess() || operationResult.getSuccessPkIds().isEmpty() || !getModel().getDataEntity().getBoolean(TransferApplyBillConstant.NCKD_GEN_SERIALNO_KEY)) {
                    break;
                }

                generateTransferSerialNo();
        }
    }

    /**
     * 生成调令顺序号
     */
    private void generateTransferSerialNo() {
        DynamicObject dataEntity = getModel().getDataEntity();
        CodeRuleInfo codeRuleInfo = CodeRuleServiceHelper.getCodeRule(dataEntity.getDataEntityType().getName(), dataEntity, dataEntity.getString(String.join(".", TransferApplyBillConstant.ORG_KEY, TransferApplyBillConstant.ID_KEY)));
        if (HRObjectUtils.isEmpty(codeRuleInfo) || !HRStringUtils.equals("调令号生成规则", codeRuleInfo.getName())) {
            dataEntity.set(TransferApplyBillConstant.NCKD_TRANSFER_SERIALNO_KEY, null);
        } else {
            dataEntity.set(TransferApplyBillConstant.NCKD_TRANSFER_SERIALNO_KEY, CodeRuleServiceHelper.getNumber(codeRuleInfo, dataEntity));
        }
        SaveServiceHelper.save(new DynamicObject[]{dataEntity});
    }

    private void validateFamilyRelation(BeforeDoOperationEventArgs args) {
        DynamicObject dataEntity = getModel().getDataEntity();
        // 获取调出公司
        DynamicObject bcompany = dataEntity.getDynamicObject(TransferApplyBillConstant.BCOMPANY_KEY);
        // 获取调入公司
        DynamicObject acompany = dataEntity.getDynamicObject(TransferApplyBillConstant.ACOMPANY_KEY);
        // 判断是否跨二级单位调动
        if (HRDynamicObjectUtils.compareValues(bcompany, acompany)) {
            return;
        }

        // 获取调动员工
        DynamicObject transferEmployee = dataEntity.getDynamicObject(TransferApplyBillConstant.BB_EM_TID);
        // 获取调入公司内员工近亲属关系
        QueryEntityType queryEntityType = (QueryEntityType) MetadataServiceHelper.getDataEntityType(TransferApplyBillConstant.NCKD_HRPI_GETFAMILYRELATION_ENTITY);
        // 查询 员工编码、员工姓名、亲属关系ID、亲属关系编码、亲属关系名称
        String queryFields = QueryFieldBuilder.create().add(TransferApplyBillConstant.EMPLOYEE_EMPNUMBER)
                .add(TransferApplyBillConstant.EMPLOYEE_NAME)
                .add(TransferApplyBillConstant.NCKD_RELATION_ID)
                .add(TransferApplyBillConstant.NCKD_RELATION_NUMBER)
                .add(TransferApplyBillConstant.NCKD_RELATION_NAME)
                .buildSelect();
        // 过滤 所属公司为调出公司 并且 近亲属员工为调动员工
        QFilter qFilter = new QFilter(String.join(".", TransferApplyBillConstant.HRPI_EMPPOSORGREL, TransferApplyBillConstant.COMPANY_KEY, TransferApplyBillConstant.NUMBER_KEY), QCP.equals, acompany.getString(TransferApplyBillConstant.NUMBER_KEY))
                .and(String.join(".", TransferApplyBillConstant.NCKD_EMPID_KEY, TransferApplyBillConstant.NUMBER_KEY), QCP.equals, transferEmployee.getString(TransferApplyBillConstant.NUMBER_KEY));
        DynamicObjectCollection familyRelationDys = HRQueryEntityHelper.getInstance().getQueryDyoColl(queryEntityType, queryFields, new QFilter[]{qFilter}, TransferApplyBillConstant.EMPLOYEE_EMPNUMBER);
        List<String> errorList = new ArrayList<String>();
        for (DynamicObject familyRelationDy : familyRelationDys) {
            // 获取近亲属员工姓名
            String empName = familyRelationDy.getString(TransferApplyBillConstant.EMPLOYEE_NAME);
            // 获取近亲属名称
            String relationName = familyRelationDy.getString(TransferApplyBillConstant.NCKD_RELATION_NAME);
            errorList.add(String.format("亲属姓名：%s，亲属关系：%s", empName, relationName));
        }

        if (!errorList.isEmpty()) {
            getView().showConfirm("近亲属关系", String.join(System.lineSeparator(), errorList), MessageBoxOptions.OKCancel, ConfirmTypes.Default, new ConfirmCallBackListener(TransferApplyBillConstant.FAMILY_RELATION_CONFIRM_CALLBACK));
            args.setCancel(true);
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
        super.confirmCallBack(messageBoxClosedEvent);

        switch (messageBoxClosedEvent.getCallBackId()) {
            case TransferApplyBillConstant.FAMILY_RELATION_CONFIRM_CALLBACK:
                if (messageBoxClosedEvent.getResult() == MessageBoxResult.Yes) {
                    getView().getPageCache().put(TransferApplyBillConstant.FAMILY_RELATION_CONFIRM_PAGE_CACHE, Boolean.TRUE.toString());
                    getView().invokeOperation(TransferApplyBillConstant.SAVE_OP);
                    getView().getPageCache().remove(TransferApplyBillConstant.FAMILY_RELATION_CONFIRM_PAGE_CACHE);
                }
        }
    }
}
