package com.tuoheng.admin.service.airportline.add;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.domain.AirportLine;
import com.tuoheng.admin.entity.domain.Tenant;
import com.tuoheng.admin.entity.domain.User;
import com.tuoheng.admin.entity.dto.AirportRouteDto;
import com.tuoheng.admin.entity.request.inspection.AirportLineRequest;
import com.tuoheng.admin.enums.AirportLineEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.AirportLineMapper;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.admin.utils.AliyunOSSUtil;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.Now;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * 保存航线
 * @Author ChengWang
 * @Date 2023/5/19
 */
@Slf4j
@Service
public class AddAirportLineService {

    @Autowired
    private AirportLineMapper airportLineMapper;

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Autowired
    private TenantMapper tenantMapper;



    public JsonResult add(AirportLineRequest request) {
        log.info("进入添加航线接口");
        User user = CurrentUserUtil.getUserInfo();
        String tenantId = user.getTenantId();
        //获取租户code
        Tenant tenant = tenantMapper.selectById(tenantId);
        if(ObjectUtil.isNull(tenant)){
            return JsonResult.error(AirportLineEnum.TENANT_IS_NOT_EXIST.getCode(),AirportLineEnum.TENANT_IS_NOT_EXIST.getMsg());
        }
        if(StringUtils.isEmpty(tenant.getCode())){
            return JsonResult.error(AirportLineEnum.TENANT_CODE_IS_NULL.getCode(),AirportLineEnum.TENANT_CODE_IS_NULL.getMsg());
        }
        //校验参数值
        JsonResult jsonResult = this.check(user.getId(),tenantId,request);
        if(jsonResult.getCode() != 0){
            log.info("添加航线数据校验失败：{}",jsonResult.getMsg());
            return jsonResult;
        }
        String ossUrl = this.createPointLineForOss(request.getAirportRouteDtoList());
        String airportLineName = request.getAirportLineName();
        Integer airportId = request.getAirportId();
        //回调机场平台接口 生成航线id
        String url = CommonConfig.airportURL + SystemConstant.API_AIRPORT_DRONE_LINE;
        log.info("进入调用机场平台,自建航线接口:url={}",url);
        JSONObject requestData = new JSONObject();
        requestData.put("airportId",airportId);
        //业务系统标识为airmonitor
        requestData.put("code",SystemConstant.PLATFORM_CODE);
        requestData.put("tenantCode",tenant.getCode());
        requestData.put("wayUrl",ossUrl);
        requestData.put("wayName",airportLineName);
        log.info("进入调用机场平台,自建航线参数值:requestData={}",requestData);
        String airportDroneLine = HttpUtils.doSend(url,requestData,null,"POST");
        log.info("调用机场平台自建航线返参：airportDroneLine={}",airportDroneLine);
        if(StringUtils.isEmpty(airportDroneLine)){
            throw new ServiceException("机场接口返回数据为空,创建航线失败");
        }
        JsonResult result = JacksonUtil.json2pojo(airportDroneLine,JsonResult.class);
        if(0 != result.getCode()){
            log.info("调用机场平台,创建航线失败：result={}",result);
            return JsonResult.error(-1,"机场平台返回失败");
        }
        log.info("机场平台创建航线成功");
        //获取航线id
        //Map<String,Object> data = (Map<String, Object>) result.getData();
        //Integer lineId = (Integer) data.get("id");
        JSONObject dataObject = (JSONObject) JSONObject.toJSON(result.getData());
        Integer lineId = null;
        if(Objects.nonNull(dataObject)){
            lineId = dataObject.getInteger("id");
            log.info("航线id为：lineId={}",lineId);
        }

        //属性赋值
        AirportLine airportLine = new AirportLine();
        airportLine.setTenantId(tenantId);
        airportLine.setInspectionLineId(lineId);
        airportLine.setAirportLineName(airportLineName);
        airportLine.setCreateTime(DateUtils.now());
        airportLine.setCreateUser(user.getId());
        String inspectionRegionJsonString = JSON.toJSONString(request.getInspectionRegionDtoList());
        airportLine.setAccidentRegion(inspectionRegionJsonString);
        String airportRouteJsonString = JSON.toJSONString(request.getAirportRouteDtoList());
        airportLine.setCoordinates(airportRouteJsonString);
        airportLine.setOssUrl(ossUrl);
        airportLine.setMark(MarkEnum.VALID.getCode());
        //生成航线
        int count = airportLineMapper.insert(airportLine);
        if(count <= 0){
           return JsonResult.error("创建航线失败");
        }

        return JsonResult.success(airportLine);
    }

