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

import cn.hutool.core.util.ObjectUtil;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.vo.DspCallbackQueryVo;
import com.tuoheng.admin.entity.vo.DspCallbackRecordVo;
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.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

@Slf4j
@Service
public class QueryRecordService {

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

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

    public JsonResult queryRecord(String msgId) {
        String url = dspDomainUrl + SystemConstant.DSP_QUERY_RECORD + msgId;
        log.info("调用dsp平台，查询录屏信息接口，url:{}", url);
        ResponseEntity<JsonResult<DspCallbackQueryVo>> response;
        ParameterizedTypeReference<JsonResult<DspCallbackQueryVo>> parameterizedTypeReference =
                new ParameterizedTypeReference<>() {
                };
        try {
            response =restTemplate.exchange(url, HttpMethod.GET, null, parameterizedTypeReference);
        } catch (Exception e) {
            log.info("调用dsp平台，查询录屏信息接口异常");
            throw new ServiceException("调用dsp平台，查询录屏信息接口异常");
        }
        if (ObjectUtil.isEmpty(response)) {
            log.info("调用dsp平台，查询录屏信息返回为空");
            throw new ServiceException("调用dsp平台，查询录屏信息返回为空");
        }
        JsonResult jsonResult = response.getBody();
        if (0 != jsonResult.getCode()) {
            log.info("调用dsp平台，查询录屏信息，失败，jsonResult:{}");
            throw new ServiceException("调用dsp平台，查询录屏信息，失败");
        }
        return jsonResult;
    }
}
