package com.tuoheng.admin.service.section;


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.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuoheng.admin.entity.RoadInformation;
import com.tuoheng.admin.entity.Section;
import com.tuoheng.admin.entity.SectionDept;
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.DeptMapper;
import com.tuoheng.admin.mapper.RoadInformationMapper;
import com.tuoheng.admin.mapper.SectionDeptMapper;
import com.tuoheng.admin.mapper.SectionMapper;
import com.tuoheng.admin.query.SectionQuery;
import com.tuoheng.admin.service.section.query.QuerySectionListByDeptIdService;
import com.tuoheng.admin.service.section.query.QuerySectionListByRoadIdAndDeptIdService;
import com.tuoheng.admin.service.section.query.QuerySectionListByRoadIdService;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.SectionInfoVo;
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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author ChengWang
 * @Date 2022/11/17
 */
@Service
public class SectionServiceImpl extends BaseServiceImpl<SectionMapper, Section> implements ISectionService {

    @Autowired
    private SectionMapper sectionMapper;

    @Autowired
    private RoadInformationMapper roadInformationMapper;

    @Autowired
    private SectionDeptMapper sectionDeptMapper;

    @Autowired
    private QuerySectionListByDeptIdService querySectionListByDeptIdService;

    @Autowired
    private QuerySectionListByRoadIdService querySectionListByRoadIdService;

    @Autowired
    private QuerySectionListByRoadIdAndDeptIdService querySectionListByRoadIdAndDeptIdService;

    @Autowired
    private DeptMapper deptMapper;


    /**
     * 获取路段列表(分页)
     *
     * @param query
     * @return
     */
    @Override
    public JsonResult queryPage(SectionQuery query) {
        if (null == query.getLimit() && null == query.getPage()) {
            throw new ServiceException(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();
        IPage<Section> pageData = null; // new Page<>(query.getPage(), query.getLimit());
        IPage<Section> page = new Page<>(query.getPage(), query.getLimit());
        // 所有部门权限
        if (DataPermissionEnum.ALL.getCode() == user.getDataPermission()) {
            //获取分页数据
            pageData = sectionMapper.selectPage(page, Wrappers.<Section>lambdaQuery()
                    .eq(Section::getMark, 1)
                    .eq(Section::getTenantId, tenantId)
                    .orderByDesc(Section::getCreateTime));
            List<Section> records = pageData.getRecords();
            List<Section> list = new ArrayList<>();
            for (Section record : records) {
                //获取每条路段对应的公路id
                RoadInformation roadInformation = roadInformationMapper.selectOne(Wrappers.<RoadInformation>lambdaQuery()
                        .eq(RoadInformation::getId, record.getRoadId())
                        .eq(RoadInformation::getMark, 1));
                if (StringUtils.isNotNull(roadInformation)) {
                    if (StringUtils.isNotEmpty(roadInformation.getCode())) {
                        record.setCode(roadInformation.getCode());
                    }
                }
                //判断路段是否关联部门
                SectionRelation(record);
                list.add(record);
            }
            pageData.setRecords(list);
        }
        // 查看本部门及下属部门
        else if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == user.getDataPermission()
                || DataPermissionEnum.DEPT.getCode() == user.getDataPermission()) {
            //获取分页数据
//            IPage<Section> page = new Page<>(query.getPage(), query.getLimit());
            //获取当前部门及其子部门列表
            String deptId = user.getDeptId();
            if (StringUtils.isEmpty(deptId)) {
                return JsonResult.error(SectionEnum.DEPT_IS_NOT_EXIST.getCode(), SectionEnum.DEPT_IS_NOT_EXIST.getMsg());
            }
            List<String> deptList = new ArrayList<>();
            // 本部门及子部门权限
            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());
                }
                deptList.addAll(deptAndSubList);
            }
            // 本部门权限
            else {
                deptList.add(deptId);
            }
            //根据部门列表查对应的部门路段数据列表
            List<SectionDept> sectionDeptList = sectionDeptMapper.selectList(Wrappers.<SectionDept>lambdaQuery()
                    .eq(SectionDept::getTenantId, tenantId)
                    .in(SectionDept::getDeptId, deptList));
            if (StringUtils.isEmpty(sectionDeptList) && sectionDeptList.size() <= 0) {
                return JsonResult.error(SectionEnum.DEPT_SECTION_IS_NOT_EXIST.getCode(), SectionEnum.DEPT_SECTION_IS_NOT_EXIST.getMsg());
            }

