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.BpmOAEntryDO;
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.oa.BpmOAEntryService;
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 BpmTaskEntryLeaderScript implements BpmTaskAssignScript {

    @Resource
    @Lazy // 解决循环依赖
    private DeptApi deptApi;
    @Resource
    @Lazy // 解决循环依赖
    private BpmOAEntryService entryService;

    @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 取到入职流程表单
        BpmOAEntryDO entryDO = entryService.getEntry(Long.valueOf(processInstance.getBusinessKey()));
        //获取入职部门ID
        Long deptId = entryDO.getEntryDeptId();

        //根据部门ID 获取部门信息
        DeptRespDTO dept = deptApi.getDept(deptId).getCheckedData();

        // 获取4级部门信息
        if (dept.getLevel() > 4) {
            String[] level = dept.getFlag().split("-");
            dept = deptApi.getDept(Long.valueOf(level[4])).getCheckedData();
        }

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

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