package com.tuoheng.admin.service.road;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
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.RoadDept;
import com.tuoheng.admin.entity.RoadInformation;
import com.tuoheng.admin.entity.Section;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.DataPermissionEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.SectionEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.query.RoadInformationQuery;
import com.tuoheng.admin.service.road.query.QueryRoadListByDeptIdService;
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.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
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 RoadInformationServiceImpl extends BaseServiceImpl<RoadInformationMapper, RoadInformation> implements RoadInformationService {

    @Autowired
    private RoadInformationMapper roadInformationMapper;

    @Autowired
    private SectionMapper sectionMapper;

    @Autowired
    private QueryRoadListByDeptIdService queryRoadListByDeptIdService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private RoadDeptMapper roadDeptMapper;

    @Override
    public JsonResult queryPage(RoadInformationQuery query) {
        if (query.getLimit() == null && query.getPage() == null) {
            return JsonResult.error(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //获取超级管理员登录信息
        User user = CurrentUserUtil.getUserInfo();
        if (ObjectUtil.isNull(user)) {
            return JsonResult.error(SectionEnum.USER_IS_NOT_EXIST.getCode(), SectionEnum.USER_IS_NOT_EXIST.getMsg());
        }
        String tenantId = user.getTenantId(); // CurrentUserUtil.getTenantId();
        if (StringUtils.isEmpty(tenantId)) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        String deptId = user.getDeptId();
        if (StringUtils.isEmpty(deptId)) {
            return JsonResult.error(SectionEnum.DEPT_IS_NOT_EXIST.getCode(), SectionEnum.DEPT_IS_NOT_EXIST.getMsg());
        }
        //获取分页数据
        IPage<RoadInformation> page = new Page<>(query.getPage(), query.getLimit());
        IPage<RoadInformation> pageData = null;
        // 按拥有部门数据权限过滤公路数据
        // 所有部门权限
        if (DataPermissionEnum.ALL.getCode() == user.getDataPermission()) {
            pageData = roadInformationMapper.selectPage(page, Wrappers.<RoadInformation>lambdaQuery()
                    .eq(RoadInformation::getMark, MarkEnum.VALID.getCode())
                    .eq(RoadInformation::getTenantId, tenantId)
                    .orderByDesc(RoadInformation::getCreateTime));
        }
        // 本部门及下属部门权限
        else if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == user.getDataPermission()) {
            List<String> deptAndSubList = deptMapper.selectAllChildListById(deptId);
            if (StringUtils.isEmpty(deptAndSubList) && deptAndSubList.size() <= 0) {
                return JsonResult.error(SectionEnum.DEPT_ID_IS_NULL.getCode(), SectionEnum.DEPT_ID_IS_NULL.getMsg());
            }
            List<RoadDept> roadDeptList = roadDeptMapper.selectList(Wrappers.<RoadDept>lambdaQuery()
                    .eq(RoadDept::getTenantId, tenantId)
                    .in(RoadDept::getDeptId, deptAndSubList));
            List<String> roadIdList = roadDeptList.stream().map(t -> t.getRoadId()).collect(Collectors.toList());
            pageData = roadInformationMapper.selectPage(page, Wrappers.<RoadInformation>lambdaQuery()
                    .eq(RoadInformation::getMark, MarkEnum.VALID.getCode())
                    .eq(RoadInformation::getTenantId, tenantId)
                    .in(RoadInformation::getId, roadIdList)
                    .orderByDesc(RoadInformation::getCreateTime));
        }
        // 本部门权限
        else {
            List<RoadDept> roadDeptList = roadDeptMapper.selectList(Wrappers.<RoadDept>lambdaQuery()
                    .eq(RoadDept::getTenantId, tenantId)
                    .in(RoadDept::getDeptId, deptId));
            List<String> roadIdList = roadDeptList.stream().map(t -> t.getRoadId()).collect(Collectors.toList());
            pageData = roadInformationMapper.selectPage(page, Wrappers.<RoadInformation>lambdaQuery()
                    .eq(RoadInformation::getMark, MarkEnum.VALID.getCode())
                    .eq(RoadInformation::getTenantId, tenantId)
                    .in(RoadInformation::getId, roadIdList)
                    .orderByDesc(RoadInformation::getCreateTime));
        }

        List<RoadInformation> records = pageData.getRecords();
        List<RoadInformation> list = new ArrayList<>();
        for (RoadInformation record : records) {
            //判断公路关联路段信息
            RoadRelation(record);
            list.add(record);
        }
        pageData.setRecords(list);

        return JsonResult.success(pageData);
    }

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

        return JsonResult.success(list);
    }

    /**
     * 根据部门id获取该部门下公路列表
     *
     * @param deptId
     * @return
     */
    @Override
    public JsonResult getListByDeptId(String deptId) {
        return queryRoadListByDeptIdService.getRoadList(deptId);
    }

    @Override
    public JsonResult editInfo(RoadInformation 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 {
            //更新
            RoadInformation roadInformation = this.getOne(Wrappers.<RoadInformation>lambdaQuery().eq(RoadInformation::getId, entity.getId()));
            String code = entity.getCode();
            //当前公路的code是否重复判断
            if (!code.equals(roadInformation.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(RoadInformation entity) {
        List<RoadInformation> roadInformationList = roadInformationMapper.selectList(new LambdaQueryWrapper<RoadInformation>()
                .eq(RoadInformation::getTenantId, CurrentUserUtil.getTenantId())
                .eq(RoadInformation::getMark, MarkEnum.VALID.getCode())
                .eq(RoadInformation::getCode, entity.getCode()));
        if (CollectionUtil.isNotEmpty(roadInformationList)) {
            for (RoadInformation roadInformation : roadInformationList) {
                if (entity.getCode().equals(roadInformation.getCode())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 根据登录人角色获取该部门下公路信息列表
     *
     * @return
     */
    @Override
    public JsonResult getListByUserType() {
        //获取当前登录人信息  登录用户名
        User user = CurrentUserUtil.getUserInfo();
        //获取租户id
        String tenantId = user.getTenantId();
        //用户类型角色判断  1超级管理员 2 部门管理员 3普通用户
        if (null == user.getDataPermission()) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //登录用户若为部门管理员或普通用户需要查询所在部门
        String deptId = user.getDeptId();
        //获取公路列表
        List<RoadInformation> roadInformationList = new ArrayList<>();
        //超级管理员
        if (DataPermissionEnum.ALL.getCode() == user.getDataPermission()) {
            roadInformationList = this.getAllRoadInformationList(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<RoadDept> list = roadDeptMapper.selectListByDeptIdList(deptIdList);
            roadInformationList = this.getRoadInformationList(tenantId, list);
        }
        //普通用户
        if (DataPermissionEnum.DEPT.getCode() == user.getDataPermission()) {
            List<RoadDept> roadDeptList = roadDeptMapper.selectList(new LambdaQueryWrapper<RoadDept>()
                    .eq(RoadDept::getTenantId, tenantId)
                    .eq(RoadDept::getDeptId, deptId));
            if (CollectionUtil.isEmpty(roadDeptList)) {
                return null;
            }
            roadInformationList = this.getRoadInformationList(tenantId, roadDeptList);
        }
        return JsonResult.success(roadInformationList);
    }

    /**
     * 根据租户id获取公路列表
     *
     * @return
     */
    @Override
    public JsonResult getListByTenantId() {
        //获取当前租户下id
        String tenantId = CurrentUserUtil.getTenantId();
        if (StringUtils.isEmpty(tenantId)) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //查询公路列表
        List<RoadInformation> roadInformationList = roadInformationMapper.selectList(new LambdaQueryWrapper<RoadInformation>()
                .eq(RoadInformation::getTenantId, tenantId)
                .eq(RoadInformation::getMark, MarkEnum.VALID.getCode()));

        return JsonResult.success(roadInformationList);
    }

    /**
     * 根据部门列表获取公路列表
     *
     * @param tenantId
     * @param list
     * @return
     */
    private List<RoadInformation> getRoadInformationList(String tenantId, List<RoadDept> list) {
        List<RoadInformation> roadInformationList;
        List<String> roadIdList = list.stream().map(o -> o.getRoadId()).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("tenantId", tenantId);
        map.put("roadIdList", roadIdList);
        map.put("mark", MarkEnum.VALID.getCode());
        roadInformationList = roadInformationMapper.getListByMap(map);
        return roadInformationList;
    }

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

    /**
     * 判断公路是否关联路段
     *
     * @param roadInformation
     */
    private void RoadRelation(RoadInformation roadInformation) {
        List<Section> sectionList = sectionMapper.selectList(new LambdaQueryWrapper<Section>()
                .eq(Section::getMark, MarkEnum.VALID.getCode())
                .eq(Section::getTenantId, CurrentUserUtil.getTenantId())
                .eq(Section::getRoadId, roadInformation.getId()));
        if (StringUtils.isNotEmpty(sectionList)) {
            //公路绑定路段，关联字段设置为true
            roadInformation.setRelation(true);
        } else {
            //公路未绑定路段，关联字段设置为false
            roadInformation.setRelation(false);
        }
    }
}
