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

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.entity.domain.Inspection;
import com.tuoheng.admin.enums.AiAnalyseStatusEnum;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.common.core.utils.HttpUtils;
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.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class StopAIService {

    @Autowired
    private InspectionMapper inspectionMapper;

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


    public JsonResult stopAI(String msgId, String inspectionId) {
        log.info("硬件停止后，停止AI分析");
        //任务调用完成之后，调用发送通道，请求DSP关闭请求
        //调用DSP接口
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("requestId", msgId);
        JSONObject responseJson = new JSONObject();
        Inspection inspectionUpdate = new Inspection();
        inspectionUpdate.setId(inspectionId);
        try {
            responseJson = this.serviceStopApplication(jsonObject);
            if (responseJson.getIntValue("code") == 0) {
                if (responseJson.containsKey("data") && ObjectUtil.isNotEmpty(responseJson.get("data"))) {
                    String requestId = responseJson.getJSONObject("data").getString("requestId");
                    log.info("硬件停止后，停止AI分析，dsp实时调用响应requestId：{}", requestId);
                } else {
                    log.info("硬件停止后，停止AI分析，dsp实时调用响应:{}", responseJson);
                }
                return JsonResult.success();
            } else {
                log.error("硬件停止后，停止AI分析，dsp实时调用失败：{}", responseJson);
                inspectionUpdate.setAnalyseStatus(AiAnalyseStatusEnum.FAILED.getCode());
            }
            inspectionMapper.updateById(inspectionUpdate);
        } catch (Exception e) {
            log.error("硬件停止后，停止AI分析，dsp实时调用失败：{}", responseJson);
            inspectionUpdate.setAnalyseStatus(AiAnalyseStatusEnum.FAILED.getCode());
            inspectionMapper.updateById(inspectionUpdate);
        }
        return JsonResult.success();
    }

    private JSONObject serviceStopApplication(JSONObject jsonObject) {
        String url = dspDomainUrl + "/api/web/serviceInst/" + jsonObject.getString("requestId") + "/stop";
        log.info("硬件停止后，停止AI分析，调用dsp url:{}", url);
        String result = HttpUtils.doSend(url, jsonObject, null, "PUT");
        log.info("硬件停止后，停止AI分析，调用dsp result:{}", result);
        return JSONObject.parseObject(result);
    }
}
