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

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.metadata.IDataEntityType;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
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.util.CollectionUtils;
import kd.bos.servicehelper.basedata.BaseDataServiceHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import nckd.jxccl.hrmp.hbpm.common.hr.PositionBillConstant;

import java.sql.ResultSet;

/**
 * 岗位申请分录快速变更帮助类
 * @from: kd.hr.homs.business.domain.orgfast.repository.AdminOrgFastChgHelper
 * @author: jtd
 * @date: 2025/12/27 17:19
 */
public class PosBillEntryFastChgHelper {

    public static void orgPropertyChanged(PropertyChangedArgs changedArgs, IFormView iFormView, IFormPlugin formPlugin) {
        ChangeData changeData = changedArgs.getChangeSet()[0];
        DynamicObject newDy = (DynamicObject) changeData.getNewValue();
        DynamicObject oldDy = (DynamicObject) changeData.getOldValue();
        String masterOrg = iFormView.getPageCache().get(PositionBillConstant.PC_MASTERORG);
        if (changedArgs.getChangeSet()[0].getNewValue() != null) {
            HRBaseServiceHelper hrBaseServiceHelper = new HRBaseServiceHelper(PositionBillConstant.NCKD_POSITIONBILL_ENTITY);
            boolean exists = hrBaseServiceHelper.isExists(iFormView.getModel().getDataEntity().getLong(PositionBillConstant.ID_KEY));
            if (!exists) {
                Long orgIdNew = newDy.getLong(PositionBillConstant.ID_KEY);
                if (StringUtils.isNotEmpty(masterOrg) && !StringUtils.equals(masterOrg, String.valueOf(orgIdNew))) {
                    Long orgIDOld = oldDy == null ? 0L : oldDy.getLong(PositionBillConstant.ID_KEY);
                    iFormView.getPageCache().put(PositionBillConstant.PC_MASTERORG, String.valueOf(orgIDOld));
                    ConfirmCallBackListener confirmCallBackListener = new ConfirmCallBackListener(PositionBillConstant.CB_CHG_ORG, formPlugin);
                    iFormView.showConfirm("切换组织体系管理组织后，将清除该组织不可使用的基础资料信息，是否切换？", MessageBoxOptions.OKCancel, confirmCallBackListener);
                }

            }
        }
    }

    public static void cleanOrgBaseInfo(long orgId, IFormView iFormView) {
        MainEntityType entityType = EntityMetadataCache.getDataEntityType(iFormView.getEntityId());
        IDataModel model = iFormView.getModel();

        for(IDataEntityProperty property : entityType.getAllFields().values()) {
            if (property instanceof BasedataProp) {
                IDataEntityType parent = property.getParent();
                if (parent != null) {
                    if (!parent.getName().equals(iFormView.getEntityId())) {
                        if (model.getDataEntity().containsProperty(property.getParent().getName())) {
                            DynamicObjectCollection dynamicObjectCollection = model.getDataEntity(true).getDynamicObjectCollection(property.getParent().getName());
                            if (!CollectionUtils.isEmpty(dynamicObjectCollection)) {
                                for(int i = 0; i < dynamicObjectCollection.size(); ++i) {
                                    DynamicObject entrtyDy = dynamicObjectCollection.get(i);
                                    DynamicObject baseDy = entrtyDy.getDynamicObject(property.getName());
                                    if (baseDy != null && cleanBastInfo(baseDy, property, iFormView, orgId)) {
                                        model.setValue(property.getName(), null, i);
                                        iFormView.updateView(property.getName(), i);
                                    }
                                }
                            }
                        }
                    } else if (model.getDataEntity().containsProperty(property.getName())) {
                        DynamicObject baseDy = model.getDataEntity().getDynamicObject(property.getName());
                        if (baseDy != null && cleanBastInfo(baseDy, property, iFormView, orgId)) {
                            model.setValue(property.getName(), null);
                            iFormView.updateView(property.getName());
                        }
                    }
                }
            }
        }

    }

    public static void cleanOrgBaseInfoForBillEntry(IFormView iFormView, int row, String fieldKey, String entryId) {
        IDataModel model = iFormView.getModel();
        DynamicObjectCollection collection = model.getDataEntity(true).getDynamicObjectCollection(entryId);
        if (collection != null && collection.size() != 0) {
            for(IDataEntityProperty entityProperty : collection.getDynamicObjectType().getProperties()) {
                if (!entityProperty.getName().equals(fieldKey) && entityProperty instanceof BasedataProp) {
                    DynamicObject entrtyDy = collection.get(row);
                    DynamicObject orgId = entrtyDy.getDynamicObject(fieldKey);
                    DynamicObject baseDy = entrtyDy.getDynamicObject(entityProperty.getName());
                    if (baseDy != null && cleanBastInfo(baseDy, entityProperty, iFormView, orgId.getLong(PositionBillConstant.ID_KEY))) {
                        iFormView.getModel().beginInit();
                        model.setValue(entityProperty.getName(), null, row);
                        iFormView.updateView(entityProperty.getName(), row);
                        iFormView.getModel().endInit();
                    }
                }
            }

        }
    }

    private static boolean cleanBastInfo(DynamicObject baseDy, IDataEntityProperty property, IFormView iFormView, long orgId) {
        Boolean baseDataCtrl = BaseDataServiceHelper.checkBaseDataCtrl(((BasedataProp) property).getBaseEntityId());
        if (baseDataCtrl) {
            if (!checkAssign(iFormView, property, baseDy, orgId)) {
                return true;
            }
        }

        return false;
    }

    private static boolean checkAssign(IFormView iFormView, IDataEntityProperty property, DynamicObject baseDy, long orgId) {
        IDataEntityType dataEntityType = baseDy.getDataEntityType();
        String baseDataTableName = dataEntityType.getAlias();
        String dbRouteKey = dataEntityType.getDBRouteKey();
        DBRoute dbRoute = DBRoute.of(dbRouteKey);
        String bsaeDataUseRegTableName = baseDataTableName + "UseReg";
        String countUseRegSql = "select FDataID from " + bsaeDataUseRegTableName + " where FDataID = ? and fuseorgid = ? ";
        Object[] params = new Object[]{baseDy.get(PositionBillConstant.ID_KEY), orgId};
        Boolean assign = DB.query(dbRoute, countUseRegSql, params, ResultSet::next);
        return assign;
    }

}
