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

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.extension.plugins.pagination.Page;
import com.tuoheng.admin.conver.InspectionFileConverMapper;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.RoleEnum;
import com.tuoheng.admin.enums.code.inspection.QueryInspectionPageListCodeEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.request.inspectionfile.QueryInspectionFilePageListRequest;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.inspection.InspectionFilePageListVo;
import com.tuoheng.common.core.config.common.CommonConfig;
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.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 查询任务问题分页列表业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-12-05
 */
@Slf4j
@Service
public class QueryInspectionFilePageListService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private QuestionTypeMapper questionTypeMapper;

    @Autowired
    private RoadInformationMapper roadInformationMapper;

    public JsonResult getPageList(QueryInspectionFilePageListRequest request) {
        log.info("进入查询任务问题分页列表业务, request:{}", request.toString());

        String userId = CurrentUserUtil.getUserId();

        JsonResult result = this.check(request);
        if (0 != result.getCode()) {
            log.info("进入查询任务问题分页列表业务：校验失败：{}", result.getMsg());
            return result;
        }

        // 获取部门Id的查询范围
        List<String> deptIdList = this.getDeptIdList(userId, request.getDeptId());
        request.setDeptIdList(deptIdList);

        // 设置分页参数
        IPage<InspectionFile> page = new Page<>(request.getPage(), request.getLimit());
        // 查询结果
        IPage<InspectionFileExtend> pageData = inspectionFileMapper.selectPageList(page, request);
        if (null == pageData || pageData.getTotal() == 0) {
            log.info("获取任务分页列表为空");
            return JsonResult.success(null, QueryInspectionPageListCodeEnum.DATA_IS_FAILED.getMsg());
        }

        // 构造返回结果对象
        List<InspectionFilePageListVo> inspectionFilePageListVoList = this.buildInspectionFilePageListVoList(pageData.getRecords());

        // 重写返回结果对象
        IPage<InspectionFilePageListVo> inspectionFilePageListVoPageData = new Page<>();
        inspectionFilePageListVoPageData.setPages(pageData.getPages());
        inspectionFilePageListVoPageData.setCurrent(pageData.getCurrent());
        inspectionFilePageListVoPageData.setSize(pageData.getSize());
        inspectionFilePageListVoPageData.setTotal(pageData.getTotal());
        inspectionFilePageListVoPageData.setRecords(inspectionFilePageListVoList);

        return JsonResult.success(inspectionFilePageListVoPageData);
    }

    /**
     * 检查参数
     *
     * @param request
     * @return
     */
    private JsonResult check(QueryInspectionFilePageListRequest request) {

        return JsonResult.success();
    }

    /**
     *  获取部门Id的查询范围
     *  1）、deptId：如果传了值，查该部门的任务
     *  2）、deptId：如果没有传值
     *      2.1）、管理员：可查全部确认问题
     *      2.2）、管理员/普通用户：本部门及子部门创建的任务中已确认问题
     *
     * @param deptId
     * @return
     */
    private List<String> getDeptIdList(String userId, String deptId) {
        List<String> deptIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(deptId)) {
            deptIdList.add(deptId);
            return deptIdList;
        }
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getId, userId)
                    .eq(User::getMark, 1));
        if (RoleEnum.SUPER_ADMIN.getCode() == user.getRoleId()) {
            return null;
        } else {
            deptIdList = deptMapper.selectAllChildListById(user.getDeptId());
            return deptIdList;
        }
    }

    /**
     *  1）、设置问题类型字段
     *  2）、设置公路名称字段
     *  3）、设置部门名称字段
     *  4）、设置缩略图字段
     *
     * @param inspectionFileExtendList
     * @return
     */
    private List<InspectionFilePageListVo> buildInspectionFilePageListVoList(List<InspectionFileExtend> inspectionFileExtendList) {
        Map<String, RoadInformation> roadMap = this.getRoadMap(inspectionFileExtendList);
        Map<String, Dept> deptMap = this.getDeptMap(inspectionFileExtendList);
        Map<String, QuestionType> questionTypeMap = this.getQuestionTypeMap();
        List<InspectionFilePageListVo> inspectionFilePageListVoList = InspectionFileConverMapper.INSTANCE.fromInspectionFileExtendListToInspectionFilePageListVoList(inspectionFileExtendList);
        QuestionType questionType;
        RoadInformation road;
        Dept dept;
        for (InspectionFilePageListVo inspectionFilePageListVo : inspectionFilePageListVoList) {
            questionType = questionTypeMap.get(inspectionFilePageListVo.getQuestionId());
            if (null != questionType) {
                inspectionFilePageListVo.setQuestionName(Integer.toString(questionType.getName()));
                inspectionFilePageListVo.setQuestionContent(questionType.getContent());
            }
            road = roadMap.get(inspectionFilePageListVo.getRoadId());
            dept = deptMap.get(inspectionFilePageListVo.getDeptId());
            if (ObjectUtil.isNotNull(road)) {
                inspectionFilePageListVo.setRoadName(road.getName());
            }
            if (ObjectUtil.isNotNull(dept)) {
                inspectionFilePageListVo.setDeptName(dept.getName());
            }
            inspectionFilePageListVo.setFileThumbnail(CommonConfig.imageURL + inspectionFilePageListVo.getFileThumbnail());
        }
        return inspectionFilePageListVoList;
    }

    /**
     *
     * 获取公路列表，放到map，减少循环次数
     *
     * @param inspectionFileExtendList
     * @return
     */
    private Map<String, RoadInformation> getRoadMap(List<InspectionFileExtend> inspectionFileExtendList) {
        List<String> roadIdList = inspectionFileExtendList.stream().map(o -> o.getRoadId()).collect(Collectors.toList());
        List<RoadInformation> roadList = roadInformationMapper.selectList(new LambdaQueryWrapper<RoadInformation>()
                .in(RoadInformation::getId, roadIdList)
                .eq(RoadInformation::getMark, 1));
        Map<String, RoadInformation> roadMap = roadList.stream().collect(Collectors.toMap(RoadInformation::getId, Function.identity()));
        return roadMap;
    }

    /**
     *
     * 获取部门列表，放到map，减少循环次数
     *
     * @param inspectionFileExtendList
     * @return
     */
    private Map<String, Dept> getDeptMap(List<InspectionFileExtend> inspectionFileExtendList) {
        List<String> deptIdList = inspectionFileExtendList.stream().map(o -> o.getDeptId()).collect(Collectors.toList());
        List<Dept> deptList = deptMapper.selectList(new LambdaQueryWrapper<Dept>()
                .in(Dept::getId, deptIdList)
                .eq(Dept::getMark, 1));
        Map<String, Dept> deptMap = deptList.stream().collect(Collectors.toMap(Dept::getId, Function.identity()));
        return deptMap;
    }

    /**
     *
     * 获取问题类型列表，放到map，减少循环次数
     *
     * @return
     */
    private Map<String, QuestionType> getQuestionTypeMap() {
        List<QuestionType> questionTypeList = questionTypeMapper.selectList(new LambdaQueryWrapper<QuestionType>()
                .eq(QuestionType::getMark, 1));

        Map<String, QuestionType> questionTypeMap = questionTypeList.stream().collect(Collectors.toMap(QuestionType::getId, Function.identity()));
        return questionTypeMap;
    }

}