            //查询对应的路段列表
            List<String> sectionIdList = sectionDeptList.stream().map(t -> t.getSectionId()).collect(Collectors.toList());
            if (StringUtils.isEmpty(sectionIdList)) {
                return JsonResult.error(SectionEnum.SECTION_ID_IS_NULL.getCode(), SectionEnum.SECTION_ID_IS_NULL.getMsg());
            }
            //根据路段id列表获取对应的路段信息
            pageData = sectionMapper.selectPage(page, Wrappers.<Section>lambdaQuery()
                    .eq(Section::getMark, 1)
                    .eq(Section::getTenantId, tenantId)
                    .in(Section::getId, sectionIdList)
                    .orderByDesc(Section::getCreateTime));
            List<Section> records = pageData.getRecords();
            List<Section> list = new ArrayList<>();
            for (Section record : records) {
                //获取每条路段对应的公路id
                RoadInformation roadInformation = roadInformationMapper.selectOne(Wrappers.<RoadInformation>lambdaQuery()
                        .eq(RoadInformation::getId, record.getRoadId())
                        .eq(RoadInformation::getMark, 1));
                if (StringUtils.isNotNull(roadInformation)) {
                    if (StringUtils.isNotEmpty(roadInformation.getCode())) {
                        record.setCode(roadInformation.getCode());
                    }
                }
                //判断路段是否关联部门
                SectionRelation(record);
                list.add(record);
            }
            pageData.setRecords(list);
        }
        return JsonResult.success(pageData);
    }

    //对路段范围进行处理
    private String getSectionRanges(Section record) {
        //路段范围属性
        String sectionRange = record.getSectionRange();
        String[] sectionRanges = sectionRange.split(",");
        sectionRange = "K" + sectionRanges[0] + "+" + sectionRanges[1] + "~" + "K" + sectionRanges[2] + "+" + sectionRanges[3];
        return sectionRange;
    }

    @Override
    public JsonResult getListInfo(SectionQuery query) {
        //获取当前登录人信息
        String tenantId = CurrentUserUtil.getTenantId();
        if (StringUtils.isEmpty(tenantId)) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        List<Section> sectionList = sectionMapper.selectList(new LambdaQueryWrapper<Section>()
                .eq(Section::getMark, 1)
                .eq(Section::getTenantId, tenantId)
                .orderByDesc(Section::getCreateTime));
        List<Section> list = new ArrayList<>();
        for (Section section : sectionList) {
            //判断路段是否关联部门
            SectionRelation(section);
            list.add(section);
        }

        return JsonResult.success(list);
    }

    /**
     * 根据部门id获取该部门下路段信息列表
     *
     * @param deptId
     * @return
     */
    @Override
    public JsonResult getListByDeptId(String deptId) {
        return querySectionListByDeptIdService.getList(deptId);
    }

    /**
     * 根据公路id获取该公路下路段信息列表
     *
     * @param roadId
     * @return
     */
    @Override
    public JsonResult getListByRoadId(String roadId) {
        return querySectionListByRoadIdService.getList(roadId);
    }

    @Override
    public JsonResult getListByRoadIdAndDeptId(String roadId, String deptId) {
        return querySectionListByRoadIdAndDeptIdService.getList(roadId, deptId);
    }

    @Override
    public JsonResult editInfo(Section entity) {
        //超级管理员可以进行新增和编辑，普通用户不能进行此操作,部门管理员可以进行修改经纬度
        String userId = CurrentUserUtil.getUserId();
        String tenantId = CurrentUserUtil.getTenantId();
        if (StringUtils.isEmpty(tenantId)) {
            return JsonResult.error("租户id为空");
        }
        if (StringUtils.isEmpty(entity.getId())) {
            //新增
            entity.setCreateTime(DateUtils.now());
            entity.setCreateUser(userId);
            entity.setTenantId(tenantId);
        } else {
            //更新
            entity.setUpdateTime(DateUtils.now());
            entity.setUpdateUser(userId);
            entity.setTenantId(tenantId);
        }
        super.edit(entity);

        return JsonResult.success();
    }

    @Override
    public JsonResult getSectionInfo(String sectionId) {
        if (StringUtils.isEmpty(sectionId)) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //根据id查询路段
        Section section = sectionMapper.selectOne(Wrappers.<Section>lambdaQuery()
                .eq(Section::getMark, 1).eq(Section::getId, sectionId));
        String roadId = section.getRoadId();
        if (StringUtils.isEmpty(roadId)) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //根据roadId查询对应的公路
        RoadInformation roadInformation = roadInformationMapper.selectOne(new LambdaQueryWrapper<RoadInformation>()
                .eq(RoadInformation::getId, roadId)
                .eq(RoadInformation::getMark, 1));
        //获取公路代号
        if (StringUtils.isNull(roadInformation)) {
            return JsonResult.error("对应的公路为空");
        }
        String code = roadInformation.getCode();
        if (StringUtils.isEmpty(code)) {
            return JsonResult.error("公路代号为空");
        }
        SectionInfoVo sectionInfoVo = new SectionInfoVo();
        BeanUtils.copyProperties(section, sectionInfoVo);
        sectionInfoVo.setCode(code);

        return JsonResult.success(sectionInfoVo);
    }

    @Override
    public JsonResult getSectionList() {
        //获取当前登录人信息 登录用户名
        User user = CurrentUserUtil.getUserInfo();
        if (ObjectUtils.isEmpty(user)) {
            return JsonResult.error(SectionEnum.USER_IS_NOT_EXIST.getCode());
        }
        String tenantId = CurrentUserUtil.getTenantId();
        //超级管理员获取当前租户下全部公路，部门管理员和普通用户显示用户所属部门监管范围路段之和
        if (null == user.getDataPermission()) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //登录用户若为部门管理员或普通用户需要查询所在部门
        String deptId = user.getDeptId();
        List<Section> list = new ArrayList<>();
        List<RoadInformation> roadInformationList = new ArrayList<>();

        //超级管理员
        if (DataPermissionEnum.ALL.getCode() == user.getDataPermission()) {
            roadInformationList = this.getAllRoadInformationList(tenantId);
            return JsonResult.success(roadInformationList);
        }

        //部门管理员和普通用户
        if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == user.getDataPermission() || DataPermissionEnum.DEPT.getCode() == user.getDataPermission()) {
            //对应部门下的路段列表
            List<SectionDept> sectionDeptList = sectionDeptMapper.selectList(new LambdaQueryWrapper<SectionDept>()
                    .eq(SectionDept::getDeptId, deptId).eq(SectionDept::getTenantId, tenantId));
            //获取对应的路段列表
            List<String> sectionList = sectionDeptList.stream().map(t -> t.getSectionId()).collect(Collectors.toList());
            //获取当前租户当前部门下的路段列表
            list = sectionMapper.selectList(Wrappers.<Section>lambdaQuery()
                    .eq(Section::getTenantId, tenantId)
                    .eq(Section::getMark, MarkEnum.VALID.getCode())
                    .in(Section::getId, sectionList));
            List<Section> sections = new ArrayList<>();
            for (Section section : list) {
                String roadId = section.getRoadId();
                //每条路段对应的公路代号
                RoadInformation roadInformation = roadInformationMapper.selectOne(Wrappers.<RoadInformation>lambdaQuery()
                        .eq(RoadInformation::getTenantId, tenantId)
                        .eq(RoadInformation::getId, roadId)
                        .eq(RoadInformation::getMark, MarkEnum.VALID.getCode()));
                if (roadInformation != null) {
                    section.setCode(roadInformation.getCode());
                }
                sections.add(section);
            }
            return JsonResult.success(sections);
        }

        return JsonResult.error(SectionEnum.QUERY_IS_FAILED.getCode());
    }


    /**
     * 如果是顶级部门，则查询所有公路列表
     *
     * @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;
    }


    private void SectionRelation(Section section) {
        List<SectionDept> sectionDeptList = sectionDeptMapper.selectList(Wrappers.<SectionDept>lambdaQuery()
                .eq(SectionDept::getTenantId, CurrentUserUtil.getTenantId())
                .eq(SectionDept::getSectionId, section.getId()));
        if (StringUtils.isNotEmpty(sectionDeptList)) {
            //路段关联与部门关联，设置关联字段为true
            section.setRelation(true);
        } else {
            section.setRelation(false);
        }
    }


}
