package com.tuoheng.admin.service.accident.forward;

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.constant.SystemConstant;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.AccidentStatusEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.request.accident.AccidentForwardRequest;
import com.tuoheng.admin.request.accident.AirportRoute;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service("newDroneForward")
public class NewDroneForward implements AccidentForwardService {

    @Autowired
    private AirportLineMapper airportLineMapper;

    @Autowired
    private AccidentInspectionMapper accidentInspectionMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private AccidentMapper accidentMapper;

    @Autowired
    private UpdateAccidentStatusService updateAccidentStatusService;

    @Override
    public JsonResult forward(User user, Accident accident, AccidentForwardRequest request) {
        AirportLine airportLine = airportLineMapper.selectOne(new LambdaQueryWrapper<AirportLine>()
                .eq(AirportLine::getAccidentId, accident.getId()));
        if (ObjectUtil.isNull(airportLine)) {
            log.info("该应急事故不存在航线");
            throw new ServiceException("该应急事故不存在航线");
        }

        AccidentInspection accidentInspection = accidentInspectionMapper.selectOne(new LambdaQueryWrapper<AccidentInspection>()
                .eq(AccidentInspection::getAccidentId, accident.getId()));
        if (ObjectUtil.isNull(accidentInspection)) {
            log.info("该应急事故不存在应急事故与应急任务对应记录");
            throw new ServiceException("该应急事故不存在应急事故与应急任务对应记录");
        }

        Inspection inspection = inspectionMapper.selectOne(new LambdaQueryWrapper<Inspection>()
                .eq(Inspection::getId, accidentInspection.getInspectionId()));
        if (ObjectUtil.isNull(inspection)) {
            log.info("该应急事故没有对应的应急任务, inspectionId={}", accidentInspection.getInspectionId());
            throw new ServiceException("该应急事故没有对应的应急任务");
        }
        //点击前往时更新时间
        inspection.setInspectionTime(DateUtils.now());
        inspectionMapper.updateById(inspection);
        Tenant tenant = tenantMapper.selectById(user.getTenantId());
//        if (1 == airportLine.getLineType()) {
//            // 点，直接定点飞行
//            JSONObject jsonObject = this.getJSONObjectByPoint(tenant, airportLine, inspection);
//            this.callAirport(jsonObject);
//        } else {
//            // 线，面
//            JSONObject jsonObject = this.getJSONObjectByUrl(tenant, airportLine, inspection);
//            this.callAirport(jsonObject);
//        }

        JSONObject jsonObject = this.getJSONObjectByUrl(tenant, airportLine, inspection);
        this.callAirport(jsonObject);

        // 修改应急事故状态
        updateAccidentStatusService.update(user, accident);

        return JsonResult.success();
    }

    private JSONObject getJSONObjectByPoint(Tenant tenant, AirportLine airportLine, Inspection inspection) {
        String coordinates = airportLine.getCoordinates();
        List<AirportRoute> airportRouteList = JSONArray.parseArray(coordinates, AirportRoute.class);
        AirportRoute airportRoute = airportRouteList.get(0);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("airportId", inspection.getAirportId());
        jsonObject.put("requestId", inspection.getId());
        jsonObject.put("code", SystemConstant.PLATFORM_CODE);
        jsonObject.put("tenantCode", tenant.getCode());
        jsonObject.put("alt", "100");    //高度设置为100
        jsonObject.put("lon", airportRoute.getLng());
        jsonObject.put("lat", airportRoute.getLat());
        return jsonObject;
    }

    /**
     * @param tenant
     * @param airportLine
     * @param inspection
     * @return
     */
    private JSONObject getJSONObjectByUrl(Tenant tenant, AirportLine airportLine, Inspection inspection) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("airportId", inspection.getAirportId());
        jsonObject.put("requestId", inspection.getId());
        jsonObject.put("code", SystemConstant.PLATFORM_CODE);
        jsonObject.put("tenantCode", tenant.getCode());
        jsonObject.put("wayUrl", airportLine.getOssUrl());
        return jsonObject;
    }

    /**
     * 调用机场平台
     *
     * @param jsonObject
     */
    private void callAirport(JSONObject jsonObject) {
        String url = CommonConfig.airportURL + SystemConstant.API_AIRPORT_POINT_FLIGH;

        log.info("调用机场，新无人机前往：url:{}", url);
        log.info("调用机场，新无人机前往：jsonObject:{}", jsonObject);

        String airPortStr = HttpUtils.doSend(url, jsonObject, null, "POST");
        if (StringUtils.isEmpty(airPortStr)) {
            log.info("调用机场，新无人机前往：机场接口返回数据为空，飞行失败，jsonObject：{}", jsonObject);
            throw new com.aliyun.oss.ServiceException("机场接口返回数据为空，飞行失败");
        }
        JsonResult jsonResult = JacksonUtil.json2pojo(airPortStr, JsonResult.class);
        if (0 != jsonResult.getCode()) {
            log.info("调用机场，新无人机前往：飞行失败，jsonResult：{}", jsonResult.getMsg());
            throw new com.tuoheng.common.core.exception.ServiceException("机场平台返回，飞行失败");
        }
    }

}
