package nckd.jimin.jyyy.hr.plugin.workflow;

import kd.bos.exception.KDBizException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.workflow.api.AgentExecution;
import kd.bos.workflow.engine.extitf.IWorkflowPlugin;
import kd.hrmp.hrpi.business.domian.service.impl.PersonRoleServiceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 通用工作流插件 Tyx 2025-07-01
 * 通过岗位获取一级部门负责人
 */
public class GetSecondDeptChargerByPosWorkflowPlugin implements IWorkflowPlugin {
    private static final Log log = LogFactory.getLog(GetSecondDeptChargerByPosWorkflowPlugin.class);
    @Override
    public List<Long> calcUserIds(AgentExecution execution) {
        List<Long> approvers = execution.getCurrentApprover();
        log.info(" before 获取流程变量 positionId ");
        //如果变量选的是分录的岗位，则变量取出来是List
        Long positionId = 0L;
        //表头
        if(execution.getVariable("positionId") == null) {
            throw new KDBizException("未设置流程变量positionId");
        }
        Object var = execution.getVariable("positionId");
        if(var instanceof List) {
            List<Long> positionList = (List) var;
            positionId = positionList.get(0);
        }
        else {
            positionId = Long.valueOf(var.toString());
        }
        log.info(" 获取流程变量 positionId : {} ", positionId);
        //获取岗位对应部门ID
        Long adminOrgId = HRWorkflowUtils.getAdminOrgIdByPositionId(positionId);
        log.info(" positionId 对应部门Id : {}", adminOrgId);
        //获取二级部门
        Long firstDeptId = HRWorkflowUtils.getSecondDeptId(adminOrgId);
        log.info(" 二级部门ID : {}", firstDeptId);
        //获取一级部门负责人
        List deptIds = new ArrayList();
        deptIds.add(firstDeptId);
        List mainChargeInfos = PersonRoleServiceImpl.getInstance().getMainChargeByOrg(deptIds);
        List chargerIds = new ArrayList();
        for(Object obj : mainChargeInfos) {
            Map map = (Map) obj;
            String charger = map.get("person").toString();
            log.info(" 计算出参与人personId : {}", charger);
            chargerIds.add(Long.valueOf(charger));
        }
        //personId转换userId
        List chargerUserId = HRWorkflowUtils.transPersonIdToUserId(chargerIds);
        approvers.addAll(chargerUserId);
        return approvers;
    }
}