package cn.iocoder.yudao.module.bpm.framework.flowable.core.candidate.expression;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.util.number.NumberUtils;
import cn.iocoder.yudao.module.bpm.service.task.BpmProcessInstanceService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.PostApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.dept.dto.PostRespDTO;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

import static java.util.Collections.emptySet;

@Component
public class BpmTaskPostExpression {
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private DeptApi deptApi;
    @Resource
    private BpmProcessInstanceService processInstanceService;
    @Autowired
    private DictDataApi dictDataApi;
    @Autowired
    private PostApi postApi;

    public Set<Long> calculateUsers(DelegateExecution execution, int level,String type) {
        Assert.isTrue(level>0, "leve必须大于0");
        ProcessInstance processInstance = processInstanceService.getProcessInstance(execution.getProcessInstanceId());
        Long startId = NumberUtils.parseLong(processInstance.getStartUserId());
        AdminUserRespDTO user = adminUserApi.getUser(startId);
        if (user == null) {
            throw new ServiceException(new ErrorCode(22,"用户不存在"));
        }
        DeptRespDTO dept = null;
        String companyCode = getCompanyCode(user.getDeptId());
        if ("qhse-bz".equals(type)&&"rh".equals(companyCode)) {
            level = level+1;
        }
        for (int i = 0; i < level; i++) {
            // 获得 level 对应的部门
            if (dept == null) {
                dept = getStartUserDept(startId);
                if (dept == null) { // 找不到发起人的部门，所以无法使用该规则
                    return emptySet();
                }
            } else {
                DeptRespDTO parentDept = deptApi.getDept(dept.getParentId());
                if (parentDept == null) { // 找不到父级部门，所以只好结束寻找。原因是：例如说，级别比较高的人，所在部门层级比较少
                    break;
                }
                dept = parentDept;
            }
        }
        if (dept == null) {
            DeptRespDTO parentDept = deptApi.getDept(dept.getParentId());
            // 找不到父级部门，所以只好结束寻找。原因是：例如说，级别比较高的人，所在部门层级比较少
            dept = parentDept;
        }
        if (dept == null) {
            throw new ServiceException(new ErrorCode(12,"部门不存在"));
        }
        Long deptId = dept.getId();
        List<DictDataRespDTO> dictDataList = dictDataApi.getDictDataList(type);
        if (CollUtil.isEmpty(dictDataList)) {
            throw new ServiceException();
        }
        String label = dictDataList.get(0).getLabel();
        PostRespDTO postByName = postApi.getPostByName(label);
        if (postByName == null) {
            throw new ServiceException();
        }
        Set<Long> users = adminUserApi.getUserListByDept(deptId).stream().filter(e -> {
            if (CollUtil.isNotEmpty(e.getPostIds())) {
                return e.getPostIds().contains(postByName.getId());
            } else {
                return false;
            }
        }).map(AdminUserRespDTO::getId).collect(Collectors.toSet());
//        List<Long> roleUserIds = roleApi.getRoleUserIds("公司设备管理");
//        Set<Long> collect = users.stream().filter(roleUserIds::contains).collect(Collectors.toSet());
//        return collect;
        return users;
    }

    private DeptRespDTO getStartUserDept(Long startUserId) {
        AdminUserRespDTO startUser = adminUserApi.getUser(startUserId);
        if (startUser.getDeptId() == null) { // 找不到部门，所以无法使用该规则
            return null;
        }
        return deptApi.getDept(startUser.getDeptId());
    }

    private String getCompanyCode(Long deptId) {
        DeptRespDTO dept = deptApi.getDeptNoPermission(deptId);
        String name = dept.getName();
        String companyCode = "";
        if (name.contains("瑞恒")) {
            companyCode = "rh";
        } else if (name.contains("瑞都")) {
            companyCode = "rd";
        } else if (name.contains("瑞鹰")) {
            companyCode = "ry";
        } else if (name.contains("科瑞石油技术")) {
            companyCode = "jt";
        } else {
            Long parentId = dept.getParentId();
            DeptRespDTO dept1 = deptApi.getDeptNoPermission(parentId);
            String name1 = dept1.getName();
            if (name1.contains("瑞恒")) {
                companyCode = "rh";
            } else if (name1.contains("瑞都")) {
                companyCode = "rd";
            } else if (name1.contains("瑞鹰")) {
                companyCode = "ry";
            } else if (name1.contains("科瑞石油技术")) {
                companyCode = "jt";
            } else {
                DeptRespDTO dept2 = deptApi.getDeptNoPermission(dept1.getParentId());
                String name2 = dept2.getName();
                if (name2.contains("瑞恒")) {
                    companyCode = "rh";
                } else if (name2.contains("瑞都")) {
                    companyCode = "rd";
                } else if (name2.contains("瑞鹰")) {
                    companyCode = "ry";
                } else {
                    DeptRespDTO dept3= deptApi.getDeptNoPermission(dept2.getParentId());
                    String name3 = dept3.getName();
                    if (name3.contains("瑞恒")) {
                        companyCode = "rh";
                    } else if (name3.contains("瑞都")) {
                        companyCode = "rd";
                    } else if (name3.contains("瑞鹰")) {
                        companyCode = "ry";
                    }
                }
            }
        }
        return companyCode;
    }
}
