package com.tuoheng.admin.service.inspection.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.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.conver.InspectionConverMapper;
import com.tuoheng.admin.entity.domain.FlightData;
import com.tuoheng.admin.entity.domain.Inspection;
import com.tuoheng.admin.entity.domain.InspectionHistory;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.code.inspection.QueryInspectionDetailsByIdCodeEnum;
import com.tuoheng.admin.mapper.FlightDataMapper;
import com.tuoheng.admin.mapper.InspectionHistoryMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.entity.vo.inspection.InspectionDetailsVo;
import com.tuoheng.admin.utils.TimeUtil;
import com.tuoheng.common.core.utils.CommonNumberTypeUtils;
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.List;


/**
 * 根据Id查询巡检任务详情业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-11-25
 */
@Slf4j
@Service
public class QueryInspectionDetailsByIdService {

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionHistoryMapper inspectionHistoryMapper;

    @Autowired
    private FlightDataMapper flightDataMapper;

    public JsonResult getInspectionDetails(String id) {
        log.info("进入查询巡检任务详情业务");
        String tenantId = CurrentUserUtil.getTenantId();
        JsonResult result = this.check(tenantId, id);
        if (0 != result.getCode()) {
            log.info("进入查询巡检任务详情业务：校验失败：{}", result.getMsg());
            return result;
        }

        Inspection inspection = (Inspection) result.getData();

        InspectionDetailsVo inspectionDetailsVo = InspectionConverMapper.INSTANCE.fromInspectionToInspectionDetailsVo(inspection);

        //获取最后一次的飞行时间  获取飞行里程
        this.getFlyTimeAndMileage(inspection,inspectionDetailsVo);

        // 任务失败，查询任务失败记录
        if (InspectionStatusEnum.FLIGHT_FAILED.getCode() == inspection.getStatus()) {
            List<InspectionHistory> inspectionHistoryList = this.getInspectionHistoryList(id);
            if (CollectionUtil.isEmpty(inspectionHistoryList)) {
                log.info("该任务没有失败记录");
            } else {
                inspectionDetailsVo.setInspectionHistoryList(inspectionHistoryList);
            }
        }
        return JsonResult.success(inspectionDetailsVo);
    }

    private void getFlyTimeAndMileage(Inspection inspection, InspectionDetailsVo inspectionDetailsVo) {
        //任务判断
        if(inspectionDetailsVo.getStatus().equals(InspectionStatusEnum.FLIGHT_COMPLETED.getCode())
                || inspectionDetailsVo.getStatus().equals(InspectionStatusEnum.IN_FLIGHT.getCode())){
            List<FlightData> flightDataList = flightDataMapper.selectList(Wrappers.<FlightData>lambdaQuery()
                    .eq(FlightData::getInspectionId, inspection.getId())
                    .eq(FlightData::getMark, MarkEnum.VALID.getCode())
                    .orderByDesc(FlightData::getCreateTime));
            if(CollectionUtils.isNotEmpty(flightDataList) && flightDataList.size() > 0 ){
                FlightData temp = flightDataList.get(0);
                FlightData temp1 = flightDataList.get(flightDataList.size()-1);
                //飞行时间
                inspectionDetailsVo.setFlyTime(TimeUtil.getFormatFlyTime(temp.getFlyTime() * 1000));
                //飞行路程
               Double mileage = (Double.parseDouble(temp.getMileage()) - Double.parseDouble(temp1.getMileage()))/ 1000;
                double round = CommonNumberTypeUtils.round(mileage, 2) ;
                inspectionDetailsVo.setMileage(round + "公里");
            }
        }

    }

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

        // 判断任务是否存在
        Inspection inspection = inspectionMapper.selectOne(new LambdaQueryWrapper<Inspection>()
                .eq(Inspection::getTenantId, tenantId)
                .eq(Inspection::getId, id)
                .eq(Inspection::getMark, MarkEnum.VALID.getCode()));

        if (null == inspection) {
            return JsonResult.error(QueryInspectionDetailsByIdCodeEnum.INSPECTION_IS_NOT_EXIST.getCode(), QueryInspectionDetailsByIdCodeEnum.INSPECTION_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success(inspection);
    }

    /**
     * 检查参数
     *
     * @param id
     * @return
     */
    private List<InspectionHistory> getInspectionHistoryList(String id) {
        List<InspectionHistory> inspectionHistoryList = inspectionHistoryMapper.selectList(new LambdaQueryWrapper<InspectionHistory>()
                .eq(InspectionHistory::getInspectionId, id)
                .eq(InspectionHistory::getMark, MarkEnum.VALID.getCode()));
        return inspectionHistoryList;
    }

}
