package cn.iocoder.yudao.module.bpm.framework.flowable.core.behavior.script.impl;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.BpmTaskRespVO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.BpmOAShiftjobsDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.oa.BpmOAShiftjobsMapper;
import cn.iocoder.yudao.module.bpm.enums.definition.BpmTaskRuleScriptEnum;
import cn.iocoder.yudao.module.bpm.framework.flowable.core.behavior.script.BpmTaskAssignScript;
import cn.iocoder.yudao.module.bpm.service.task.BpmProcessInstanceService;
import cn.iocoder.yudao.module.bpm.service.task.BpmTaskService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet;
import static java.util.Collections.emptySet;

@Component
public class BpmTaskShiftjobsLeaderScript implements BpmTaskAssignScript {

    @Resource
    private DeptApi deptApi;
    @Resource
    private BpmOAShiftjobsMapper bpmOAShiftjobsMapper;

    @Resource
    @Lazy // 解决循环依赖
    private BpmProcessInstanceService bpmProcessInstanceService;

    @Resource
    @Lazy // 解决循环依赖
    private BpmTaskService bpmTaskService ;
    @Override
    public Set<Long> calculateTaskCandidateUsers(DelegateExecution execution) {

        // 获得发起人
        ProcessInstance processInstance = bpmProcessInstanceService.getProcessInstance(execution.getProcessInstanceId());
        List<BpmTaskRespVO> bpmTaskRespVOs = bpmTaskService.getTaskListByProcessInstanceId(processInstance.getProcessInstanceId());
        if (CollUtil.isEmpty(bpmTaskRespVOs)) {
            return emptySet();
        }

        //根据流程实例ID 取到调岗流程表单
        BpmOAShiftjobsDO shiftjobsDO = bpmOAShiftjobsMapper.selectByProcessInstanceId(processInstance.getProcessInstanceId());
        //获取调岗部门ID
        Long deptId = shiftjobsDO.getNewDeptId();

        //根据部门ID 获取部门信息
        DeptRespDTO dept = deptApi.getDept(deptId).getCheckedData();
        if (dept.getLevel() > 3) { //判断部门层级

            String [] flag = dept.getFlag().split("-");
            dept = deptApi.getDept(Long.valueOf(flag[3])).getCheckedData();
        }

        return dept.getLeaderUserId() != null ? asSet(dept.getLeaderUserId()) : emptySet();
    }

    @Override
    public BpmTaskRuleScriptEnum getEnum() {
        return BpmTaskRuleScriptEnum.LEADER_X5;
    }
}
