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.FlightDataHl;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.FlightDataHlMapper;
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 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);
        log.info("获取飞行数据, dataJson:{}", dataJson);

        List<TZHLAirportFlightDataResponse> flightDataHlList = JSON.parseArray(dataJson, TZHLAirportFlightDataResponse.class);

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

    /**
     * 飞行数据入库
     *
     * @param inspection
     * @param flightDataHlList
     * @return
     */
    private void addFlightDataHl(Inspection inspection, List<TZHLAirportFlightDataResponse> flightDataHlList) {
        log.info("开始飞行数据保存入库");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (CollectionUtil.isNotEmpty(flightDataHlList) && flightDataHlList.size() != 0) {
            List<FlightDataHl> flightDataHls = new ArrayList<>(flightDataHlList.size());
            for (TZHLAirportFlightDataResponse responseData : flightDataHlList) {
                FlightDataHl flightDataHl = new FlightDataHl();
                BeanUtils.copyProperties(responseData, flightDataHl);
                flightDataHl.setTenantId(inspection.getTenantId());
                flightDataHl.setInspectionId(inspection.getId());
                try {
                    flightDataHl.setCreateTime(sdf.parse(responseData.getCreateTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                flightDataHl.setCreateUser(inspection.getCreateUser());

                flightDataHls.add(flightDataHl);
                log.info("结束飞行数据保存入库， flightDataHls：{}", flightDataHls);

            }
            CommonUtils.batchOperate((x) -> flightDataHlMapper.addBatch(x),flightDataHls,1000);

            //将最新的一条数据存入缓存，并设置过期时间
            log.info("开始存入最新一条数据于缓存中");
            if (CollectionUtil.isNotEmpty(flightDataHls) && flightDataHls.size() > 0) {
                flightDataHls = flightDataHls.stream().sorted(Comparator.comparing(FlightDataHl::getCreateTime).reversed()).collect(Collectors.toList());
                //倒序排列的第一个最新数据保存到缓存
                redisUtils.set(inspection.getId(), flightDataHls.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<FlightDataHl> flightDataHl = flightDataHlMapper.selectList(new LambdaQueryWrapper<FlightDataHl>()
                .eq(FlightDataHl::getMark, MarkEnum.VALID.getCode())
                .eq(FlightDataHl::getTenantId, tenantId)
                .eq(FlightDataHl::getInspectionId, inspection.getId())
                .orderByDesc(FlightDataHl::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();
    }

}
