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

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import kd.bos.bill.OperationStatus;
import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.ILocaleString;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.property.BasedataProp;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.events.ClickListener;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.servicehelper.basedata.BaseDataServiceHelper;
import kd.hr.hbp.common.util.HRStringUtils;
import nckd.jxccl.hrmp.hbpm.business.hr.service.impl.PositionBillServiceHelper;
import nckd.jxccl.hrmp.hbpm.business.hr.utils.PositionBillUtil;
import nckd.jxccl.hrmp.hbpm.common.hr.PositionBillConstant;

import java.util.EventObject;
import java.util.Map;

/**
 * 岗位申请单分录表单插件
 * @from: kd.hr.homs.formplugin.web.orgbatch.AdminOrgBatchDetailPlugin
 * @author: jtd
 * @date: 2025-11-04 9:35
 */
public class PositionBillEntryFormPlugin extends AbstractFormPlugin implements ClickListener, BeforeF7SelectListener {

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

        FormShowParameter formShowParameter = getView().getFormShowParameter();
        setOrg();
        setDefaultValue();
        if (formShowParameter.getCustomParam(PositionBillConstant.CP_SEQUENCE) != null && getModel().getDataEntity(true).getInt(PositionBillConstant.NCKD_SEQUENCE) == 0) {
            getModel().setValue(PositionBillConstant.NCKD_SEQUENCE, formShowParameter.getCustomParam(PositionBillConstant.CP_SEQUENCE));
        }
    }

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

        getModel().setDataChanged(false);
        OperationStatus status = getView().getFormShowParameter().getStatus();
        if (OperationStatus.ADDNEW.equals(status) || OperationStatus.EDIT.equals(status)) {
            getView().setEnable(Boolean.TRUE, PositionBillConstant.NCKD_ORG_KEY);
        }
    }

    /**
     * 设置单头ID
     */
    private void setDefaultValue() {
        Object billId = getView().getFormShowParameter().getCustomParam(PositionBillConstant.CP_BILLID);
        if (billId != null) {
            getModel().setValue(PositionBillConstant.NCKD_BILLID, Long.parseLong(String.valueOf(billId)));
        }
    }

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

        BasedataEdit adminorg = getView().getControl(PositionBillConstant.NCKD_ADMINORG);
        adminorg.addBeforeF7SelectListener(this);
        BasedataEdit position = getView().getControl(PositionBillConstant.NCKD_POSITION_KEY);
        position.addBeforeF7SelectListener(this);
        BasedataEdit parent = getView().getControl(PositionBillConstant.NCKD_PARENT);
        parent.addBeforeF7SelectListener(this);
        addItemClickListeners(PositionBillConstant.NCKD_ADVCONTOOLBARAP11_KEY);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent beforeF7SelectEvent) {
        String fieldKey = beforeF7SelectEvent.getProperty().getName();
        DynamicObject orgDy = getModel().getDataEntity().getDynamicObject(PositionBillConstant.NCKD_ORG);
        MainEntityType entityType = EntityMetadataCache.getDataEntityType(getView().getEntityId());
        IDataEntityProperty property = entityType.getAllFields().get(fieldKey);
        Boolean baseDataCtrl = BaseDataServiceHelper.checkBaseDataCtrl(((BasedataProp) property).getBaseEntityId());
        if (baseDataCtrl && orgDy == null && !HRStringUtils.equals(PositionBillConstant.NCKD_PARENT, fieldKey) && !HRStringUtils.equals(PositionBillConstant.NCKD_ORG, fieldKey)) {
            getView().showTipNotification("请先选择组织体系管理组织。");
            beforeF7SelectEvent.setCancel(true);
        } else {
            switch (fieldKey) {
                case PositionBillConstant.NCKD_ADMINORG:
                    // 替换组织F7模板
                    beforeF7SelectEvent.getFormShowParameter().setFormId(PositionBillConstant.HAOS_ORGBATCHTREELISTF7_ENTITY);
                    beforeF7SelectEvent.getFormShowParameter().setCaption("行政组织");
                    break;
                case PositionBillConstant.NCKD_POSITION_KEY:
                    // 替换岗位F7模板
                    beforeF7SelectEvent.getFormShowParameter().setFormId(PositionBillConstant.NCKD_HBPM_POSORGTREELISTF_ENTITY);
                    beforeF7SelectEvent.getFormShowParameter().setCaption("岗位");
                    break;
                case PositionBillConstant.NCKD_PARENT:
                    DynamicObject positionObject = (DynamicObject) getModel().getValue(PositionBillConstant.NCKD_POSITION_KEY);
                    PositionBillServiceHelper.setParentFilter(PositionBillUtil.getView(getView(), PositionBillConstant.NCKD_POSITIONBILL_ENTITY), positionObject, beforeF7SelectEvent);
                    beforeF7SelectEvent.getFormShowParameter().setCaption("上级岗位");
                    beforeF7SelectEvent.getFormShowParameter().setFormId(PositionBillConstant.NCKD_HBPM_POSORGTREELISTF_ENTITY);
            }

        }
    }

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


        OperationResult result = afterDoOperationEventArgs.getOperationResult();
        if (ObjectUtils.isEmpty(result) || result.isSuccess()) {
            if (HRStringUtils.equals(afterDoOperationEventArgs.getOperateKey(), PositionBillConstant.SAVE_OP) || HRStringUtils.equals(afterDoOperationEventArgs.getOperateKey(), PositionBillConstant.SAVE_AND_NEW_OP)) {
                getView().returnDataToParent(getModel().getDataEntity().getLong(PositionBillConstant.ID_KEY));
            }
        }
    }

    public void itemClick(ItemClickEvent evt) {
        super.itemClick(evt);
        if (PositionBillConstant.NCKD_TB_DEL_KEY.equals(evt.getItemKey())) {
            EntryGrid posDutyEntryGrid = getView().getControl(PositionBillConstant.NCKD_POSDUTY_ENTRY_ENTITY_KEY);
            int length = posDutyEntryGrid.getSelectRows().length;
            if (length > 0) {
                ConfirmCallBackListener deleteEntryCallBackListener = new ConfirmCallBackListener(PositionBillConstant.CB_DEL_ROW, this);
                getView().showConfirm(String.format("你已选中%s条记录，删除后将不可恢复，是否继续？", length), MessageBoxOptions.OKCancel, deleteEntryCallBackListener);
            } else {
                getView().showTipNotification("请选中需要操作的行。");
            }
        }

    }

    public void confirmCallBack(MessageBoxClosedEvent event) {
        super.confirmCallBack(event);
        if (PositionBillConstant.CB_DEL_ROW.equals(event.getCallBackId()) && event.getResult().getValue() == MessageBoxResult.Yes.getValue()) {
            EntryGrid strategyEntryGrid = getView().getControl(PositionBillConstant.NCKD_POSDUTY_ENTRY_ENTITY_KEY);
            int[] rows = strategyEntryGrid.getSelectRows();
            getModel().deleteEntryRows(PositionBillConstant.NCKD_POSDUTY_ENTRY_ENTITY_KEY, rows);
        }

    }

    /**
     * 设置组织体系管理组织
     */
    private void setOrg() {
        String entityId = getView().getEntityId();
        if (PositionBillConstant.NCKD_POSBILLENTRYADD_ENTITY.equals(entityId) || PositionBillConstant.NCKD_POSBILLENTRYCHANGE_ENTITY.equals(entityId)) {
            Object orgParam = getView().getFormShowParameter().getCustomParam(PositionBillConstant.ORG_KEY);
            String isInit = getPageCache().get(PositionBillConstant.PC_ISINIT);
            if (orgParam != null && HRStringUtils.isEmpty(isInit)) {
                getModel().beginInit();
                getModel().setValue(PositionBillConstant.NCKD_ORG_KEY, orgParam);
                getModel().endInit();
                getPageCache().put(PositionBillConstant.PC_ISINIT, EnableEnum.YES.getCode());
            }
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        AbstractOperate operate = (AbstractOperate) args.getSource();
        String operateKey = operate.getOperateKey();
        if (HRStringUtils.equals(operateKey, PositionBillConstant.SAVE_OP) || HRStringUtils.equals(operateKey, PositionBillConstant.SAVE_AND_NEW_OP)) {
            IFormView parentView = getBillFormView(getView());
            // 组织下同级岗位名称数据 {orgBoid:{positionId:positionName}}
            Map<String, Map<String, ILocaleString>> orgBoIdToSiblingNameMap = Maps.newHashMapWithExpectedSize(16);
            // 岗位编码数据 {positionId:number}
            Map<String, String> numberMap = Maps.newHashMapWithExpectedSize(16);
            if (parentView != null) {
                setValidateData(parentView, PositionBillConstant.ADD_TAG, orgBoIdToSiblingNameMap, numberMap);
                setValidateData(parentView, PositionBillConstant.CHANGE_TAG, orgBoIdToSiblingNameMap, numberMap);
            }

            operate.getOption().setVariableValue(PositionBillConstant.OP_BILL_SIBLING_NAMES_MAP, JSONObject.toJSONString(orgBoIdToSiblingNameMap));
            operate.getOption().setVariableValue(PositionBillConstant.OP_BILL_NUMBER_MAP, JSONObject.toJSONString(numberMap));
            operate.getOption().setVariableValue(PositionBillConstant.OP_VALIDATOR_BILL_POSITION_ALL_CHANGE_POSITION_KEY, getView().getFormShowParameter().getCustomParam(PositionBillConstant.OP_VALIDATOR_BILL_POSITION_ALL_CHANGE_POSITION_KEY));
        }
    }

    private IFormView getBillFormView(IFormView formView) {
        if (formView != null) {
            IFormView parentView = formView.getParentViewNoPlugin();
            return parentView != null && PositionBillConstant.NCKD_POSITIONBILL_ENTITY.equals(parentView.getFormShowParameter().getFormId()) ? parentView : getBillFormView(parentView);
        } else {
            return null;
        }
    }


    private void setValidateData(IFormView parentView, String suffix, Map<String, Map<String, ILocaleString>> orgBoIdToSiblingNameMap, Map<String, String> numberMap) {
        for(DynamicObject addEntryDy : parentView.getModel().getDataEntity(true).getDynamicObjectCollection(String.join("_", PositionBillConstant.NCKD_ENTRYENTITY, suffix))) {
            DynamicObject adminOrgDy = addEntryDy.getDynamicObject(String.join("_", PositionBillConstant.NCKD_ADMINORG, suffix));
            if (adminOrgDy != null) {
                String positionKey = String.join("_", PositionBillConstant.NCKD_POSITION_KEY, suffix);
                String positionIdKey = String.join(".", positionKey, PositionBillConstant.ID_KEY);
                if (PositionBillConstant.ADD_TAG.equals(suffix)) {
                    positionIdKey = positionKey;
                }

                long positionId = addEntryDy.getLong(positionIdKey);
                long boId = adminOrgDy.getLong(PositionBillConstant.BOID_KEY);
                Map<String, ILocaleString> siblingNameMap = orgBoIdToSiblingNameMap.get(String.valueOf(boId));
                if (siblingNameMap == null) {
                    siblingNameMap = Maps.newHashMapWithExpectedSize(16);
                }

                siblingNameMap.put(String.valueOf(positionId), addEntryDy.getLocaleString(String.join("_", PositionBillConstant.NCKD_NAME_KEY, suffix)));
                orgBoIdToSiblingNameMap.put(String.valueOf(boId), siblingNameMap);
                numberMap.put(String.valueOf(positionId), addEntryDy.getString(String.join("_", PositionBillConstant.NCKD_NUMBER_KEY, suffix)));
            }

        }

    }
}
