package cn.wisenergy.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.wisenergy.common.utils.exception.BASE_RESP_CODE_ENUM;
import cn.wisenergy.common.utils.exception.BaseCustomException;
import cn.wisenergy.mapper.WorkDeptMapper;
import cn.wisenergy.model.app.WorkDept;
import cn.wisenergy.model.app.WorkUser;
import cn.wisenergy.model.dto.OrganizationStructureDto;
import cn.wisenergy.model.dto.ProjectDto;
import cn.wisenergy.model.dto.UserRoleLevelDto;
import cn.wisenergy.model.enums.LevelEnum;
import cn.wisenergy.model.enums.LevelRankEnum;
import cn.wisenergy.service.WorkCentreService;
import cn.wisenergy.service.WorkDeptService;
import cn.wisenergy.service.WorkProjectService;
import cn.wisenergy.service.WorkUserService;
import cn.wisenergy.service.utils.UserRoleLevelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chenqi
 * @since 2021-01-19
 */
@Service
@Slf4j
public class WorkDeptServiceImpl implements WorkDeptService {

    @Autowired
    private WorkDeptMapper workDeptMapper;

    @Autowired
    private WorkDeptService workDeptService;

    @Autowired
    private WorkUserService workUserService;

    @Autowired
    private WorkCentreService workCentreService;

    @Autowired
    private WorkProjectService workProjectService;

    @Override
    public WorkDept getById(Integer id) {
        log.info("WorkDeptServiceImpl[]getById[]input.param.id" + id);
        if (null == id) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        WorkDept workDept = workDeptMapper.selectById(id);
        if (null == workDept) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.DEPT_IS_NULL);
        }
        return workDept;

    }

    @Override
    public List<WorkDept> getDeptInfo(Integer deptId) {
        log.info("WorkDeptServiceImpl[]getAllDeptInfo" + deptId);
        //获取部门信息
        Map<String, Object> map = new HashMap<>();
        map.put("id", deptId);
        List<WorkDept> workDepts = workDeptMapper.getDeptByCondition(map);
        if (CollectionUtil.isEmpty(workDepts)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.DEPT_NOT_FOUND);
        }
        return workDepts;
    }

    @Override
    public List<OrganizationStructureDto> getAllDeptByAllCentreId() {
        log.info("WorkDeptServiceImpl[]getAllDeptByAllCentreId[]");
        List<OrganizationStructureDto> allDeptByAllCentre = workDeptMapper.getAllDeptByAllCentre();
        if (CollectionUtils.isEmpty(allDeptByAllCentre)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.DEPT_IS_NULL);
        }
        return allDeptByAllCentre;
    }

    @Override
    public Boolean updateManagerIdISNullById(Integer id) {
        log.info("WorkDeptServiceImpl[]updateManagerIdISNullById[]input.param.id:{}" + id);
        if (null == id) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        int i = workDeptMapper.updateManagerIdISNullById(id);
        return i > 0;
    }

    @Override
    public Boolean updateById(WorkDept workDept) {
        log.info("WorkDeptServiceImpl[]updateById[]input.param.workDept:{}" + workDept);
        if (null == workDept || null == workDept.getId()) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        int i = workDeptMapper.updateById(workDept);
        return i>0;
    }

    @Override
    public List<WorkDept> getDeptByManagerId(Integer userId) {
        log.info("WorkDeptServiceImpl[]getDeptByManagerId[]input.param.userId:{}" + userId);
        if (null == userId) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        List<WorkDept> workDeptList = workDeptMapper.getDeptByManagerId(userId);
        if (CollectionUtils.isEmpty(workDeptList)) {
            return null;
        }
        return workDeptList;
    }

    /**
     * 获取管理员所管理的项目的部门
     *
     * @param userId
     * @return
     */
    @Override
    public List<WorkDept> getDeptOfProjectOfManager(Integer userId) {
        log.info("WorkDeptServiceImpl[]getDeptOfProjectOfManager[]input.param.userId:{}" + userId);
        if (null == userId) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        WorkUser user = workUserService.getById(userId);
        if (null == user) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.QUERY_USER_INFO_FAIL);
        }
        List<UserRoleLevelDto> roleUserLevel = UserRoleLevelUtils.getRoleUserLevel(userId);
        if (!UserRoleLevelUtils.isManagerLevel(userId, LevelEnum.PROJECT_MANAGER.getLevelName())) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.THE_USER_NOT_MANAGER_PLASE_MANAGER_LOGIN);
        }
        Set<WorkDept> depts = new LinkedHashSet<>();
        for (UserRoleLevelDto userRoleLevelDto : roleUserLevel) {
            if (userRoleLevelDto.getLevelName().equals(LevelEnum.PROJECT_MANAGER.getLevelName())) {
                // 中心级
                if (LevelRankEnum.CENTRAL_LEVEL.getRank().equals(userRoleLevelDto.getRank())) {
                    List<WorkDept> deptByCentreManager = workCentreService.getDeptByCentreManager(user);
                    if (!CollectionUtils.isEmpty(deptByCentreManager)) {
                        depts.addAll(deptByCentreManager);
                    }
                }
                // 部门级
                if (LevelRankEnum.DEPARTMENT_LEVEL.getRank().equals(userRoleLevelDto.getRank())) {
                    WorkDept dept = workDeptService.getById(user.getDeptId());
                    if (null != dept) {
                        depts.add(dept);
                    }
                }
                // 项目级
                if (LevelRankEnum.PROJECT_LEVEL.getRank().equals(userRoleLevelDto.getRank())) {
                    List<ProjectDto> projectIdByManager = workProjectService.getByManagerId(userId, null);
                    if (!CollectionUtils.isEmpty(projectIdByManager)) {
                        List<Integer> deptIds = new ArrayList<>();
                        projectIdByManager.forEach(project -> deptIds.add(project.getDeptId()));
                        List<WorkDept> workDepts = workDeptMapper.selectBatchIds(deptIds);
                        if (!CollectionUtils.isEmpty(workDepts)) {
                            depts.addAll(workDepts);
                        }
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(depts)) {
            List<WorkDept> workDepts = new ArrayList<>(depts);
            Collections.sort(workDepts);
            depts.clear();
            return workDepts;
        }
        return null;
    }
}
