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.DataPermissionEnum;
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 ChannelMapper channelMapper;

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

        String userId = CurrentUserUtil.getUserId();
        String tenantId = CurrentUserUtil.getTenantId();
        request.setTenantId(tenantId);

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

        // 获取部门Id的查询范围
        List<String> deptIdList = this.getDeptIdList(userId, tenantId, 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 tenantId, 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::getTenantId, tenantId)
                    .eq(User::getMark, 1));
        if (DataPermissionEnum.ALL.getCode() == user.getDataPermission()) {
            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, Channel> channelMap = this.getRoadMap(inspectionFileExtendList);
        Map<String, Dept> deptMap = this.getDeptMap(inspectionFileExtendList);
        List<InspectionFilePageListVo> inspectionFilePageListVoList = InspectionFileConverMapper.INSTANCE.fromInspectionFileExtendListToInspectionFilePageListVoList(inspectionFileExtendList);
        Channel channel;
        Dept dept;
        for (InspectionFilePageListVo inspectionFilePageListVo : inspectionFilePageListVoList) {
            channel = channelMap.get(inspectionFilePageListVo.getChannelId());
            dept = deptMap.get(inspectionFilePageListVo.getDeptId());
            if (ObjectUtil.isNotNull(channel)) {
                inspectionFilePageListVo.setChannelName(channel.getName());
            }
            if (ObjectUtil.isNotNull(dept)) {
                inspectionFilePageListVo.setDeptName(dept.getName());
            }
            inspectionFilePageListVo.setFileImage(CommonConfig.imageURL + inspectionFilePageListVo.getFileImage());
            inspectionFilePageListVo.setFileThumbnail(CommonConfig.imageURL + inspectionFilePageListVo.getFileThumbnail());
            inspectionFilePageListVo.setFileOriginal(CommonConfig.imageURL + inspectionFilePageListVo.getFileOriginal());
        }
        return inspectionFilePageListVoList;
    }

    /**
     *
     * 获取航道列表，放到map，减少循环次数
     *
     * @param inspectionFileExtendList
     * @return
     */
    private Map<String, Channel> getRoadMap(List<InspectionFileExtend> inspectionFileExtendList) {
        List<String> channelIdList = inspectionFileExtendList.stream().map(o -> o.getChannelId()).collect(Collectors.toList());
        List<Channel> channelList = channelMapper.selectList(new LambdaQueryWrapper<Channel>()
                .in(Channel::getId, channelIdList)
                .eq(Channel::getMark, 1));
        Map<String, Channel> channelMap = channelList.stream().collect(Collectors.toMap(Channel::getId, Function.identity()));
        return channelMap;
    }

    /**
     *
     * 获取部门列表，放到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;
    }

}
