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

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.extension.plugins.pagination.Page;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.code.inspection.QueryInspectionPageListCodeEnum;
import com.tuoheng.admin.enums.code.inspectionfile.QueryInspectionFilePageListByWorkOrderIdCodeEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.request.inspectionfile.QueryInspectionFileWorkOrderPageListRequest;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.inspection.InspectionFileHandleVo;
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.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *  根据工单ID查询工单问题列表业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-12-08
 */
@Slf4j
@Service
public class QueryInspectionFilePageListByWorkOrderIdService {

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

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private InspectionFileHandleMapper inspectionFileHandleMapper;

    @Autowired
    private QuestionTypeMapper questionTypeMapper;

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Autowired
    private WorkOrderFileMapper workOrderFileMapper;

    public JsonResult getPageList(QueryInspectionFileWorkOrderPageListRequest request) {
        log.info("进入根据工单ID查询工单问题列表表业务, workOrderId:{}", request.getWorkOrderId());
        JsonResult result = this.check(request.getWorkOrderId());
        if (0 != result.getCode()) {
            log.info("根据工单ID查询工单问题列表业务：校验失败：{}", result.getMsg());
            return result;
        }

        String tenantId = CurrentUserUtil.getTenantId();

        // 设置分页参数
        IPage<WorkOrderFile> page = new Page<>(request.getPage(), request.getLimit());
        // 查询结果
        IPage<WorkOrderFile> pageData = workOrderFileMapper.selectPage(page, new LambdaQueryWrapper<WorkOrderFile>()
                                        .eq(WorkOrderFile::getTenantId, tenantId)
                                        .eq(WorkOrderFile::getWorkOrderId, request.getWorkOrderId()));

        if (null == pageData || pageData.getTotal() == 0) {
            log.info("根据工单ID查询工单问题列表业务：获取任务分页列表为空");
            return JsonResult.success(pageData);
        }

        List<WorkOrderFile> workOrderFileList = pageData.getRecords();

        List<String> inspectionFileIdList = workOrderFileList.stream().map(o -> o.getInspectionFileId()).collect(Collectors.toList());

        List<InspectionFile> inspectionFileList = inspectionFileMapper.selectList(new LambdaQueryWrapper<InspectionFile>()
                .in(InspectionFile::getId, inspectionFileIdList)
                .eq(InspectionFile::getTenantId, tenantId)
                .eq(InspectionFile::getMark, 1));

        // 构造返回结果对象
        List<InspectionFileHandleVo> inspectionFileHandleVoList = this.buildInspectionFileHandleVoList(request.getWorkOrderId(), inspectionFileIdList, inspectionFileList);

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

        return JsonResult.success(inspectionFilePageListVoPageData);
    }

