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

import cn.hutool.core.util.ObjectUtil;
import com.tuoheng.admin.entity.FlightData;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.mapper.FlightDataMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.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);
        }
        log.info("正在巡检的任务,inspection={}",inspection);

        FlightData flightData = new FlightData();
        BeanUtils.copyProperties(inspectionRequest, flightData);
        flightData.setTenantId(inspection.getTenantId());
        flightData.setInspectionId(inspection.getId());
        flightData.setAltitude(null);
        //机场传过来的高度是相对高度
        flightData.setUltrasonic(inspectionRequest.getAltitude());
        flightData.setSpeed(inspectionRequest.getHspeed());
        flightData.setYsingal(inspectionRequest.getYsingal());
        flightData.setDistHome(inspectionRequest.getDistHome());

        log.info("云盒遥测数据,flightData={}",flightData);

        //将最新一条数据放入缓存，并设置过期时间
        redisUtils.set(String.valueOf(inspection.getId()), flightData, 10);
        int result = flightDataMapper.insert(flightData);
        if(result<=0){
            return JsonResult.error("遥测数据保存失败");
        }

        return JsonResult.success(OperationEnum.OPERATION_SUCCESS.getMessage());
    }
}
