package com.tuoheng.admin.tzhl.service.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.tzhl.constant.TZHLConstant;
import com.tuoheng.admin.tzhl.response.TZHLAirportLineResponse;
import com.tuoheng.admin.tzhl.response.TZHLShelterTaskResponse;
import com.tuoheng.admin.tzhl.service.CallTianYiPlatformService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ShelterTaskService {

    @Autowired
    @Qualifier("restTemplate")
    private RestTemplate restTemplate;

    @Autowired
    private CallTianYiPlatformService callTianYiPlatformService;

    public Long distributeTask(Inspection inspection, TZHLAirportLineResponse tzhlAirportLineResponse) {
        String apiPath = TZHLConstant.TIAN_YI_API_SHELTER_TASKS;
        JSONObject jsonObject = this.buildJSONObject(inspection, tzhlAirportLineResponse);
        String dataJson = callTianYiPlatformService.callPost(apiPath, jsonObject);
        return Long.valueOf(dataJson);
    }

    private JSONObject buildJSONObject(Inspection inspection, TZHLAirportLineResponse tzhlAirportLineResponse) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dockSn", inspection.getSn());
        jsonObject.put("taskName", inspection.getName());
        jsonObject.put("taskType", 0); // 任务类型（0：立即执行，1：定时任务，2：条件任务）
        jsonObject.put("isIntervene", 1); // 人为干预（0：false，1：true）
        jsonObject.put("outOfControlAction", 0); // 遥控器失控动作（"0":"返航","1":"悬停","2":"降落"）
        jsonObject.put("rthAltitude", 100); // 返航高度（单位：米）
        Integer flyLineVersion = tzhlAirportLineResponse.getFlyLineVersion();
        String lineCodesTmp = "";
        if (3 == flyLineVersion) {
            lineCodesTmp = "v2_";
        } else if (4 == flyLineVersion) {
            lineCodesTmp = "v3_";
        }
        List<String> lineCodes = new ArrayList<>();
        lineCodes.add(lineCodesTmp + inspection.getInspectionLine());
        jsonObject.put("lineCodes", lineCodes);
        return jsonObject;
    }

}
