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.ChannelLegDto;
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 ChannelMapper channelMapper;

    @Autowired
    private LegMapper legMapper;

    @Autowired
    private ChannelDeptMapper channelDeptMapper;

    @Autowired
    private LegDeptMapper legDeptMapper;

    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<ChannelLegDto> channelLegDtoList = this.getChannelLegDtoList(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.setChannelLegDtoList(channelLegDtoList);
        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<ChannelLegDto> getChannelLegDtoList(String tenantId, String id) {
        // 获取该部门下航道列表
        List<Channel> channelList = this.getRoadInformationList(tenantId, id);
        if (CollectionUtil.isEmpty(channelList)) {
            // 不会出现此场景，在代码层面考虑健壮性，加此判断
            // 根据业务需求，添加部门时，必须添加航道和航段信息
            // 若航道数据为空，说明肯定也没也航段信息，不用继续往下判断，因此直接返回
            log.info("获取部门信息业务：航道信息为空");
            return null;
        }

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

        List<ChannelLegDto> channelLegDtoList = new ArrayList<>();
        ChannelLegDto channelLegDto;
        List<Leg> legListTmp;

        Map<String, Channel> channelMap = channelList.stream().collect(Collectors.toMap(Channel::getId, Function.identity()));
        Channel channel;
        for (Leg leg : legList) {
            channelLegDto = new ChannelLegDto();
            legListTmp = new ArrayList<>();
            legListTmp.add(leg);
            channel = channelMap.get(leg.getChannelId());
            if (ObjectUtil.isNull(channel)) {
                continue;
            }
            channelLegDto.setChannel(channel);
            channelLegDto.setLegList(legListTmp);
            channelLegDtoList.add(channelLegDto);
        }
        return channelLegDtoList;
    }

    /**
     * 查询该部门下航道信息列表
     * @param tenantId
     * @param id
     * @return
     */
    private List<Channel> getRoadInformationList(String tenantId, String id) {
        List<ChannelDept> channelDeptList = channelDeptMapper.selectList(new LambdaQueryWrapper<ChannelDept>()
                .eq(ChannelDept::getTenantId, tenantId)
                .eq(ChannelDept::getDeptId, id));
        if (CollectionUtil.isEmpty(channelDeptList)) {
            return null;
        }
        List<String> channelIdList = channelDeptList.stream().map(o -> o.getChannelId()).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("tenantId", tenantId);
        map.put("channelIdList", channelIdList);
        List<Channel> channelList = channelMapper.getListByMap(map);
        return channelList;
    }

    /**
     * 查询该部门下航段信息列表
     * @param tenantId
     * @param id
     * @return
     */
    private List<Leg> getLegList(String tenantId, String id) {
        List<LegDept> legDeptList = legDeptMapper.selectList(new LambdaQueryWrapper<LegDept>()
                .eq(LegDept::getTenantId, tenantId)
                .eq(LegDept::getDeptId, id));
        if (CollectionUtil.isEmpty(legDeptList)) {
            return null;
        }
        List<String> legIdList = legDeptList.stream().map(o -> o.getLegId()).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("tenantId", tenantId);
        map.put("legIdList", legIdList);
        List<Leg> legList = legMapper.getListByMap(map);
        return legList;
    }
}
