package nckd.jxccl.hrmp.hbpm.business.hr.service.impl;

import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.metadata.clr.DataEntityPropertyCollection;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.property.BasedataProp;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.IFormView;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.plugin.IFormPlugin;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.hr.hbp.common.util.HRStringUtils;
import nckd.jxccl.base.common.utils.PatternUtil;
import nckd.jxccl.hrmp.hbpm.common.hr.PositionBillConstant;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 岗位申请单属性变更服务类
 * @from: kd.hr.homs.business.domain.batchbill.service.impl.AdminOrgBatchBillPropertyChangedService
 * @author: jtd
 * @date: 2025/12/24 22:05
 */
public class PositionBillPropertyChangedService extends PositionBillBaseService {
    private IFormPlugin closeCallBackPlugin;
    private final Map<String, Map<?, DynamicObject>> baseDataCacheMap;

    public IFormPlugin getCloseCallBackPlugin() {
        return closeCallBackPlugin;
    }

    public void setCloseCallBackPlugin(IFormPlugin closeCallBackPlugin) {
        this.closeCallBackPlugin = closeCallBackPlugin;
    }

    public PositionBillPropertyChangedService(IFormView view, Map<String, Map<?, DynamicObject>> baseDataCacheMap) {
        super(view);
        this.baseDataCacheMap = baseDataCacheMap;
    }

    public void propertyChanged(PropertyChangedArgs changedArgs) {
        if (!HRStringUtils.equals(EnableEnum.YES.getCode(), getModel().getContextVariable("entryimport"))) {
            IDataEntityProperty property = changedArgs.getProperty();
            int rowIndex = changedArgs.getChangeSet()[0].getRowIndex();
            String fieldKey = property.getName();
            String suffix = getSuffixByFieldKey(fieldKey);
            Object objectNew = changedArgs.getChangeSet()[0].getNewValue();
            Object objectOld = changedArgs.getChangeSet()[0].getOldValue();
            if (fieldKey.equals(String.join("_", PositionBillConstant.NCKD_POSITION_KEY, suffix))) {
                if (objectOld == null) {
                    entrySelectF7Change(property, suffix, rowIndex);
                } else if (objectNew != null) {
                    showConfirmByOldValue(changedArgs, suffix, rowIndex);
                }
            } else if (fieldKey.equals(String.join("_", PositionBillConstant.NCKD_ORG_KEY, suffix))) {
                DynamicObject oldObj = (DynamicObject) objectOld;
                DynamicObject newObj = (DynamicObject) objectNew;
                if (newObj != null && oldObj != null && oldObj.getLong(PositionBillConstant.ID_KEY) != newObj.getLong(PositionBillConstant.ID_KEY)) {
                    Long orgIDOld = oldObj == null ? 0L : oldObj.getLong(PositionBillConstant.ID_KEY);
                    getView().getPageCache().remove(PositionBillConstant.PC_ENTRY_ORG_VALUE);
                    getView().getPageCache().put(PositionBillConstant.PC_ENTRY_ORG_VALUE, String.valueOf(orgIDOld));
                    ConfirmCallBackListener confirmCallBackListener = new ConfirmCallBackListener(fieldKey, closeCallBackPlugin);
                    getView().showConfirm("切换组织体系管理组织后，将清除该组织不可使用的基础资料信息，是否切换？", MessageBoxOptions.OKCancel, confirmCallBackListener);
                }
            }
        }

    }

