package com.tuoheng.admin.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.domain.ThInspection;
import com.tuoheng.admin.entity.domain.ThMission;
import com.tuoheng.admin.entity.request.InspectionRequest;
import com.tuoheng.admin.entity.request.MissionStatusRequest;
import com.tuoheng.admin.entity.request.PushAndPullURLRequest;
import com.tuoheng.admin.entity.vo.*;
import com.tuoheng.admin.enums.MarkTypeEnum;
import com.tuoheng.admin.enums.TaskStatusEnum;
import com.tuoheng.admin.enums.UpdateOrCreateEnum;
import com.tuoheng.admin.mapper.ThInspectionMapper;
import com.tuoheng.admin.mapper.ThMissionMapper;
import com.tuoheng.admin.service.IMissionService;
import com.tuoheng.admin.service.IThInspectionService;
import com.tuoheng.common.common.BaseServiceImpl;
import com.tuoheng.common.config.CommonConfig;
import com.tuoheng.common.exception.ServiceException;
import com.tuoheng.common.utils.HttpUtils;
import com.tuoheng.common.utils.JacksonUtil;
import com.tuoheng.common.utils.JsonResult;
import com.tuoheng.common.utils.RedisUtils;
import com.tuoheng.system.utils.ShiroUtils;
import groovy.util.logging.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @User qiujinyang
 * @Description
 * @Date Created by 2022/7/28 9:39
 */
@Service
@Slf4j
public class ThInspectionServiceImpl extends BaseServiceImpl<ThInspectionMapper, ThInspection> implements IThInspectionService {


    @Autowired
    private ThInspectionMapper inspectionMapper;

    @Autowired
    private ThMissionMapper missionMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private IMissionService missionService;

    @Override
    public List<InspectionVO> track(Integer id) {

        LambdaQueryWrapper<ThInspection> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ThInspection::getMissionId,id).orderByDesc(ThInspection::getCreateTime);
        //lambdaQueryWrapper.eq(ThInspection::getTenantId, ShiroUtils.getTenantId());
        List<InspectionVO> result=new ArrayList<>();
        List<ThInspection> thInspections = inspectionMapper.selectList(lambdaQueryWrapper);

