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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.conver.InspectionFileConverMapper;
import com.tuoheng.admin.conver.ReportConverMapper;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.InspectionFileStatusEnum;
import com.tuoheng.admin.enums.InspectionTypeEnum;
import com.tuoheng.admin.enums.code.report.QueryInspectionReportCodeEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.inspection.InspectionFileHandleReportVo;
import com.tuoheng.admin.vo.inspection.InspectionFileReportVo;
import com.tuoheng.admin.vo.inspection.InspectionReportVo;
import com.tuoheng.admin.vo.inspection.InspectionResultVo;
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.Arrays;
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-12
 */
@Slf4j
@Service
public class QueryInspectionHandleReportService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private  DeptMapper deptMapper;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private QuestionTypeMapper questionTypeMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private InspectionFileHandleMapper inspectionFileHandleMapper;

    public JsonResult getInspectionHandleReport(String id) {
        log.info("进入查看巡检处理报告业务");
        String tenantId = CurrentUserUtil.getTenantId();
        JsonResult result = this.check(tenantId, id);
        if (0 != result.getCode()) {
            log.info("进入查看巡检处理报告业务：校验失败：{}", result.getMsg());
            return result;
        }
        Report report = (Report) result.getData();
        InspectionReportVo inspectionReportVo = this.buildInspectionReportVo(report);
        return JsonResult.success(inspectionReportVo);
    }

    /**
     * 检查参数
     *
     * @param tenantId
     * @param id
     * @return
     */
    private JsonResult check(String tenantId, String id) {
        // 判断id是否为空
        if (StringUtils.isEmpty(id)) {
            return JsonResult.error(QueryInspectionReportCodeEnum.REPORT_ID_IS_NULL.getCode(), QueryInspectionReportCodeEnum.REPORT_ID_IS_NULL.getMsg());
        }

        // 判断报告是否存在
        Report report = reportMapper.selectOne(new LambdaQueryWrapper<Report>()
                .eq(Report::getTenantId, tenantId)
                .eq(Report::getId, id)
                .eq(Report::getMark, 1));
        if (null == report) {
            return JsonResult.error(QueryInspectionReportCodeEnum.REPORT_IS_NOT_EXIST.getCode(), QueryInspectionReportCodeEnum.REPORT_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success(report);
    }

    /**
     * 构造返回的数据列
     *
     * @param report
     * @return
     */
    private InspectionReportVo buildInspectionReportVo(Report report) {
        InspectionReportVo inspectionReportVo = ReportConverMapper.INSTANCE.fromReportToInspectionReportVo(report);
        List<InspectionFile> inspectionFileList = inspectionFileMapper.selectList(new LambdaQueryWrapper<InspectionFile>()
                                                    .eq(InspectionFile::getInspectionId, report.getInspectionId())
                                                    .in(InspectionFile::getStatus, GetInspectionFileStatusList.getStatusList())
                                                    .eq(InspectionFile::getMark, 1));

        List<InspectionFileReportVo> inspectionFileHandleVoList = InspectionFileConverMapper.INSTANCE.fromInspectionFileListToInspectionFileHandleVoList(inspectionFileList);

        List<InspectionFileHandle> inspectionFileHandleList = this.getInspectionFileHandleList(inspectionFileList);
        Map<String, InspectionFileHandle> inspectionFileHandleMap = this.getInspectionFileHandleMap(inspectionFileHandleList);
        Map<String, User> userMap = this.getUserMap(inspectionFileHandleList);
        if (null != inspectionFileHandleMap) {
            InspectionFileHandle inspectionFileHandle;
            InspectionFileHandleReportVo inspectionFileHandleReportVo;
            List<String> handlerImageList = null;
            for (InspectionFileReportVo inspectionFileReportVo : inspectionFileHandleVoList) {
                inspectionFileHandle = inspectionFileHandleMap.get(inspectionFileReportVo.getId());
                inspectionFileReportVo.setFileImage(CommonConfig.imageURL + inspectionFileReportVo.getFileImage());
                inspectionFileReportVo.setFileThumbnail(CommonConfig.imageURL + inspectionFileReportVo.getFileThumbnail());
                inspectionFileReportVo.setFileOriginal(CommonConfig.imageURL + inspectionFileReportVo.getFileOriginal());
                if (null != inspectionFileHandle) {
                    handlerImageList = new ArrayList<>();
                    String[] arr = inspectionFileHandle.getHandlerImage().split(",");
                    List<String> list = Arrays.stream(arr).map(String::toString).collect(Collectors.toList());
                    for (String str : list) {
                        handlerImageList.add(CommonConfig.imageURL + str);
                    }
                    inspectionFileHandleReportVo = new InspectionFileHandleReportVo();
                    if (CollectionUtil.isNotEmpty(userMap)) {
                        User user = userMap.get(inspectionFileHandle.getHandlerUser());
                        if (null != user) {
                            inspectionFileHandleReportVo.setHandlerUser(user.getRealname());
                        }
                    }
                    inspectionFileHandleReportVo.setHandlerResult(inspectionFileHandle.getHandlerResult());
                    inspectionFileHandleReportVo.setHandlerTime(inspectionFileHandle.getHandlerTime());
                    inspectionFileHandleReportVo.setHandlerImageList(handlerImageList);
                    inspectionFileReportVo.setInspectionFileHandleReportVo(inspectionFileHandleReportVo);
                }
            }
        }
        String deptName = this.getDeptName(report.getDeptId());
        List<InspectionResultVo> inspectionResultVoList = this.buildInspectionResult(report);
        inspectionReportVo.setDeptName(deptName);
        inspectionReportVo.setInspectionResultVoList(inspectionResultVoList);
        inspectionReportVo.setInspectionFileReportVoList(inspectionFileHandleVoList);

        // 机场任务没有设备名称，暂定使用机场名称作为设备名称
        if (InspectionTypeEnum.AIRPORT.getCode() == report.getInspectionType()) {
            inspectionReportVo.setEquipmentName(report.getAirportName());
        }
        return inspectionReportVo;
    }

    private List<InspectionFileHandle> getInspectionFileHandleList(List<InspectionFile> inspectionFileList) {
        List<String> inspectionFileIdList = inspectionFileList.stream().map(o -> o.getId()).collect(Collectors.toList());
        List<InspectionFileHandle> inspectionFileHandleList = null;
        if (!CollectionUtil.isEmpty(inspectionFileIdList)) {
            inspectionFileHandleList = inspectionFileHandleMapper.selectList(Wrappers.<InspectionFileHandle>lambdaQuery()
                    .in(InspectionFileHandle::getInspectionFileId, inspectionFileIdList)
                    .eq(InspectionFileHandle::getMark, 1));

        }
        if (CollectionUtil.isEmpty(inspectionFileIdList)) {
            return null;
        }
        return inspectionFileHandleList;
    }

    private Map<String, InspectionFileHandle> getInspectionFileHandleMap(List<InspectionFileHandle> inspectionFileHandleList) {
        if (CollectionUtil.isEmpty(inspectionFileHandleList)) {
            return null;
        }
        Map<String, InspectionFileHandle> inspectionFileHandleMap = inspectionFileHandleList.stream().collect(Collectors.toMap(InspectionFileHandle::getInspectionFileId, Function.identity()));
        return inspectionFileHandleMap;
    }

    /**
     * 获取用户列表，放到map，减少循环次数
     *
     * @param inspectionFileHandleList
     * @return
     */
    private Map<String, User> getUserMap(List<InspectionFileHandle> inspectionFileHandleList) {
        if (CollectionUtil.isEmpty(inspectionFileHandleList)) {
            return null;
        }
        List<String> userIdList = inspectionFileHandleList.stream().map(o -> o.getHandlerUser()).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(userIdList)) {
            return null;
        }
        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>()
                .in(User::getId, userIdList)
                .eq(User::getMark, 1));
        Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        return userMap;
    }

    /**
     * 获取部门路名称
     */
    private String getDeptName(String deptId) {
        if (StringUtils.isEmpty(deptId)) {
            return "";
        }
        Dept dept = deptMapper.selectOne(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getId, deptId)
                .eq(Dept::getMark, 1));
        if (null != dept) {
            return dept.getName();
        }
        return "";
    }

    private List<InspectionResultVo> buildInspectionResult(Report report) {
        List<InspectionResultVo> inspectionResultVoList = new ArrayList<>();
        List<QuestionType> questionTypeList = questionTypeMapper.selectList(new LambdaQueryWrapper<QuestionType>()
                .eq(QuestionType::getMark, 1));
        QuestionType questionType;
        InspectionResultVo inspectionResultVo;
        for (int i = 0; i < questionTypeList.size(); i++) {
            inspectionResultVo = new InspectionResultVo();
            questionType = questionTypeList.get(i);
            Integer count = this.getCount(report.getInspectionId(), questionType.getCode());
            inspectionResultVo.setQuestionTypeContent(questionType.getContent());
            inspectionResultVo.setCount(count);
            inspectionResultVoList.add(inspectionResultVo);
        }
        return inspectionResultVoList;
    }

    private Integer getCount(String inspectionId, String questionCode) {
        Integer count = inspectionFileMapper.selectCount(new LambdaQueryWrapper<InspectionFile>()
                .eq(InspectionFile::getInspectionId, inspectionId)
                .in(InspectionFile::getStatus, GetInspectionFileStatusList.getStatusList())
                .eq(InspectionFile::getQuestionCode, questionCode)
                .eq(InspectionFile::getMark, 1));
        return count;
    }

}
