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

import cn.hutool.core.util.ObjectUtil;
import com.tuoheng.admin.entity.domain.FlightData;
import com.tuoheng.admin.entity.domain.Inspection;
import com.tuoheng.admin.mapper.FlightDataMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.entity.request.inspection.InspectionRequest;
import com.tuoheng.common.core.common.OperationEnum;
import com.tuoheng.common.core.enums.ServiceExceptionEnum;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author ChengWang
 * @Date 2022/12/13
 */
@Service
@Slf4j
public class QueryFlightDataTrackService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private FlightDataMapper flightDataMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    public JsonResult track(InspectionRequest inspectionRequest) {
        Inspection inspection = inspectionMapper.selectById(inspectionRequest.getRequestId());
        if (ObjectUtil.isEmpty(inspection)) {
            throw new ServiceException(ServiceExceptionEnum.TASK_DOES_NOT_EXIST);
        }
        FlightData flightData = new FlightData();
        BeanUtils.copyProperties(inspectionRequest, flightData);
        flightData.setTenantId(inspection.getTenantId());
        flightData.setInspectionId(inspection.getId());
        flightData.setAltitude(null);
        //机场传过来的高度是相对高度
        flightData.setUltrasonic(inspectionRequest.getAltitude());

        //将最新一条数据放入缓存，并设置过期时间
        redisUtils.set(String.valueOf(inspection.getId()), flightData, 10);
        flightDataMapper.insert(flightData);
        return JsonResult.success(OperationEnum.OPERATION_SUCCESS.getMessage());
    }
}
