package com.tuoheng.admin.tzhl.service.fly.data;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.dto.AirportDto;
import com.tuoheng.admin.entity.FlightData;
import com.tuoheng.admin.entity.FlightDataHl;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.FlightDataHlMapper;
import com.tuoheng.admin.mapper.FlightDataMapper;
import com.tuoheng.admin.tzhl.constant.TZHLConstant;
import com.tuoheng.admin.tzhl.response.TZHLAirportFlightDataResponse;
import com.tuoheng.admin.tzhl.service.CallTianYiPlatformService;
import com.tuoheng.admin.tzhl.service.airport.TZHLGetAirportListService;
import com.tuoheng.common.core.utils.CommonUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.RedisUtils;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FlyDataService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private FlightDataHlMapper flightDataHlMapper;

    @Autowired
    private FlightDataMapper flightDataMapper;

    @Autowired
    private CallTianYiPlatformService callTianYiPlatformService;

    @Autowired
    private TZHLGetAirportListService getAirportListService;

    public void getFlyData(Inspection inspection) {
        log.info("获取飞行数据操作, inspectionId:{}", inspection.getId());
        String apiPath = TZHLConstant.TIAN_YI_API_FLIGHT_DATA;
        JSONObject jsonObject = this.jsonObjectRequest(inspection);
        String dataJson = callTianYiPlatformService.callPost(apiPath, jsonObject);
        List<TZHLAirportFlightDataResponse> flightDataHlList = JSON.parseArray(dataJson, TZHLAirportFlightDataResponse.class);

        log.info("获取飞行数据, flightDataHlList size:{}", flightDataHlList.size());

        // 查询到的数据入库
        this.addFlightDataHl(inspection, flightDataHlList);
    }

    /**
     * 飞行数据入库
     *
     * @param inspection
     * @param flightDataHlList
     * @return
     */
    private void addFlightDataHl(Inspection inspection, List<TZHLAirportFlightDataResponse> flightDataHlList) {
        log.info("飞行数据保存入库, inspectionId:{}", inspection.getId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (CollectionUtil.isNotEmpty(flightDataHlList) && flightDataHlList.size() != 0) {
            List<FlightData> flightDataList = new ArrayList<>(flightDataHlList.size());
            for (TZHLAirportFlightDataResponse responseData : flightDataHlList) {
                FlightData flightData = new FlightData();
                BeanUtils.copyProperties(responseData, flightData);
                flightData.setGpssingal(responseData.getGps());
                flightData.setTenantId(inspection.getTenantId());
                flightData.setInspectionId(inspection.getId());
                flightData.setAlt(responseData.getHt());
                flightData.setTimestamp(String.valueOf(responseData.getTime()));
                try {
                    flightData.setCreateTime(sdf.parse(responseData.getCreateTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                flightData.setCreateUser(inspection.getCreateUser());

                flightDataList.add(flightData);

            }
            CommonUtils.batchOperate((x) -> flightDataMapper.addBatch(x),flightDataList,1000);

            //将最新的一条数据存入缓存，并设置过期时间
            log.info("开始存入最新一条数据于缓存中");
            if (CollectionUtil.isNotEmpty(flightDataList) && flightDataList.size() > 0) {
                flightDataList = flightDataList.stream().sorted(Comparator.comparing(FlightData::getCreateTime).reversed()).collect(Collectors.toList());

                redisUtils.set(inspection.getId(), flightDataList.get(0), 10);

            }
        }
        return;
    }

    private JSONObject jsonObjectRequest(Inspection inspection) {
        JsonResult jsonResult = this.check(inspection);
        if (jsonResult.getCode() != 0) {
            return null;
        }
        //根据任务获取对应的部门
        Long recordId = inspection.getRecordId();

        AirportDto airportDto = getAirportListService.getAirport(inspection.getAirportId());
        Long deptId = 0L;
        if (ObjectUtil.isNotEmpty(airportDto)) {
            deptId = airportDto.getDeptId();
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("recordId", recordId);
        jsonObject.put("deptId", deptId);
        //查飞行数据最新一条的生成时间
        this.getCreateTime(inspection, jsonObject);

        return jsonObject;
    }

    /**
     * 获取最新的一条数据信息
     *
     * @param inspection
     * @return
     */
    private void getCreateTime(Inspection inspection, JSONObject jsonObject) {
        String tenantId = inspection.getTenantId();

        List<FlightData> flightDataHl = flightDataMapper.selectList(new LambdaQueryWrapper<FlightData>()
                .eq(FlightData::getMark, MarkEnum.VALID.getCode())
                .eq(FlightData::getTenantId, tenantId)
                .eq(FlightData::getInspectionId, inspection.getId())
                .orderByDesc(FlightData::getCreateTime)
                .last("limit 1"));

        if (CollectionUtil.isEmpty(flightDataHl) && flightDataHl.size() == 0) {
            //查出的数据为空,直接结束返回
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (ObjectUtil.isNotNull(flightDataHl.get(0))) {
            Date createTime = flightDataHl.get(0).getCreateTime();
            String dateString = sdf.format(createTime);
            jsonObject.put("createTime", dateString);
        } else {
            return;
        }
    }

    private JsonResult check(Inspection inspection) {
        if (StringUtils.isEmpty(inspection.getDeptId())) {
            return JsonResult.error("任务部门id为空");
        }
        if (null == inspection.getRecordId()) {
            return JsonResult.error("飞行记录id为空");
        }
        return JsonResult.success();
    }

}
