package com.tuoheng.admin.service.third.airport;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.config.SystemConstant;
import com.tuoheng.admin.entity.domain.Tenant;
import com.tuoheng.admin.entity.request.airport.DroneControlRequest;
import com.tuoheng.admin.entity.request.airport.PointFlightRequest;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.common.exception.ServiceException;
import com.tuoheng.common.utils.HttpUtils;
import com.tuoheng.common.utils.JsonResult;
import com.tuoheng.common.utils.StringUtils;
import com.tuoheng.system.entity.User;
import com.tuoheng.system.utils.ShiroUtils;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DroneControlService {

    @Autowired
    private TenantMapper tenantMapper;

    public JsonResult execute(DroneControlRequest request) {
        log.info("进入调用机场平台，操作无人机");

        this.check(request);

        // 读取不同租户的机场平台url
        User user = ShiroUtils.getUserInfo();
        Integer tenantId = user.getTenantId();

        Tenant tenant = this.getTenant(tenantId);

        String url = tenant.getAirportUrl() + SystemConstant.API_AIRPORT_POINT_FLIGH;
        JSONObject jsonObject = new JSONObject().parseObject(request.getValue());

        log.info("调用机场平台，操作无人机: url:{}", url);
        log.info("调用机场平台，操作无人机: jsonObject:{}", jsonObject);

        String airPortStr = HttpUtils.doSend(url, jsonObject, null, "POST");
        if (StringUtils.isEmpty(airPortStr)) {
            log.info("执行定点飞行：机场接口返回数据为空，飞行失败，jsonObject：{}", jsonObject);
            return JsonResult.error(-1, "机场接口返回数据为空");
        }

        log.info("调用机场平台方法: 操作无人机结束");
        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param request
     * @return
     */
    private void check(DroneControlRequest request) {
        if (StringUtils.isEmpty(request.getValue())) {
            throw new ServiceException("操作无人机，传参空");
        }
    }

    /**
     * 获取租户
     *
     * @param tenantId
     * @return
     */
    private Tenant getTenant(Integer tenantId) {
        Tenant tenant = tenantMapper.selectById(tenantId);
        if (ObjectUtil.isEmpty(tenant)) {
            log.info("调用机场平台，操作无人机: 租户不存在");
            throw new ServiceException("租户不存在");
        }

        if (StringUtils.isEmpty(tenant.getAirportUrl())) {
            log.info("调用机场平台，操作无人机: 机场平台URL为空");
            throw new ServiceException("机场平台URL为空");
        }
        return tenant;
    }


}