package nckd.jxccl.hrmp.hbpm.plugin.form.hr;

import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.ConfirmTypes;
import kd.bos.form.IPageCache;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeClosedEvent;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.hr.hbp.common.util.HRStringUtils;
import nckd.jxccl.hrmp.hbpm.business.hr.PositionBillService;
import nckd.jxccl.hrmp.hbpm.common.hr.PositionBillConstant;

import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;

/**
 * 岗位申请-新增岗位表单插件
 * @author: jtd
 * @date: 2025-11-05 15:32
 */
public class PosBillEntryAddFormPlugin extends AbstractFormPlugin {

    /**
     * 编码规则的编码
     */
    private static final String CODERULE_NUMBER = "codeRuleNumber";

    /**
     * 保存结果标识
     */
    private static final String SAVE_RESULT = "saveResult";

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

        getPageCache().put("paramsChangeSetNumber", Boolean.FALSE.toString());
        // 如果是新增
        long entityId = getModel().getDataEntity().getLong(PositionBillConstant.ID_KEY);
        if (entityId == 0L) {
            Long billId = getView().getFormShowParameter().getCustomParam("billid");
            getModel().setValue(PositionBillConstant.NCKD_BILLID, billId);
            getPageCache().put("initFlag", Boolean.TRUE.toString());
        }

        // 设置生效时间
        long positionBsedTime = getView().getFormShowParameter().getCustomParam("position_bsed");
        getModel().setValue(PositionBillConstant.NCKD_BSED, new Date(positionBsedTime));
        getModel().setValue(PositionBillConstant.ENABLE, EnableEnum.YES.getCode());

        // 设置岗位编码
        if (HRStringUtils.isEmpty(getModel().getDataEntity().getString(PositionBillConstant.NUMBER_KEY))) {
            setPositionNumber(PositionBillService.getPositionHrDy(getModel().getDataEntity()));
        } else {
            setPositionNumberEnable();
        }
        getPageCache().put("paramsChangeSetNumber", Boolean.TRUE.toString());

