package com.tuoheng.admin.service.channel;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.DataPermissionEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.query.ChannelQuery;
import com.tuoheng.admin.service.channel.query.QueryChannelListByDeptIdService;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.common.BaseServiceImpl;
import com.tuoheng.common.core.enums.ServiceExceptionEnum;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.*;
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.stream.Collectors;

/**
 * @Author ChengWang
 * @Date 2022/11/17
 */
@Service
public class ChannelServiceImpl extends BaseServiceImpl<ChannelMapper, Channel> implements ChannelService {

    @Autowired
    private ChannelMapper channelMapper;

    @Autowired
    private LegMapper legMapper;

    @Autowired
    private QueryChannelListByDeptIdService queryChannelListByDeptIdService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private ChannelDeptMapper channelDeptMapper;

    @Override
    public JsonResult queryPage(ChannelQuery query) {
        if (query.getLimit() == null && query.getPage() == null) {
            return JsonResult.error(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //获取超级管理员登录信息
        String tenantId = CurrentUserUtil.getTenantId();
        if(StringUtils.isEmpty(tenantId)){
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //获取分页数据
        IPage<Channel> page = new Page<>(query.getPage(), query.getLimit());
        IPage<Channel> pageData = channelMapper.selectPage(page, Wrappers.<Channel>lambdaQuery()
                .eq(Channel::getMark, MarkEnum.VALID.getCode())
                .eq(Channel::getTenantId, tenantId)
                .orderByDesc(Channel::getCreateTime));
        List<Channel> records = pageData.getRecords();
        List<Channel> list = new ArrayList<>();
        for (Channel record : records) {
            //判断航道关联航段信息
            RoadRelation(record);
            list.add(record);
        }
        pageData.setRecords(list);

        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult getListInfo(ChannelQuery query) {
        //获取超级管理员登录信息
        String tenantId = CurrentUserUtil.getTenantId();
        if(StringUtils.isEmpty(tenantId)){
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //当前租户下所有航道信息
        List<Channel> channelList = channelMapper.selectList(new LambdaQueryWrapper<Channel>()
                .eq(Channel::getMark, MarkEnum.VALID.getCode())
                .eq(Channel::getTenantId, tenantId));
        List<Channel> list = new ArrayList<>();
        for (Channel channel : channelList) {
            RoadRelation(channel);
            list.add(channel);
        }

        return JsonResult.success(list);
    }

    /**
     * 根据部门id获取该部门下航道列表
     * @param deptId
     * @return
     */
    @Override
    public JsonResult getListByDeptId(String deptId) {
        return queryChannelListByDeptIdService.getChannelList(deptId);
    }

    @Override
    public JsonResult editInfo(Channel entity) {
        //获取当前超级管理员用户信息
        String userId = CurrentUserUtil.getUserId();
        if(StringUtils.isEmpty(userId)){
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        if(StringUtils.isEmpty(CurrentUserUtil.getTenantId())){
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        if (StringUtils.isEmpty(entity.getId())) {
            //新增
            if (this.getInformationListByCode(entity)) return JsonResult.error("航道已存在");
            entity.setCreateUser(userId);
            entity.setCreateTime(DateUtils.now());
            entity.setTenantId(CurrentUserUtil.getTenantId());
        } else {
            //更新
            Channel channel = this.getOne(Wrappers.<Channel>lambdaQuery().eq(Channel::getId, entity.getId()));
            String code = entity.getCode();
            //当前航道的code是否重复判断
            if(!code.equals(channel.getCode())){
                //code如果不存在则查询数据库中航道列表是否有重复的code
                if (this.getInformationListByCode(entity)) return JsonResult.error("航道已存在");
            }
            entity.setUpdateUser(userId);
            entity.setUpdateTime(DateUtils.now());
            entity.setTenantId(CurrentUserUtil.getTenantId());
        }
        super.edit(entity);

        return JsonResult.success();
    }
    //查询数据库中当前租户对应的航道列表
    private boolean getInformationListByCode(Channel entity) {
        List<Channel> channelList = channelMapper.selectList(new LambdaQueryWrapper<Channel>()
                .eq(Channel::getTenantId, CurrentUserUtil.getTenantId())
                .eq(Channel::getMark, MarkEnum.VALID.getCode())
                .eq(Channel::getCode,entity.getCode()));
        if(CollectionUtil.isNotEmpty(channelList)){
            for (Channel channel : channelList) {
                if(entity.getCode().equals(channel.getCode())){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 根据登录人角色获取该部门下航道信息列表
     * @return
     */
    @Override
    public JsonResult getListByUserType() {
        //获取当前登录人信息  登录用户名
        User user = CurrentUserUtil.getUserInfo();
        if(null == user){
            return JsonResult.error("用户不存在");
        }
        //获取租户id
        String tenantId = user.getTenantId();
        //用户类型角色判断  1超级管理员 2 部门管理员 3普通用户
        if(null == user.getDataPermission()){
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //登录用户若为部门管理员或普通用户需要查询所在部门
        String deptId = user.getDeptId();
        //获取航道列表
        List<Channel> channelList = new ArrayList<>();
        //超级管理员
        if(DataPermissionEnum.ALL.getCode()== user.getDataPermission()){
            channelList = this.getAllChannelList(tenantId);
        }
        //部门管理员
        if(DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == user.getDataPermission()){
            //根据当前用户对应的部门id获取该部门及子部门的id集合
            List<String> deptIdList = deptMapper.selectAllChildListById(deptId);
            if(CollectionUtil.isEmpty(deptIdList)){
                return null;
            }
            List<ChannelDept> list = channelDeptMapper.selectListByDeptIdList(deptIdList);
            channelList = this.getRoadInformationList(tenantId, list);
        }
        //普通用户
        if(DataPermissionEnum.DEPT.getCode() == user.getDataPermission()){
            List<ChannelDept> channelDeptList = channelDeptMapper.selectList(new LambdaQueryWrapper<ChannelDept>()
                    .eq(ChannelDept::getTenantId, tenantId)
                    .eq(ChannelDept::getDeptId, deptId));
            if (CollectionUtil.isEmpty(channelDeptList)) {
                return null;
            }
            channelList =this.getRoadInformationList(tenantId,channelDeptList);
        }
        return JsonResult.success(channelList);
    }

    /**
     * 根据部门列表获取航道列表
     * @param tenantId
     * @param list
     * @return
     */
    private List<Channel> getRoadInformationList(String tenantId, List<ChannelDept> list) {
        List<Channel> channelList;
        List<String> channelIdList = list.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());
        channelList = channelMapper.getListByMap(map);
        return channelList;
    }

    /**
     * 如果是顶级部门，则查询所有航道列表
     *
     * @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 channel
     */
    private void RoadRelation(Channel channel) {
        List<Leg> legList = legMapper.selectList(new LambdaQueryWrapper<Leg>()
                .eq(Leg::getMark, MarkEnum.VALID.getCode())
                .eq(Leg::getTenantId, CurrentUserUtil.getTenantId())
                .eq(Leg::getChannelId, channel.getId()));
        if (StringUtils.isNotEmpty(legList)) {
            //航道绑定航段，关联字段设置为true
            channel.setRelation(true);
        } else {
            //航道未绑定航段，关联字段设置为false
            channel.setRelation(false);
        }
    }
}
