package nckd.jxccl.hr.haos.plugin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.bec.api.IEventServicePlugin;
import kd.bos.bec.model.KDBizEvent;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.sdk.hr.haos.business.helper.HAOSServiceHelper;
import nckd.jxccl.base.org.helper.OrgHelper;

import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;


/**
 * Tyx 2026-01-09
 * 事件订阅调用插件
 * 事件名：行政组织变动.生效
 */
public class DealOrgLongNamePlugin implements IEventServicePlugin {

    private static final Log logger = LogFactory.getLog(DealOrgLongNamePlugin.class);
    private static HRBaseServiceHelper ADMINORGDETAIL_HELPER = new HRBaseServiceHelper("haos_adminorgdetail");
    
    @Override
    public Object handleEvent(KDBizEvent evt) {

        // 获取事件参数，格式：
        // [{"data":[{"beforeversion":2388628286830828544,"isbelongcompanychange":false,"boid":2309486703347249189,"changeoperate":1030,"changescene":1030,"afterversion":2388631384106227714}]}]
        String paramStr = evt.getSource();
        JSONArray jsonArray = JSONArray.parseArray(paramStr);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            JSONArray dataArr = jsonObject.getJSONArray("data");
            // TODO 不确定这里data会不会为空
            JSONObject data = dataArr.getJSONObject(0);

            // 获取变动场景id，目前只处理 组织新设-1010，调整上级-1020,变更信息-1030的情况：
            Long sceneId = data.getLong("changescene");
            if(sceneId.equals(1010L) || sceneId.equals(1020L) || sceneId.equals(1030L)) {
                Long boId = data.getLong("boid");
                updateOrgLongName(boId);
            }
        }
        return IEventServicePlugin.super.handleEvent(evt);
    }

    /**
     * 更新组织长名称
     * @param boId 组织boId
     */
    public void updateOrgLongName (Long boId) {
        DynamicObject org = ADMINORGDETAIL_HELPER.loadOne(boId);
        String structLongNumber = org.getString("structlongnumber");
        List<Map<String, Object>> subOrgList = HAOSServiceHelper.querySubOrgToList(Collections.singletonList(boId), new Date(), 6);

        Set subOrgIdset = subOrgList.stream().map(i -> i.get("orgId")).collect(Collectors.toSet());
        String selectProperties = "id,boid,number,name,structlongnumber,structnumber,nckd_orglongname";
        QFilter idQFilter = new QFilter("id", "in", subOrgIdset);
        DynamicObject[] subOrgDyns = ADMINORGDETAIL_HELPER.query(selectProperties, new QFilter[]{idQFilter});
        Set structLongNumberSet = Arrays.stream(subOrgDyns).map(dyx -> dyx.get("structlongnumber").toString())
                .flatMap(longNumber -> Arrays.stream(longNumber.split("!")))
                .collect(Collectors.toSet());

        Map<String, Map<String, String>> structMap = OrgHelper.getStructNumberMap(structLongNumberSet, null);
        for (DynamicObject subOrg : subOrgDyns) {
            OrgHelper.dealLongName(subOrg, structMap);
        }
        SaveServiceHelper.update(subOrgDyns);
    }




}
