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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.Dept;
import com.tuoheng.admin.entity.ChannelDept;
import com.tuoheng.admin.entity.Channel;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.code.channel.QueryChannelListByDeptIdCodeEnum;
import com.tuoheng.admin.mapper.DeptMapper;
import com.tuoheng.admin.mapper.ChannelDeptMapper;
import com.tuoheng.admin.mapper.ChannelMapper;
import com.tuoheng.admin.utils.CurrentUserUtil;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 根据部门Id查询航道列表业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-11-22
 */
@Slf4j
@Service
public class QueryChannelListByDeptIdService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private ChannelMapper channelMapper;

    @Autowired
    private ChannelDeptMapper channelDeptMapper;

    public JsonResult getChannelList(String deptId) {
        log.info("进入根据部门Id查询航道列表业务");
        String tenantId = CurrentUserUtil.getTenantId();

        // 校验
        JsonResult result = this.check(tenantId, deptId);
        if (0 != result.getCode()) {
            log.info("根据部门Id查询航道列表业务：校验失败：{}", result.getMsg());
            return result;
        }

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

        // 获取航道列表
//        List<RoadInformation> channelList;
//        if (SystemConstant.ROOT_DEPT_PID.equals(dept.getPid())) {
//            // 顶级部门获取所有的航道列表
//            channelList = this.getAllRoadInformationList(tenantId);
//        } else {
//            // 非顶级部门获取该部门下航道列表
//            channelList = this.getRoadInformationListByDeptId(tenantId, deptId);
//        }
        // 获取航道列表
        List<Channel> channelList = this.getChannelListByDeptId(tenantId, dept.getId());
        if (CollectionUtil.isEmpty(channelList)) {
            log.info("根据部门Id查询航道列表业务：航道信息为空");
            return JsonResult.error(QueryChannelListByDeptIdCodeEnum.ROAD_LIST_IS_NULL.getCode(), QueryChannelListByDeptIdCodeEnum.ROAD_LIST_IS_NULL.getMsg());
        }
        return JsonResult.success(channelList);
    }

    /**
     * 检查参数
     *
     * @param tenantId
     * @param id
     * @return
     */
    private JsonResult check(String tenantId, String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonResult.error(QueryChannelListByDeptIdCodeEnum.DEPT_ID_IS_NULL.getCode(), QueryChannelListByDeptIdCodeEnum.DEPT_ID_IS_NULL.getMsg());
        }
        // 判断部门是否存在
        Dept dept;
        if (SystemConstant.ROOT_DEPT_PID.equals(id)) {
            dept = deptMapper.selectOne(new LambdaQueryWrapper<Dept>()
                    .eq(Dept::getTenantId, tenantId)
                    .eq(Dept::getPid, id)
                    .eq(Dept::getMark, MarkEnum.VALID.getCode()));
        } else {
            dept = deptMapper.selectOne(new LambdaQueryWrapper<Dept>()
                    .eq(Dept::getTenantId, tenantId)
                    .eq(Dept::getId, id)
                    .eq(Dept::getMark, MarkEnum.VALID.getCode()));
        }
        if (null == dept) {
            return JsonResult.error(QueryChannelListByDeptIdCodeEnum.DEPT_IS_NOT_EXIST.getCode(), QueryChannelListByDeptIdCodeEnum.DEPT_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success(dept);
    }

    /**
     * 如果是顶级部门，则查询所有航道列表
     *
     * @param tenantId
     * @return
     */
    private List<Channel> getAllChannelList(String tenantId) {
        List<Channel> channelList = channelMapper.selectList(new LambdaQueryWrapper<Channel>()
                .eq(Channel::getTenantId, tenantId)
                .eq(Channel::getMark, MarkEnum.VALID.getCode()));
        if (CollectionUtil.isEmpty(channelList)) {
            return null;
        }
        return channelList;
    }

    /**
     * 如果是非顶级部门，则查询该部门下航道信息列表
     *
     * @param tenantId
     * @param deptId
     * @return
     */
    private List<Channel> getChannelListByDeptId(String tenantId, String deptId) {
        List<ChannelDept> channelDeptList = channelDeptMapper.selectList(new LambdaQueryWrapper<ChannelDept>()
                .eq(ChannelDept::getTenantId, tenantId)
                .eq(ChannelDept::getDeptId, deptId));
        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);
        map.put("mark",MarkEnum.VALID.getCode());
        List<Channel> channelList = channelMapper.getListByMap(map);
        return channelList;
    }

}