        // 新增的时候生成岗位ID
        String positionIdKey = String.format("%s_id", PositionBillConstant.NCKD_POSITION);
        long positionId = getModel().getDataEntity().getLong(positionIdKey);
        if (positionId == 0L) {
            positionId = ORM.create().genLongId(PositionBillConstant.HBPM_POSITIONHR);
            getModel().setValue(positionIdKey, positionId);
        }
    }

    private void setPositionNumberEnable() {
        DynamicObject org = getModel().getDataEntity().getDynamicObject(PositionBillConstant.NCKD_ORG);
        if (org == null) {
            getView().setEnable(Boolean.valueOf(false), PositionBillConstant.NUMBER_KEY);
            return;
        }
        long orgid = org.getLong(PositionBillConstant.ID_KEY);
        DynamicObject positionHrDy = PositionBillService.getPositionHrDy(getModel().getDataEntity());
        boolean cudeRule = CodeRuleServiceHelper.isExist(PositionBillConstant.HBPM_POSITIONHR, positionHrDy, String.valueOf(orgid));
        if (cudeRule && !CodeRuleServiceHelper.isModifiable(PositionBillConstant.HBPM_POSITIONHR, positionHrDy, String.valueOf(org.getLong(PositionBillConstant.ID_KEY)))) {
            getView().setEnable(Boolean.valueOf(false), PositionBillConstant.NUMBER_KEY);
        }
    }

    private void setPositionNumber(DynamicObject positionHrDy) {
        // 组织体系管理组织
        DynamicObject org = getModel().getDataEntity().getDynamicObject(PositionBillConstant.NCKD_ORG);
        if (org == null) {
            getView().setEnable(Boolean.FALSE, PositionBillConstant.NUMBER_KEY);
            return;
        }

        String number = getModel().getDataEntity().getString(PositionBillConstant.NUMBER_KEY);
        if (HRStringUtils.isNotEmpty(number) && !HRStringUtils.equals(number, getView().getPageCache().get(CODERULE_NUMBER))) {
            return;
        }

        long orgid = org.getLong(PositionBillConstant.ID_KEY);
        boolean cudeRule = CodeRuleServiceHelper.isExist(PositionBillConstant.HBPM_POSITIONHR, positionHrDy, String.valueOf(orgid));
        if (cudeRule) {
            if (CodeRuleServiceHelper.isModifiable(PositionBillConstant.HBPM_POSITIONHR, positionHrDy, String.valueOf(org.getLong(PositionBillConstant.ID_KEY)))) {
                String positionNumber = CodeRuleServiceHelper.getNumber(PositionBillConstant.HBPM_POSITIONHR, positionHrDy, String.valueOf(org.getLong(PositionBillConstant.ID_KEY)));
                HRBaseServiceHelper hrBaseServiceHelper = new HRBaseServiceHelper(PositionBillConstant.HBPM_POSITIONHR);
                QFilter qFilter = new QFilter(PositionBillConstant.NUMBER_KEY, QCP.equals, positionNumber);
                if (!hrBaseServiceHelper.isExists(qFilter)) {
                    getModel().setValue(PositionBillConstant.NUMBER_KEY, positionNumber);
                    getView().getPageCache().put(CODERULE_NUMBER, positionNumber);
                } else {
                    setPositionNumber(positionHrDy);
                }
            } else {
                getView().setEnable(Boolean.FALSE, PositionBillConstant.NUMBER_KEY);
            }
        } else {
            getModel().setValue(PositionBillConstant.NUMBER_KEY, null);
            getView().getPageCache().put(CODERULE_NUMBER, "");
            getView().setEnable(Boolean.TRUE, PositionBillConstant.NUMBER_KEY);
        }
    }

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

        // 设置岗位ID
        long positionId = getModel().getDataEntity().getLong(PositionBillConstant.ID_KEY);
        if (positionId == 0L) {
            getModel().setValue(PositionBillConstant.ID_KEY, ORM.create().genLongId(PositionBillConstant.HBPM_POSITIONHR));
        }

        // 设置上级岗位变更前的数据到页面缓存中
        DynamicObject parentPosition = getModel().getDataEntity().getDynamicObject(PositionBillConstant.NCKD_PARENT);
        if (parentPosition != null) {
            getView().getPageCache().put("beforeParentPositionId", parentPosition.getString(PositionBillConstant.ID_KEY));
        }

        // 取消变更提示
        getModel().setDataChanged(false);
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs eventArgs) {
        super.afterDoOperation(eventArgs);
        OperationResult result = eventArgs.getOperationResult();
        if (!ObjectUtils.isEmpty(result) && !result.isSuccess()) {
            return;
        }
        IPageCache parentPageCache = getView().getParentView().getPageCache();
        String operateKey = eventArgs.getOperateKey();
        if (HRStringUtils.equals(operateKey, PositionBillConstant.SAVE_AND_NEW_OP) || HRStringUtils.equals(operateKey, PositionBillConstant.SAVE_OP)) {
            String beforeParentPositionId = getView().getPageCache().get("beforeParentPositionId");
            String addPositionParentChange = Boolean.FALSE.toString();
            DynamicObject parentPosition = getModel().getDataEntity().getDynamicObject(PositionBillConstant.NCKD_PARENT);
            if (parentPosition != null) {
                String afterParentOrgId = parentPosition.getString(PositionBillConstant.ID_KEY);
                if (!HRStringUtils.equals(beforeParentPositionId, afterParentOrgId)) {
                    addPositionParentChange = Boolean.TRUE.toString();
                }
                parentPageCache.put("addPositionParentChange", addPositionParentChange);
                parentPageCache.put("parentId", afterParentOrgId);
            }
            Map<String, String> map = new HashMap<>();
            DynamicObject dataEntity = getModel().getDataEntity();
            map.put("positionId", dataEntity.getString(String.format("%s_id", PositionBillConstant.NCKD_POSITION)));
            map.put("name", dataEntity.getString(PositionBillConstant.NAME_KEY));
            map.put("id", dataEntity.getString(PositionBillConstant.ID_KEY));
            getView().getPageCache().put("saveResult", Boolean.TRUE.toString());
            getView().returnDataToParent(map);
        }
    }

    @Override
    public void beforeClosed(BeforeClosedEvent event) {
        super.beforeClosed(event);

        String isCancelOverFlag = getView().getPageCache().get("isclose");
        if (HRStringUtils.isNotEmpty(isCancelOverFlag) && Boolean.TRUE.toString().equals(isCancelOverFlag)) {
            getModel().setDataChanged(false);
            getView().getPageCache().put("isclose", Boolean.FALSE.toString());
            return;
        }

        boolean dataChanged = getModel().getDataChanged();
        if (dataChanged) {
            event.setCancel(true);
            ConfirmCallBackListener confirmCallBacks = new ConfirmCallBackListener("close_addbill", this);
            Map<Integer, String> btnNameMaps = new HashMap<>();
            btnNameMaps.put(MessageBoxResult.Cancel.getValue(), "返回编辑");
            btnNameMaps.put(MessageBoxResult.Yes.getValue(), "直接退出");
            MessageBoxOptions options = MessageBoxOptions.OKCancel;
            String msg = "检测到您有更改内容，是否不保存直接退出？若不保存，将丢失这些更改。";
            getView().showConfirm(msg, getModel().getChangeDesc(), options, ConfirmTypes.Save, confirmCallBacks, btnNameMaps);
        } else {
            String codeRuleNumber = getView().getPageCache().get(CODERULE_NUMBER);
            if (!StringUtils.isEmpty(codeRuleNumber)) {
                DynamicObject org = getModel().getDataEntity().getDynamicObject(PositionBillConstant.ORG_KEY);
                if (org == null) {
                    return;
                }
                String saveResult = getView().getPageCache().get(SAVE_RESULT);
                if (!Boolean.TRUE.toString().equals(saveResult)) {
                    long orgId = org.getLong(PositionBillConstant.ID_KEY);
                    DynamicObject positionHrDy = PositionBillService.getPositionHrDy(getModel().getDataEntity());
                    CodeRuleServiceHelper.recycleNumber(PositionBillConstant.HBPM_POSITIONHR, positionHrDy, String.valueOf(orgId), codeRuleNumber);
                }
            }
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent event) {
        super.confirmCallBack(event);
        if ("close_addbill".equals(event.getCallBackId()) && event.getResult() != MessageBoxResult.Cancel) {
            String codeRuleNumber = getView().getPageCache().get(CODERULE_NUMBER);
            if (!StringUtils.isEmpty(codeRuleNumber)) {
                DynamicObject org = getModel().getDataEntity().getDynamicObject(PositionBillConstant.ORG_KEY);
                if (org == null) {
                    return;
                }
                String saveResult = getView().getPageCache().get(SAVE_RESULT);
                if (!Boolean.TRUE.toString().equals(saveResult)) {
                    long orgId = org.getLong(PositionBillConstant.ID_KEY);
                    DynamicObject positionHrDy = PositionBillService.getPositionHrDy(getModel().getDataEntity());
                    CodeRuleServiceHelper.recycleNumber(PositionBillConstant.HBPM_POSITIONHR, positionHrDy, String.valueOf(orgId), codeRuleNumber);
                }
            }
            getView().getPageCache().put("isclose", Boolean.TRUE.toString());
            getView().invokeOperation("close");
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs changedArgs) {
        String fieldKey = changedArgs.getProperty().getName();
        boolean isGetNumber = true;
        if (PositionBillConstant.NCKD_ESTDATE.equals(fieldKey)) {
            setEstablishmentDateToBsed((Date)changedArgs.getChangeSet()[0].getNewValue());
        }
    }

    /**
     * 设置设立日期到生效日期
     * @param date
     */
    private void setEstablishmentDateToBsed(Date date) {
        if (date != null) {
            getModel().setValue(PositionBillConstant.NCKD_BSED, date);
        }
    }

}
