package com.tuoheng.admin.service.dept.query;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.conver.DeptConverMapper;
import com.tuoheng.admin.dto.RoadSectionDto;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.code.dept.QueryDeptInfoCodeEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.dept.DeptInfoVo;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 获取部门信息业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-11-19
 */
@Slf4j
@Service
public class QueryDeptInfoService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoadInformationMapper roadInformationMapper;

    @Autowired
    private SectionMapper sectionMapper;

    @Autowired
    private RoadDeptMapper roadDeptMapper;

    @Autowired
    private SectionDeptMapper sectionDeptMapper;

    public JsonResult getDeptInfo(String deptId) {
        log.info("进入获取部门信息业务, deptId:{}", deptId);
        String tenantId = CurrentUserUtil.getTenantId();

        // 校验
        JsonResult result = this.check(tenantId, deptId);
        if (0 != result.getCode()) {
            log.info("获取部门信息业务：校验失败：{}", result.getMsg());
            return result;
        }

        // 在校验中，判断部门是否存在时，若部门存在，直接将部门信息返回，减少数据库查询次数
        Dept dept = (Dept) result.getData();

        // 处理公路与路段的对应关系
        List<RoadSectionDto> roadSectionDtoList = this.getRoadSectionDtoList(tenantId, deptId);

        // 拼装返回数据实体
        Dept parent = this.getParentDept(tenantId, dept.getPid());
        Integer userCount = this.getUserCount(tenantId, deptId);
        Integer childDeptCount = this.getChildDeptCount(tenantId, deptId);

        DeptInfoVo deptInfoVo = DeptConverMapper.INSTANCE.fromDeptToDeptVo(dept);
        deptInfoVo.setRoadSectionDtoList(roadSectionDtoList);
        deptInfoVo.setUserCount(userCount);
        deptInfoVo.setChildDeptCount(childDeptCount);
        if (null != parent) {
            deptInfoVo.setPname(parent.getName());
        }

        return JsonResult.success(deptInfoVo);
    }

    /**
     * 检查参数
     * @param tenantId
     * @param id
     * @return
     */
    private JsonResult check(String tenantId, String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonResult.error(QueryDeptInfoCodeEnum.DEPT_ID_IS_NULL.getCode(), QueryDeptInfoCodeEnum.DEPT_ID_IS_NULL.getMsg());
        }

        // 判断部门是否存在
        Dept dept = deptMapper.selectOne(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getTenantId, tenantId)
                .eq(Dept::getId, id)
                .eq(Dept::getMark, 1));
        if (null == dept) {
            return JsonResult.error(QueryDeptInfoCodeEnum.DEPT_IS_NOT_EXIST.getCode(), QueryDeptInfoCodeEnum.DEPT_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success(dept);
    }

    /**
     * 获取父部门信息
     */
    private Dept getParentDept(String tenantId, String pid) {
       Dept dept = deptMapper.selectOne(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getTenantId, tenantId)
                .eq(Dept::getId, pid)
                .eq(Dept::getMark, 1));
        return dept;
    }

    /**
     * 获取部门下用户数
     */
    private Integer getUserCount(String tenantId, String deptId) {
        Integer count = userMapper.selectCount(new LambdaQueryWrapper<User>()
                .eq(User::getTenantId, tenantId)
                .eq(User::getDeptId, deptId)
                .eq(User::getMark, 1));
        return count;
    }

    /**
     * 获取部门下子部门数
     */
    private Integer getChildDeptCount(String tenantId, String deptId) {
        Integer count = deptMapper.selectCount(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getTenantId, tenantId)
                .eq(Dept::getPid, deptId)
                .eq(Dept::getMark, 1));
        return count;
    }

    /**
     * 拼装数据
     * @param tenantId
     * @param id
     * @return
     */
    private List<RoadSectionDto> getRoadSectionDtoList(String tenantId, String id) {
        // 获取该部门下公路列表
        List<RoadInformation> roadInformationList = this.getRoadInformationList(tenantId, id);
        if (CollectionUtil.isEmpty(roadInformationList)) {
            // 不会出现此场景，在代码层面考虑健壮性，加此判断
            // 根据业务需求，添加部门时，必须添加公路和路段信息
            // 若公路数据为空，说明肯定也没也路段信息，不用继续往下判断，因此直接返回
            log.info("获取部门信息业务：公路信息为空");
            return null;
        }

        // 获取该部门下路段列表
        List<Section> sectionList = this.getSectionList(tenantId, id);
        if (CollectionUtil.isEmpty(sectionList)) {
            // 不会出现此场景，在代码层面考虑健壮性，加此判断
            // 若路段信息为空，不用继续往下判断，因此直接返回
            log.info("获取部门信息业务：路段信息为空");
            return null;
        }

        List<RoadSectionDto> roadSectionDtoList = new ArrayList<>();
        RoadSectionDto roadSectionDto;
        List<Section> sectionListTmp;

        Map<String, RoadInformation> roadInformationMap = roadInformationList.stream().collect(Collectors.toMap(RoadInformation::getId, Function.identity()));
        RoadInformation roadInformation;
        for (Section section : sectionList) {
            roadSectionDto = new RoadSectionDto();
            sectionListTmp = new ArrayList<>();
            sectionListTmp.add(section);
            roadInformation = roadInformationMap.get(section.getRoadId());
            if (ObjectUtil.isNull(roadInformation)) {
                continue;
            }
            roadSectionDto.setRoad(roadInformation);
            roadSectionDto.setSectionList(sectionListTmp);
            roadSectionDtoList.add(roadSectionDto);
        }
        return roadSectionDtoList;
    }

    /**
     * 查询该部门下公路信息列表
     * @param tenantId
     * @param id
     * @return
     */
    private List<RoadInformation> getRoadInformationList(String tenantId, String id) {
        List<RoadDept> roadDeptList = roadDeptMapper.selectList(new LambdaQueryWrapper<RoadDept>()
                .eq(RoadDept::getTenantId, tenantId)
                .eq(RoadDept::getDeptId, id));
        if (CollectionUtil.isEmpty(roadDeptList)) {
            return null;
        }
        List<String> roadIdList = roadDeptList.stream().map(o -> o.getRoadId()).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("tenantId", tenantId);
        map.put("roadIdList", roadIdList);
        List<RoadInformation> roadInformationList = roadInformationMapper.getListByMap(map);
        return roadInformationList;
    }

    /**
     * 查询该部门下路段信息列表
     * @param tenantId
     * @param id
     * @return
     */
    private List<Section> getSectionList(String tenantId, String id) {
        List<SectionDept> sectionDeptList = sectionDeptMapper.selectList(new LambdaQueryWrapper<SectionDept>()
                .eq(SectionDept::getTenantId, tenantId)
                .eq(SectionDept::getDeptId, id));
        if (CollectionUtil.isEmpty(sectionDeptList)) {
            return null;
        }
        List<String> sectionIdList = sectionDeptList.stream().map(o -> o.getSectionId()).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("tenantId", tenantId);
        map.put("sectionIdList", sectionIdList);
        List<Section> sectionList = sectionMapper.getListByMap(map);
        return sectionList;
    }
}
