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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.QueryInspectionFileDistributionListRequest;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.inspection.InspectionFileDistributionListVo;
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.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

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

    @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 getList(QueryInspectionFileDistributionListRequest 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);
        request.setDeptIdList(deptIdList);

        // 查询结果
        List<InspectionFileDistribution> inspectionFileDistributionList = inspectionFileMapper.selectDistributionList(request);
        if (null == inspectionFileDistributionList || inspectionFileDistributionList.size() == 0) {
            log.info("获取任务问题分布列表为空");
            return JsonResult.success(inspectionFileDistributionList);
        }

        // 构造返回结果对象
        List<InspectionFileDistributionListVo> inspectionFileDistributionListVoList = this.buildInspectionFileDistributionListVo(inspectionFileDistributionList);

        return JsonResult.success(inspectionFileDistributionListVoList);
    }

    /**
     * 检查参数
     *
     * @param request
     * @return
     */
    private JsonResult check(QueryInspectionFileDistributionListRequest request) {
        return JsonResult.success();
    }

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

    /**
     *  1）、设置问题类型字段
     *  2）、设置缩略图字段
     *
     * @param inspectionFileDistributionList
     * @return
     */
    private List<InspectionFileDistributionListVo> buildInspectionFileDistributionListVo(List<InspectionFileDistribution> inspectionFileDistributionList) {
        Map<String, QuestionType> questionTypeMap = this.getQuestionTypeMap();
        List<InspectionFileDistributionListVo> inspectionFileDistributionListVoList = InspectionFileConverMapper.INSTANCE.fromInspectionFileDistributionListToInspectionFileDistributionListVoList(inspectionFileDistributionList);
        QuestionType questionType;
        for (InspectionFileDistributionListVo inspectionFileDistributionListVo : inspectionFileDistributionListVoList) {
            questionType = questionTypeMap.get(inspectionFileDistributionListVo.getQuestionId());
            if (null != questionType) {
                inspectionFileDistributionListVo.setQuestionName(questionType.getContent());
            }
            if (StringUtils.isNotEmpty(inspectionFileDistributionListVo.getFileImage())) {
                inspectionFileDistributionListVo.setFileImage(CommonConfig.imageURL + inspectionFileDistributionListVo.getFileImage());
            }
            if (StringUtils.isNotEmpty(inspectionFileDistributionListVo.getFileThumbnail())) {
                inspectionFileDistributionListVo.setFileThumbnail(CommonConfig.imageURL + inspectionFileDistributionListVo.getFileThumbnail());
            }
            if (StringUtils.isNotEmpty(inspectionFileDistributionListVo.getFileOriginal())) {
                inspectionFileDistributionListVo.setFileOriginal(CommonConfig.imageURL + inspectionFileDistributionListVo.getFileOriginal());
            }
        }
        return inspectionFileDistributionListVoList;
    }

    /**
     *
     * 获取问题类型列表，放到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;
    }

}
