package com.tuoheng.admin.service.inspection.query;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.domain.Inspection;
import com.tuoheng.admin.entity.domain.LiveChannel;
import com.tuoheng.admin.entity.domain.Tenant;
import com.tuoheng.admin.entity.domain.User;
import com.tuoheng.admin.entity.third.Airport;
import com.tuoheng.admin.entity.vo.LiveChannelVo;
import com.tuoheng.admin.entity.vo.VideoUrlVo;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.code.AriportCodeEnum;
import com.tuoheng.admin.enums.code.inspection.QueryVideoServiceEnum;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.mapper.LiveChannelMapper;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.utils.HttpUtils;
import com.tuoheng.common.core.utils.JacksonUtil;
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;
import java.util.Objects;

/**
 * 根据任务id查询视频直播和回放
 *
 * @Author ChengWang
 * @Date 2022/11/29
 */
@Service
@Slf4j
public class QueryVideoService {

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private LiveChannelMapper liveChannelMapper;

    @Autowired
    private TenantMapper tenantMapper;


    public JsonResult getVideoById(String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonResult.error(QueryVideoServiceEnum.INSPECTION_ID_IS_NULL.getCode(), QueryVideoServiceEnum.INSPECTION_ID_IS_NULL.getMsg());
        }
        //根据id查询对应的任务
        Inspection inspection = inspectionMapper.selectById(id);
        if (ObjectUtil.isNull(inspection)) {
            return JsonResult.error(QueryVideoServiceEnum.INSPECTION_IS_NOT_EXIST.getCode(), QueryVideoServiceEnum.INSPECTION_IS_NOT_EXIST.getMsg());

        }
        LiveChannelVo liveChannelVo = new LiveChannelVo();
        if (10 == inspection.getStatus()) {
            //任务状态为任务飞行中10视频直播
            LiveChannel liveChannel = liveChannelMapper.selectOne(new LambdaQueryWrapper<LiveChannel>()
                    .eq(LiveChannel::getMark, 1)
                    .eq(LiveChannel::getInspectionId, inspection.getId())
                    .eq(LiveChannel::getStatus, 1));
            if (ObjectUtil.isNull(liveChannel)) {
                return JsonResult.error(QueryVideoServiceEnum.LIVE_CHANNEL_IS_NOT_EXIST.getCode(), QueryVideoServiceEnum.LIVE_CHANNEL_IS_NOT_EXIST.getMsg());
            }
            if (StringUtils.isEmpty(liveChannel.getAipullUrl())) {
                return JsonResult.error(QueryVideoServiceEnum.AIPULL_URL_IS_NULL.getCode(), QueryVideoServiceEnum.AIPULL_URL_IS_NULL.getMsg());
            }
            liveChannelVo.setAipullUrl(liveChannel.getAipullUrl());

        }
        if (15 == inspection.getStatus()) {
            //任务状态为任务飞行完成15视频回放
            if (StringUtils.isEmpty(inspection.getAiVideoUrl())) {
                return JsonResult.error(QueryVideoServiceEnum.AIVIDEO_URL_IS_NULL.getCode(), QueryVideoServiceEnum.AIVIDEO_URL_IS_NULL.getMsg());
            }
            liveChannelVo.setAiVideoUrl(CommonConfig.videoURL + inspection.getAiVideoUrl());
        }
        return JsonResult.success(liveChannelVo);
    }

    /**
     * 根据任务id和无人机id获取直播和机场内外部视频
     * @param inspectionId
     * @param droneId
     * @return
     */
    public JsonResult getVideoUrl(String inspectionId, Integer droneId) {
        User user = CurrentUserUtil.getUserInfo();
        String userId = user.getId();
        String tenantId = user.getTenantId();
        //校验
        JsonResult result = this.check(userId, tenantId, inspectionId, droneId);
        if (0 != result.getCode()) {
            log.info("进入获取直播和机场内外部视频接口,数据校验失败");
            return JsonResult.error(result.getCode(), result.getMsg());
        }

        VideoUrlVo vo = new VideoUrlVo();
        //根据任务id获取aipullUrl
        Inspection inspection = inspectionMapper.selectById(inspectionId);
        if (ObjectUtil.isNull(inspection)) {
            return JsonResult.error(QueryVideoServiceEnum.INSPECTION_IS_NOT_EXIST.getCode(), QueryVideoServiceEnum.INSPECTION_IS_NOT_EXIST.getMsg());
        }
        LiveChannel liveChannel = liveChannelMapper.selectOne(new LambdaQueryWrapper<LiveChannel>()
                .eq(LiveChannel::getMark, MarkEnum.VALID.getCode())
                .eq(LiveChannel::getInspectionId, inspection.getId())
                .eq(LiveChannel::getStatus, 1));
        if (ObjectUtil.isNotNull(liveChannel)) {
            if (StringUtils.isNotEmpty(liveChannel.getAipullUrl())) {
                vo.setAipullUrl(liveChannel.getAipullUrl());
            }
        }
        //获取机场内外部视频
        Tenant tenant = tenantMapper.selectById(tenantId);
        if (ObjectUtil.isNull(tenant)) {
            return JsonResult.error(AriportCodeEnum.GET_NO_TENANT.getCode(), AriportCodeEnum.GET_NO_TENANT.getMsg());
        }
        String url = CommonConfig.airportURL + SystemConstant.API_AIRPORT_LIST;
        String tempParam = "&tenantCode=" + tenant.getCode() + "&droneId=" + droneId;
        String param = "page=1&limit=100" + tempParam;
        String airPortStr = HttpUtils.sendGet(url, param);
        if (StringUtils.isEmpty(airPortStr)) {
            log.info("根据无人机id获取机场内外视频地址数据，返回为空:airPortStr={}", airPortStr);
            throw new SecurityException("调用机场平台获取数据为空");
        }
        //String---->JsonResult
        JsonResult jsonResult = JacksonUtil.json2pojo(airPortStr, JsonResult.class);
        JSONObject dataObject = (JSONObject) JSONObject.toJSON(jsonResult.getData());
        //url

        if (Objects.nonNull(dataObject)) {
            log.info("获取的数据,dataObject={}", dataObject.toJSONString());
            String records = dataObject.get("records").toString();
            List<Airport> airportList = JSONObject.parseArray(records, Airport.class);
            log.info("获取records中的数据为：airportList={}", airportList);
            if(CollectionUtil.isNotEmpty(airportList) || airportList.size() != 0){
                Airport airport = airportList.get(0);
                if(ObjectUtil.isNotNull(airport)){
                    vo.setInternalMonitorUrl(airport.getInternalMonitorUrl());
                    vo.setExternalMonitorUrl(airport.getExternalMonitorUrl());
                    vo.setFlvExternalMonitorUrl(airport.getFlvExternalMonitorUrl());
                }
            }
        }

            return JsonResult.success(vo);
        }


    private JsonResult check(String userId, String tenantId, String inspectionId, Integer droneId) {
        if(StringUtils.isEmpty(inspectionId)){
            return JsonResult.error(QueryVideoServiceEnum.INSPECTION_ID_IS_NULL.getCode(),QueryVideoServiceEnum.INSPECTION_ID_IS_NULL.getMsg());
        }
        if(null == droneId){
            return JsonResult.error(QueryVideoServiceEnum.DRONE_ID_IS_NULL.getCode(),QueryVideoServiceEnum.DRONE_ID_IS_NULL.getMsg());
        }
        return JsonResult.success();
    }
}