    private void entrySelectF7Change(IDataEntityProperty property, String suffix, int row) {
        String lineSuffix = "_"+suffix;
        DataEntityPropertyCollection entryEntityInfo = getModel().getDataEntity(true).getDynamicObjectCollection(PositionBillConstant.NCKD_ENTRYENTITY+lineSuffix).getDynamicObjectType().getProperties();

        Map<String, String> transKeyMap = new HashMap<String, String>();
        // 获取分录要转换的键值，将单据分录字段转换转成分录页面字段
        transKeyMap.putAll(PositionBillServiceHelper.getPosBillEntryTransKeyMap());
        // 获取岗位要转换的键值
        transKeyMap.putAll(PositionBillServiceHelper.getPositionTransKeyMap());
        // 获取岗位所有属性
        Set<String> positionProperties = PositionBillServiceHelper.getPositionProperties();

        StringBuilder selectSqlBuilder = new StringBuilder();
        for(IDataEntityProperty iDataEntityProperty : entryEntityInfo) {
            String propName = iDataEntityProperty.getName();
            if (PatternUtil.isExProperty(propName) && propName.endsWith(lineSuffix)) {
                String selectName = PositionBillServiceHelper.getNoLineSuffixProp(propName, lineSuffix);
                selectName = transKeyMap.getOrDefault(selectName, selectName);
                if (positionProperties.contains(selectName)) {
                    selectSqlBuilder.append(",").append(selectName);
                }
            }
        }

        if (selectSqlBuilder.length() > 0) {
            selectSqlBuilder.deleteCharAt(0);
        }

        BasedataProp basedataProp = (BasedataProp) property;
        String baseEntityId = basedataProp.getBaseEntityId();
        Map<?, DynamicObject> dyMap = baseDataCacheMap.get(baseEntityId);
        DynamicObject entryEntityDyn = PositionBillServiceHelper.getFocusEntry(suffix, getView(), row);
        DynamicObject position = null;
        long positionId = entryEntityDyn.getLong(String.join(".", PositionBillConstant.NCKD_POSITION_KEY+lineSuffix, PositionBillConstant.ID_KEY));
        if (dyMap != null) {
            position = dyMap.get(positionId);
        }

        // 从数据库获取岗位数据
        if (position == null) {
            HRBaseServiceHelper helper = new HRBaseServiceHelper(PositionBillConstant.HBPM_POSITIONHR);
            QFilter filter = new QFilter(PositionBillConstant.ID_KEY, QCP.equals, positionId);
            position = helper.loadOne(selectSqlBuilder.toString(), filter.toArray());
        }

        if (position != null) {
            long entryId = ORM.create().genLongId(PositionBillConstant.NCKD_POSITIONBILLENTRY_ENTITY);
            entryEntityDyn.set(PositionBillConstant.ID_KEY, entryId);

            for(IDataEntityProperty iDataEntityProperty : entryEntityInfo) {
                String propName = iDataEntityProperty.getName();
                if (PatternUtil.isExProperty(propName) && propName.endsWith(lineSuffix)) {
                    String selectName = PositionBillServiceHelper.getNoLineSuffixProp(propName, lineSuffix);
                    selectName = transKeyMap.getOrDefault(selectName, selectName);
                    if (positionProperties.contains(selectName)) {
                        // 原上级岗位特殊处理
                        if (HRStringUtils.equals(selectName, PositionBillConstant.NCKD_PARENT)) {
                            entryEntityDyn.set(PositionBillConstant.NCKD_ORIPARENT_KEY+lineSuffix, position.get(selectName));
                        }
                        entryEntityDyn.set(propName, position.get(selectName));
                    }
                }
            }

            getView().updateView(PositionBillConstant.NCKD_ENTRYENTITY+lineSuffix);
        }

    }

    private void showConfirmByOldValue(PropertyChangedArgs e, String suffix, int rowIndex) {
        DynamicObject position = (DynamicObject) e.getChangeSet()[0].getOldValue();
        Long positionOld = position != null ? position.getLong(PositionBillConstant.ID_KEY) : null;
        getView().getPageCache().put(PositionBillConstant.PC_POSITIONOLD, positionOld == null ? "" : String.valueOf(positionOld));
        getView().getPageCache().put(PositionBillConstant.PC_POSITIONROW, String.valueOf(rowIndex));
        ConfirmCallBackListener confirmCallBackListener = new ConfirmCallBackListener(PositionBillConstant.CB_SELECT_POSITION + suffix, getCloseCallBackPlugin());
        getView().showConfirm("切换岗位后，当前已修改的内容将会丢失，是否继续？", MessageBoxOptions.OKCancel, confirmCallBackListener);
    }

    private String getSuffixByFieldKey(String fieldKey) {
        int charIndex = fieldKey.lastIndexOf("_");
        String suffix = "";
        if (charIndex != -1) {
            suffix = fieldKey.substring(charIndex+1);
        }

        return suffix;
    }
}