        for (ThInspection thInspection : thInspections) {
            InspectionVO inspectionVO=new InspectionVO();
            BeanUtils.copyProperties(thInspection,inspectionVO);
            result.add(inspectionVO);
        }
        return result;
    }


    @Override
    public Integer track(InspectionRequest inspectionRequest) throws ServiceException {
        ThInspection inspection=new ThInspection(UpdateOrCreateEnum.CREATE.getCode());
        BeanUtils.copyProperties(inspectionRequest,inspection);
        //获取当前巡检正在执行的任务
        List<ThMission> thMissions = missionMapper.selectList(new LambdaQueryWrapper<ThMission>()
                .eq(ThMission::getInspectionLine, inspectionRequest.getInspectionId())
                .eq(ThMission::getStatus, TaskStatusEnum.FLIGHT.getCode())
                .eq(ThMission::getMark, MarkTypeEnum.VALID.getCode()).orderByAsc(ThMission::getExecutionStartTime));
        if(ObjectUtil.isEmpty(thMissions) || thMissions.size()==0){
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(),"没有正在飞行的任务！");
        }
        ThMission mission = thMissions.get(0);
        inspection.setMissionId(mission.getId());
        inspection.setTenantId(mission.getTenantId());
        inspectionMapper.insert(inspection);
        return inspection.getId();
    }

    @Override
    public List<AirPortVO>  airport() throws ServiceException {
        //这边需要配置到yml文件里面
        String url = CommonConfig.airportUrl +"/api/airportInterface/airportList";
        String param="page=1&limit=10";
        String airPortStr = HttpUtils.sendGet(url, param);
        JsonResult jsonResult = JacksonUtil.json2pojo(airPortStr, JsonResult.class);
        if(ObjectUtil.isEmpty(jsonResult) || (!ObjectUtil.isEmpty(jsonResult.getData()) &&jsonResult.getCode() != 0)) {
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "获取机场信息失败，请重试");
        }
        return JSONObject.parseArray(JSONObject.parseObject(JSONObject.toJSONString(jsonResult.getData())).get("records").toString(), AirPortVO.class);
    }

    @Override
    public List<AirLineVO> airLine(Integer droneId) throws ServiceException {

        //这边需要配置到yml文件里面
        String url = CommonConfig.airportUrl +"/api/airportInterface/taskByDroneId";
        String param="page=1&limit=100&droneId="+droneId;
        String airPortStr = HttpUtils.sendGet(url, param);
        JsonResult<AirLineVO> jsonResult = JacksonUtil.json2pojo(airPortStr, JsonResult.class);
        if(ObjectUtil.isEmpty(jsonResult) || (!ObjectUtil.isEmpty(Objects.requireNonNull(jsonResult).getData()) && jsonResult.getCode() != 0)) {
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "获取航线信息失败，请重试");
        }
        return JSONObject.parseArray(JSONObject.parseObject(JSONObject.toJSONString(jsonResult.getData())).get("records").toString(), AirLineVO.class);
    }

    @Override
    public JsonResult executeTask(String taskId,PushAndPullURLRequest pushAndPull) throws ServiceException{

        ThMission thMission = missionMapper.selectById(taskId);
        Assert.notNull(thMission,"任务不能为空！");
        taskId=thMission.getInspectionLine().toString();

        int status = (Integer)redisUtils.get("status");
        //1：开，2：关
        if(status==1) {
            //这边需要配置到yml文件里面
            String url = CommonConfig.airportUrl + "/api/airportInterface/executeTask";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("taskId", taskId);

            String airPortStr = HttpUtils.doSend(url, jsonObject, null, "POST");
            JsonResult jsonResult = JacksonUtil.json2pojo(airPortStr, JsonResult.class);
            if (ObjectUtil.isEmpty(jsonResult) || (!ObjectUtil.isEmpty(Objects.requireNonNull(jsonResult).getData()) && jsonResult.getCode() != 0)) {
                assert jsonResult != null;
                return JsonResult.error(JSONObject.parseArray(JSONObject.parseObject(JSONObject.toJSONString(jsonResult.getData())).get("data").toString(), AirExecuteTaskVO.class), "执行任务失败！");
            } else if (ObjectUtil.isEmpty(jsonResult.getData()) && jsonResult.getCode() != 0) {
                return JsonResult.error(jsonResult.getMsg());
            } else {
                ThMission thMissionUpdate=new ThMission(UpdateOrCreateEnum.UPDATE.getCode());
                thMissionUpdate.setId(thMission.getId());
                //修改执行时间为当前
                thMissionUpdate.setExecutionStartTime(new Date());
                missionMapper.updateById(thMissionUpdate);
                //返回执行结果
                return JsonResult.success(jsonResult.getMsg());
            }
        }else{
            if(ObjectUtil.isEmpty(pushAndPull)){
                //如果是空，好歹给个通道
                pushAndPull.setPullUrl("rtmp://live.play.t-aaron.com/live/THSAq_hd");
                pushAndPull.setPushUrl("rtmp://live.push.t-aaron.com/live/THSAq");
            }
            MissionStatusRequest missionStatusRequest=new MissionStatusRequest();
            missionStatusRequest.setId(thMission.getInspectionLine());
            missionStatusRequest.setPushUrl(pushAndPull.getPushUrl());
            missionStatusRequest.setPullUrl(pushAndPull.getPullUrl());
            missionStatusRequest.setStatus(2);
            //修改任务状态，任务开始飞行
            boolean b = missionService.updateStatus(missionStatusRequest);
            return JsonResult.success(thMission.getInspectionLine());
        }
    }

    @Override
    public AirWeatherVO getWeather(Integer airportId) throws ServiceException{
        //这边需要配置到yml文件里面
        String url = CommonConfig.airportUrl + "/api/airportInterface/getWeather";
        String param="airportId="+airportId;
        String weatherStr = HttpUtils.sendGet(url, param);
        JsonResult jsonResult;
        try {
            jsonResult = JacksonUtil.json2pojo(weatherStr, JsonResult.class);
            if (ObjectUtil.isEmpty(jsonResult) || Objects.requireNonNull(jsonResult).getCode() != 0) {
                throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "获取天气信息失败，请重试");
            }
            if(ObjectUtil.isEmpty(jsonResult.getData())){
                return new AirWeatherVO();
            }
            return JSONObject.parseObject(JSONObject.toJSONString(jsonResult.getData()),AirWeatherVO.class);
        }catch (Exception e){
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "获取天气信息失败，请重试");
        }
    }

    @Override
    public JsonResult lineTrack(Integer missionId) {

        ThMission thMission = missionMapper.selectById(missionId);
        Assert.notNull(thMission,"任务不能为空！");
        Integer taskId= thMission.getInspectionLine();
        //解析标准srt文件里面的坐标，调用硬件接口，返回数据
        String url = CommonConfig.airportUrl + "/api/airportInterface/getLocationById";
        String param="id="+taskId;
        String airportLine = HttpUtils.sendGet(url, param);
        JsonResult jsonResult = JacksonUtil.json2pojo(airportLine, JsonResult.class);
        if(ObjectUtil.isEmpty(jsonResult) || Objects.requireNonNull(jsonResult).getCode() != 0) {
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "获取标准航线信息失败，请重试");
        }

        JSONArray resultData = JSONArray.parseArray(JSONObject.toJSONString( jsonResult.getData()));
        for (Object o : resultData) {
            JSONObject jsonObject=(JSONObject)o;
            jsonObject.put("lng",jsonObject.getString("lon"));
            jsonObject.remove("lon");
        }
        jsonResult.setData(resultData);

        System.out.println(jsonResult.getData().toString());
        return jsonResult;
    }


}
