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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.FileTypeEnum;
import com.tuoheng.admin.enums.InspectionFileStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.SourceEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.request.inspectionfile.AddInspectionFileRequest;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.utils.GaodeUtil;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JacksonUtil;
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;

/**
 * DSP回调 服务实现类
 *
 * @author wanjing
 * @since 2023-12-02
 */
@Slf4j
@Service
public class AddInspectionFileService {

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private FlightDataMapper flightDataMapper;

    @Autowired
    private QuestionTypeMapper questionTypeMapper;

    /**
     * 保存DSP回调数据
     *
     * @param request 回调请求体
     * @return
     */
    public JsonResult add(AddInspectionFileRequest request) {
        log.info("添加问题数据, request：{}", JacksonUtil.obj2StringPretty(request));
        User user = CurrentUserUtil.getUserInfo();

        // 查询任务
        Inspection inspection = inspectionMapper.selectOne(new LambdaQueryWrapper<Inspection>()
                .eq(Inspection::getId, request.getInspectionId()));
        if (ObjectUtil.isNull(inspection)) {
            log.info("任务不存在");
            throw new ServiceException(0, "任务不存在");
        }

        InspectionFile inspectionFile = new InspectionFile();
        //问题编号
        inspectionFile.setQuestionCode(request.getQuestionCode());
        QuestionType questionTypeData = null;
        if (StringUtils.isNotEmpty(request.getQuestionCode())) {
            questionTypeData = questionTypeMapper.selectOne(Wrappers.<QuestionType>lambdaQuery()
                    .eq(QuestionType::getCode, request.getQuestionCode())
                    .eq(QuestionType::getMark, MarkEnum.VALID.getCode()));
            if (ObjectUtil.isNotEmpty(questionTypeData)) {
                inspectionFile.setQuestionId(questionTypeData.getId());
                inspectionFile.setQuestionName(questionTypeData.getContent());
            } else {
                log.error("该问题类型在业务平台不存在，code={}", request.getQuestionCode());
            }
        }
        inspectionFile.setTenantId(user.getTenantId());
        inspectionFile.setInspectionId(request.getInspectionId());
        // 文件类型
        inspectionFile.setFileType(FileTypeEnum.IMAGE.getCode());
        // 文件编码
        inspectionFile.setFileCode(request.getFileCode());
        // 文件名称
        inspectionFile.setFileName(request.getFileName());
        //图片大小，单位MB，保留两位小数，目前没有获取图片大小的字段
        inspectionFile.setFileSize(0.00);
        inspectionFile.setStatus(InspectionFileStatusEnum.WAIT_CONFIRMED.getCode());
        inspectionFile.setMark(1);
        // 原始图片
        String fileOriginalUrl = request.getFileOriginalUrl();
        if (StringUtils.isNotEmpty(fileOriginalUrl) && fileOriginalUrl.contains(CommonConfig.imageURL)) {
            fileOriginalUrl = fileOriginalUrl.replaceAll(CommonConfig.imageURL, "");
        }
        inspectionFile.setFileOriginal(fileOriginalUrl);
        // 标记图片
        String fileMarkerUrl = request.getFileMarkerUrl();
        if (StringUtils.isNotEmpty(fileMarkerUrl) && fileMarkerUrl.contains(CommonConfig.imageURL)) {
            fileMarkerUrl = fileMarkerUrl.replaceAll(CommonConfig.imageURL, "");
        }
        inspectionFile.setFileImage(fileMarkerUrl);

        // 问题图片来源
        inspectionFile.setSource(SourceEnum.AI.getCode());
        inspectionFile.setCreateUser(user.getId()); // 设置默认用户
        inspectionFile.setCreateTime(DateUtils.now());
        //拉取最新一条经纬度信息
        FlightData flightData = flightDataMapper.selectOne(Wrappers.<FlightData>lambdaQuery()
                .eq(FlightData::getInspectionId, request.getInspectionId())
                .orderByDesc(FlightData::getCreateTime)
                .last("limit 1"));
        if (ObjectUtil.isNotNull(flightData)) {
            inspectionFile.setLatitude(flightData.getLat());
            inspectionFile.setLongitude(flightData.getLng());
            inspectionFile.setGaodeLatitude(flightData.getLat());
            inspectionFile.setGaodeLongitude(flightData.getLng());
        }
        String gaodeAddress_live = GaodeUtil.getGaodeAddress(flightData.getLng(), flightData.getLat());
        if (ObjectUtil.isNotNull(gaodeAddress_live)) {
            inspectionFile.setLocation(gaodeAddress_live);
            inspectionFile.setGaodeAddress(gaodeAddress_live);
        }
        List<InspectionFile> inspectionFileList = new ArrayList<>();
        inspectionFileList.add(inspectionFile);
        inspectionFileMapper.addBatch(inspectionFileList);

        return JsonResult.success();
    }

}
