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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.enums.code.inspection.EditInspectionStatusCodeEnum;
import com.tuoheng.admin.request.inspection.MissionStatusRequest;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Locale;

@Slf4j
@Service
public class StartAIService {

    /**
     * DSP服务API接口域名
     */
    @Value("${tuoheng.dsp-domain-url:}")
    private String dspDomainUrl;

    @Value("${tuoheng.dsp-service-inst-id:}")
    private String dspServiceInstId;

    @Value("${tuoheng.dsp-callback-url:}")
    private String dspCallbackUrl;

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

    /**
     * 调用DSP接口
     *
     * @param missionStatusRequest
     * @return
     */
    public JsonResult startAI(MissionStatusRequest missionStatusRequest) {
        log.info("进入调用DSP接口方法, missionStatusRequest={}", missionStatusRequest.getId());
        log.info("进入调用DSP接口方法, dspServiceInstId={}", dspServiceInstId);
        JSONObject request = new JSONObject();
        JSONArray configList = new JSONArray();
        JSONObject instConfigMode = new JSONObject();
        instConfigMode.put("ename", "service_mode");
        instConfigMode.put("evalue", "1");
        configList.add(instConfigMode);
        JSONObject instConfigUrl = new JSONObject();
        instConfigUrl.put("ename", "callback_url");
        instConfigUrl.put("evalue", dspCallbackUrl);
        configList.add(instConfigUrl);
        request.put("serviceInstConfigList", configList);

        JSONArray reqList = new JSONArray();

        JSONObject instReqUrlPush = new JSONObject();
        instReqUrlPush.put("ename", "push_url");
        instReqUrlPush.put("evalue", missionStatusRequest.getPushUrl());
        reqList.add(instReqUrlPush);

        JSONObject instReqUrlPull = new JSONObject();
        instReqUrlPull.put("ename", "pull_url");
        instReqUrlPull.put("evalue", missionStatusRequest.getPullUrl());
        reqList.add(instReqUrlPull);

        request.put("serviceInstReqList", reqList);
        JSONObject responseJson = this.serviceInstApplication(request);
        if (responseJson.getIntValue("code") == 0) {
            String requestId = responseJson.getJSONObject("data").getString("requestId");
            log.info("dsp实时调用响应requestId：{}", requestId);
        } else {
            log.error("dsp实时调用失败：{}", responseJson);
            return JsonResult.error(EditInspectionStatusCodeEnum.TASK_ANALYSIS_FAILED.getCode(), EditInspectionStatusCodeEnum.TASK_ANALYSIS_FAILED.getMsg());
        }
        return JsonResult.success(responseJson);
    }

    private JSONObject serviceInstApplication(JSONObject jsonObject) {
        String url = String.format(Locale.ENGLISH, "%s/api/web/serviceInst/%s/application", dspDomainUrl, dspServiceInstId);
        log.info("调用DSP服务, url:{}", url);
        log.info("调用DSP服务, jsonObject:{}", jsonObject);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(jsonObject, headers);
        ResponseEntity<JsonResult> response;
        try {
            response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, JsonResult.class);
        } catch (Exception e) {
            log.error("调用DSP服务：DSP返回异常, url:{}", url);
            log.error("调用DSP服务：DSP返回异常, httpEntity:{}", httpEntity);
            throw new ServiceException("调用DSP服务：DSP返回异常");
        }
        JsonResult jsonResult = response.getBody();
        if (0 != jsonResult.getCode()) {
            log.info("调用DSP服务：DSP返回失败，jsonResult：{}", jsonResult.getMsg());
            throw new ServiceException("调用DSP服务：DSP返回失败");
        }
        log.info("调用DSP服务, result:{}", jsonResult);
        return JSONObject.parseObject(JSONObject.toJSONString(jsonResult));
    }

}