    /**
     * 检查参数
     *
     * @param workOrderId
     * @return
     */
    private JsonResult check(String workOrderId) {
        if (StringUtils.isEmpty(workOrderId)) {
            return JsonResult.error(QueryInspectionFilePageListByWorkOrderIdCodeEnum.WORK_ORDER_ID_IS_NULL.getCode(), QueryInspectionFilePageListByWorkOrderIdCodeEnum.WORK_ORDER_ID_IS_NULL.getMsg());
        }
        WorkOrder workOrder = workOrderMapper.selectOne( new LambdaQueryWrapper<WorkOrder>()
                                .eq(WorkOrder::getId, workOrderId)
                                .eq(WorkOrder::getMark, 1));
        if (null == workOrder) {
            return JsonResult.error(QueryInspectionFilePageListByWorkOrderIdCodeEnum.WORK_ORDER_IS_NOT_EXIST.getCode(), QueryInspectionFilePageListByWorkOrderIdCodeEnum.WORK_ORDER_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success();
    }

    /**
     *  1）、设置问题类型字段
     *  2）、设置缩略图字段
     *
     * @param inspectionFileIdList
     * @param inspectionFileList
     *
     * @return
     */
    private  List<InspectionFileHandleVo> buildInspectionFileHandleVoList(String workOrderId, List<String> inspectionFileIdList, List<InspectionFile> inspectionFileList) {
        Map<String, QuestionType> questionTypeMap = this.getQuestionTypeMap();
        List<InspectionFileHandle> inspectionFileHandleList = this.getInspectionFileHandleList(inspectionFileIdList);
        Map<String, InspectionFileHandle> inspectionFileHandleMap = this.getInspectionFileHandleMap(inspectionFileHandleList);
        Map<String, User> inspectionFileHandleUserMap = this.getInspectionFileHandleUserMap(inspectionFileHandleList);

        List<InspectionFileHandleVo> inspectionFileHandleVoList = new ArrayList<>();
        InspectionFileHandleVo inspectionFileHandleVo;
        User user;
        QuestionType questionType;
        InspectionFileHandle inspectionFileHandle;
        for (InspectionFile inspectionFile : inspectionFileList) {
            inspectionFileHandleVo = new InspectionFileHandleVo();
            inspectionFileHandleVo.setWorkOrderId(workOrderId);
            inspectionFileHandleVo.setInspectionFileId(inspectionFile.getId());
            inspectionFileHandleVo.setStatus(inspectionFile.getStatus());
            inspectionFileHandleVo.setLatitude(inspectionFile.getLatitude());
            inspectionFileHandleVo.setLongitude(inspectionFile.getLongitude());
            inspectionFileHandleVo.setLocation(inspectionFile.getLocation());
            inspectionFileHandleVo.setFileImage(CommonConfig.imageURL + inspectionFile.getFileImage());
            inspectionFileHandleVo.setFileThumbnail(CommonConfig.imageURL + inspectionFile.getFileThumbnail());
            inspectionFileHandleVo.setFileOriginal(CommonConfig.imageURL + inspectionFile.getFileOriginal());
            questionType = questionTypeMap.get(inspectionFile.getQuestionCode());
            if (null != questionType) {
                inspectionFileHandleVo.setQuestionCode(questionType.getCode());
                inspectionFileHandleVo.setQuestionName(questionType.getContent());
            }
            if (ObjectUtil.isNotNull(inspectionFileHandleMap)) {
                inspectionFileHandle = inspectionFileHandleMap.get(inspectionFile.getId());
                if (null != inspectionFileHandle) {
                    String handlerImages = "";
                    if (ObjectUtil.isNotNull(inspectionFileHandleUserMap)) {
                        user = inspectionFileHandleUserMap.get(inspectionFileHandle.getHandlerUser());
                        if (null != user) {
                            inspectionFileHandleVo.setHandlerUsername(user.getRealname());
                        }
                    }
                    if (StringUtils.isNotEmpty(inspectionFileHandle.getHandlerImage())) {
                        String[] arr = inspectionFileHandle.getHandlerImage().split(",");
                        List<String> list = Arrays.stream(arr).map(String::toString).collect(Collectors.toList());
                        for (String str : list) {
                            handlerImages += CommonConfig.imageURL + str + ",";
                        }
                    }
                    if (StringUtils.isNotEmpty(handlerImages)) {
                        handlerImages = handlerImages.substring(0, handlerImages.length() - 1);
                        inspectionFileHandleVo.setHandlerImages(handlerImages);
                    }
                    inspectionFileHandleVo.setHandlerUser(inspectionFileHandle.getHandlerUser());
                    inspectionFileHandleVo.setHandlerTime(inspectionFileHandle.getHandlerTime());
                    inspectionFileHandleVo.setHandlerResult(inspectionFileHandle.getHandlerResult());
                }
            }
            //根据问题id查询对应的任务
            String inspectionCode = this.getInspectionCodeByInspectionFile(inspectionFile);
            inspectionFileHandleVo.setInspectionCode(inspectionCode);
            inspectionFileHandleVoList.add(inspectionFileHandleVo);
        }
        return inspectionFileHandleVoList;
    }
    //获取任务相关属性
    private String getInspectionCodeByInspectionFile(InspectionFile inspectionFile) {
        if(ObjectUtil.isNull(inspectionFile)){
            throw new SecurityException("任务问题为空");
        }
        String inspectionCode = null;
        Inspection inspection = inspectionMapper.selectById(inspectionFile.getInspectionId());
        if(ObjectUtil.isNotNull(inspection)){
            if(StringUtils.isNotEmpty(inspection.getCode())){
                inspectionCode = inspection.getCode();
            }
        }
        return inspectionCode;
    }

    /**
     *
     * 获取问题类型列表，放到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::getCode, Function.identity()));
        return questionTypeMap;
    }

    /**
     *
     * 获取问题处理结果
     *
     * @param inspectionFileIdList
     * @return
     */
    private List<InspectionFileHandle> getInspectionFileHandleList(List<String> inspectionFileIdList) {
        List<InspectionFileHandle> inspectionFileHandleList = inspectionFileHandleMapper.selectList(new LambdaQueryWrapper<InspectionFileHandle>()
                .in(InspectionFileHandle::getInspectionFileId, inspectionFileIdList));

        if (CollectionUtil.isEmpty(inspectionFileHandleList)) {
            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(HashMap::new, (m, v) -> m.put(v.getInspectionFileId(), v), HashMap::putAll);
        return inspectionFileHandleMap;
    }

    private Map<String, User> getInspectionFileHandleUserMap(List<InspectionFileHandle> inspectionFileHandleList) {
        if (CollectionUtil.isEmpty(inspectionFileHandleList)) {
            return null;
        }
        List<String> userIdList = inspectionFileHandleList.stream().map(o -> o.getHandlerUser()).collect(Collectors.toList());
        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;
    }
}