    private JsonResult check(String id, String tenantId, AirportLineRequest request) {
        if(StringUtils.isEmpty(tenantId)){
            return JsonResult.error(AirportLineEnum.TENANT_ID_IS_NULL.getCode(),AirportLineEnum.TENANT_ID_IS_NULL.getMsg());
        }
        //航线名称
        if(StringUtils.isEmpty(request.getAirportLineName())){
            return JsonResult.error(AirportLineEnum.AIRPORT_LINE_NAME_IS_NULL.getCode(),AirportLineEnum.AIRPORT_LINE_NAME_IS_NULL.getMsg());
        }
        if(null == request.getAirportId()){
            return JsonResult.error(AirportLineEnum.AIRPORT_ID_IS_NULL.getCode(),AirportLineEnum.AIRPORT_ID_IS_NULL.getMsg());
        }
        //区域
        if(CollectionUtils.isEmpty(request.getInspectionRegionDtoList()) || request.getInspectionRegionDtoList().size() == 0 ){
            return JsonResult.error(AirportLineEnum.REGION_LIST_IS_NULL.getCode(),AirportLineEnum.REGION_LIST_IS_NULL.getMsg());
        }
        //航线
        if(CollectionUtils.isEmpty(request.getAirportRouteDtoList()) || request.getAirportRouteDtoList().size() == 0){
            return JsonResult.error(AirportLineEnum.AIRPORT_ROUTE_LIST_IS_NULL.getCode(),AirportLineEnum.AIRPORT_ROUTE_LIST_IS_NULL.getMsg());
        }
        return JsonResult.success();
    }


    /**
     * 生成指点航线
     *
     * @param airportRouteList
     * @return
     */
    public String createPointLineForOss(List<AirportRouteDto> airportRouteList) {
        String fileUrl = "";
        try {
            String s = "QGC WPL 110\n";
            String tmp = "\t0.00000000\t0.00000000\t0.00000000\t0.00000000\t";
            String tmp16 = "\t0\t3\t16" + tmp;
            String tmp22 = "\t0\t3\t22" + tmp;
            String tmp20 = "\t0\t3\t20" + tmp;
            String end = ".000000\t1\n";
            AirportRouteDto airportRoute;
            for (int i = 1; i <= airportRouteList.size(); i++) {
                airportRoute = airportRouteList.get(i - 1);
                if (1 == i) {
                    s += i + tmp22;
                } else if (airportRouteList.size() == i) {
                    s += i + tmp20;
                } else {
                    s += i + tmp16;
                }
                s += airportRoute.getLat() + "\t" + airportRoute.getLng() + "\t" + airportRoute.getAltitude() + end;
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            out.write(s.getBytes());
            // 将outputstream转成inputstream
            ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
            String filename = UUID.randomUUID().toString() + ".waypoints";
            aliyunOSSUtil.uploadFile2OSS(in, filename);
            fileUrl = aliyunOSSUtil.getFileUrl(filename);
            out.close();
            in.close();
        } catch (Exception e) {
            log.error("创建航线，上传oss失败", e);
            throw new ServiceException("创建航线，上传oss失败");
        }
        return fileUrl;
    }

}
