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

import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.mapper.InspectionMapper;
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 org.springframework.web.util.UriComponentsBuilder;

@Slf4j
@Service
public class StopRecordService {

    @Autowired
    private InspectionMapper inspectionMapper;

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

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

    public JsonResult stopRecord(String msgId) {
        String url = UriComponentsBuilder.fromHttpUrl(dspDomainUrl + SystemConstant.DSP_STOP_RECORD).toUriString();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("requestId", msgId);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(jsonObject, headers);

        log.info("调用dsp平台，停止录制接口，url:{}", url);
        log.info("调用dsp平台，停止录制接口，jsonObject:{}", jsonObject);

        ResponseEntity<JsonResult> response = null;
        try {
            response = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, JsonResult.class);
        } catch (Exception e) {
            log.info("调用dsp平台，停止录制接口异常, e:{}", e);
//            throw new ServiceException("调用dsp平台，停止录制接口异常");
        }
        if (response == null || !response.hasBody()) {
            log.error("调用dsp平台，停止录制接口返回为空!");
//            throw new ServiceException("调用dsp平台，停止录制接口返回为空");
        }
        JsonResult jsonResult = response.getBody();
        if (0 != jsonResult.getCode()) {
            log.info("调用dsp平台，停止录制接口返回失败，jsonResult：{}", jsonResult);
//            throw new ServiceException("调用dsp平台，停止录制接口返回失败");
        }
        return jsonResult;
    }

}
