package com.casic.missiles.service.Impl.system;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.casic.missiles.mapper.system.SystemFlowFormMapper;
import com.casic.missiles.model.system.SystemFlowForm;
import com.casic.missiles.modular.system.dao.DeptMapper;
import com.casic.missiles.modular.system.dao.UserMapper;
import com.casic.missiles.modular.system.model.Dept;
import com.casic.missiles.modular.system.model.User;
import com.casic.missiles.service.system.ISystemFlowFormService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wangpeng
 * @since 2022-12-12
 */
@Service
public class SystemFlowFormServiceImpl extends ServiceImpl<SystemFlowFormMapper, SystemFlowForm> implements ISystemFlowFormService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private DeptMapper deptMapper;

    @Override
    public int getDirectorLevel(Long userId) {
        //需要保证用户所在组织机构一定要有个角色的TIPS为director的角色的人
        int level = 0;
        return getDirectorList(level, userId);
    }

    private int getDirectorList(int level, Long userId) {
        User user = userMapper.selectById(userId);
        Long deptId = user.getDeptId();
        Dept dept = deptMapper.selectById(deptId);
        String pids = dept.getPids();
        List<String> deptIds = new ArrayList<>();
        if(StringUtils.isNotEmpty(pids)){
            String replace = pids.replace("[", "").replace("]", "");
            pids = replace.substring(0, replace.length() - 1);
            //在角色管理中配置的角色所在组织机构，要保证该机构的子组织结构使用该角色也可以生效
            deptIds = new ArrayList<>(Arrays.asList(pids.split(",")));
        }
        if(level >= 1){
            //主管获取所在的上级部门
            deptId = dept.getPid();
        }
        //保证无父id时deptIds有值，sql正常执行
        if(CollectionUtils.isEmpty(deptIds)){
            deptIds.add(String.valueOf(deptId));
        }
        List<Map<String, Object>> list = SqlRunner.db().selectList("select su.ID as id from sys_role sr " +
                "JOIN sys_ru_relation srr ON sr.ID = srr.ROLEID " +
                "JOIN sys_user su ON srr.USERID = su.ID " +
                "WHERE (sr.DEPT_ID = {2} or sr.DEPT_ID in {0})" +//角色所在的组织机构及该结构的子结构
                "AND sr.TIPS = {1}" +
                "AND su.DEPT_ID = {2}", deptIds, "director", String.valueOf(deptId));

        if(CollectionUtils.isEmpty(list)){
            return level;
        }
        level += 1;
        Map<String, Object> idMap = list.get(0);
        String id = String.valueOf(idMap.get("id"));
        return getDirectorList(level, Long.valueOf(id));
    }
}
