package nckd.jxccl.hrmp.haos.plugin.operate.adminorg;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;
import nckd.jxccl.hrmp.haos.common.adminorg.AdminOrgConstant;

import java.util.Arrays;

/**
 * 组织快速维护保存操作插件
 * @entity: nckd_haos_adminorgdet_ext
 * @operate: save
 * @author: jtd
 * @date: 2025-10-13 11:08
 */
public class AdminOrgDetailSaveOpPlugin extends AbstractOperationServicePlugIn {

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);

        DynamicObject[] dataEntities = e.getDataEntities();
        if (dataEntities != null) {
            for (DynamicObject dataEntity : dataEntities) {
                setAdminOrgStructHierarchy(dataEntity);
            }
        }
    }

    private void setAdminOrgStructHierarchy(DynamicObject dataEntity) {
        String[] structNumbers = dataEntity.getString(AdminOrgConstant.STRUCTLONGNUMBER).split("!");
        // 过滤组织上下级关系编码和是否当前生效数据
        QFilter[] qFilters = {new QFilter(AdminOrgConstant.STRUCTNUMBER, QCP.in, Arrays.asList(structNumbers)), QFilterCommonHelper.getCurrentVersionFilter()};
        DynamicObjectCollection adminOrgColl = QueryServiceHelper.query(AdminOrgConstant.ADMINORG_ENTITYID, AdminOrgConstant.ID_KEY, qFilters, AdminOrgConstant.LEVEL);
        for (int i = 0; i < AdminOrgConstant.ADMINORG_STRUCT_FIELDS.length; i++) {
            if (i < adminOrgColl.size() && adminOrgColl.get(i) != null) {
                dataEntity.set(AdminOrgConstant.ADMINORG_STRUCT_FIELDS[i], adminOrgColl.get(i).getLong(AdminOrgConstant.ID_KEY));
            } else if (i == adminOrgColl.size()) {
                dataEntity.set(AdminOrgConstant.ADMINORG_STRUCT_FIELDS[i], dataEntity.getLong(AdminOrgConstant.ID_KEY));
            } else {
                dataEntity.set(AdminOrgConstant.ADMINORG_STRUCT_FIELDS[i], null);
            }
        }
    }

}