package com.tuoheng.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.UserTypeEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.query.RoadInformationQuery;
import com.tuoheng.admin.service.RoadInformationService;
import com.tuoheng.admin.service.road.query.QueryRoadListByDeptIdService;
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.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
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);
        }
        //获取登录人信息id
        //Long userId = SecurityUserUtils.getLoginUser().getUserId();
        //获取分页数据
        IPage<RoadInformation> page = new Page<>(query.getPage(), query.getLimit());
        IPage<RoadInformation> pageData = roadInformationMapper.selectPage(page, Wrappers.<RoadInformation>lambdaQuery()
                .eq(RoadInformation::getMark, 1)
                .eq(RoadInformation::getTenantId, 0)
                .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) {
        //当前租户下所有公路信息
        List<RoadInformation> roadInformationList = roadInformationMapper.selectList(new LambdaQueryWrapper<RoadInformation>()
                .eq(RoadInformation::getMark, 1)
                .eq(RoadInformation::getTenantId, 0));
        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) {
//        User user = (User) ThreadLocalUtil.get();
//        if (StringUtils.isNull(user)) {
//            return JsonResult.error("获取不到用户信息");
//        }
        if (StringUtils.isEmpty(entity.getId())) {
            //新增
            entity.setCreateUser("cw");
            entity.setCreateTime(DateUtils.now());
        } else {
            //更新
            entity.setUpdateUser("cw");
            entity.setUpdateTime(DateUtils.now());
        }
        super.edit(entity);

        return JsonResult.success();
    }

    /**
     * 根据登录人角色获取该部门下公路信息列表
     * @return
     */
    @Override
    public JsonResult getListByUserType() {
        //获取当前登录人信息  登录用户名
        //String username = SecurityUserUtils.username();
        String username="admin";
        if(StringUtils.isEmpty(username)){
            return JsonResult.error("登录用户名不存在");
        }
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getMark, 1)
                .eq(User::getUsername, username));
        if(null == user){
            return JsonResult.error("用户不存在");
        }
        //获取租户id
        String tenantId = user.getTenantId();
        //用户类型角色判断  1超级管理员 2 部门管理员 3普通用户
        if(null == user.getType()){
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //登录用户若为部门管理员或普通用户需要查询所在部门
        String deptId = user.getDeptId();
        //获取公路列表
        List<RoadInformation> roadInformationList = new ArrayList<>();
        if(null == deptId){
            //超级管理员
            if(UserTypeEnum.SUPER_ADMIN.getCode()== user.getType()){
                roadInformationList = this.getAllRoadInformationList(tenantId);
            }
        }
        //部门管理员
        if(UserTypeEnum.ADMIN.getCode() == user.getType()){
            //根据当前用户对应的部门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(UserTypeEnum.ORDINARY_USER.getCode() == user.getType()){
            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);
    }

    /**
     * 根据部门列表获取公路列表
     * @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",1);
        roadInformationList = roadInformationMapper.getListByMap(map);
        return roadInformationList;
    }

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

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