package nckd.jimin.jyyy.hr.haos.task;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jimin.jyyy.hr.haos.util.OrgUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @author Tyx
 * @date  2025/6/26
 * 一次性后台任务，批量更新所有组织的长名称和长编码，nckd_longname和nckd_longnumber
 */
public class DealOrgLongNameTask extends AbstractTask implements Plugin {

    private static final Log log = LogFactory.getLog(DealOrgLongNameTask.class);
    private static String adminOrgDetail_entity = "haos_adminorgdetail";
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        log.info(" ------- 开始执行批量修改组织长名称/长编码方法 ------- ");
        String selectProperties = "id,boid,number,name,structlongnumber,structnumber,nckd_longname,nckd_longnumber,bsed";
        QFilter filter = new QFilter("iscurrentversion", QCP.equals, "1");
        DynamicObject[] orgDyns = new HRBaseServiceHelper(adminOrgDetail_entity).query(selectProperties, filter.toArray());
        log.info(" ------- 批量更新条数 : {} ------", orgDyns.length);
        for (DynamicObject org : orgDyns) {
            String structLongNumber = org.getString("structlongnumber");
            Date bsed = new Date();
            Set structLongNumberSet = Arrays.stream(structLongNumber.split("!")).
                    collect(Collectors.toSet());
            Map<String, Map<String, String>> structMap = OrgUtils.getStructNumberMap(structLongNumberSet, bsed);
            OrgUtils.dealLongNameAndNumber(org, structMap);
        }
        SaveServiceHelper.update(orgDyns);
    }
}