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

import com.alibaba.fastjson.JSONObject;
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 DspServiceImpl implements IDspService {

    @Autowired
    private StartAIService startAIService;

    @Autowired
    private StopAIService stopAIService;

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

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

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

    @Override
    public 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));
    }

    @Override
    public JSONObject serviceStopApplication(JSONObject jsonObject) {
        String url = dspDomainUrl + "/api/web/serviceInst/" + jsonObject.getString("requestId") + "/stop";
        ResponseEntity<JsonResult> response;
        try {
            response = restTemplate.exchange(url, HttpMethod.PUT, null, JsonResult.class);
        } catch (Exception e) {
            log.error("硬件停止后，停止AI分析异常！{}", e);
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "硬件停止后，停止AI分析异常！");
        }
        return JSONObject.parseObject(response.getBody().toString());
    }

    @Override
    public JsonResult startAI(MissionStatusRequest missionStatusRequest) {
        return startAIService.startAI(missionStatusRequest);
    }

    @Override
    public JsonResult stopAI(String msgId, String inspectionId) {
        return stopAIService.stopAI(msgId, inspectionId);
    }
}
