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

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.request.inspection.MissionStatusRequest;
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.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class StartRecordService {

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

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

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

    /**
     * 调用DSP接口
     *
     * @param request
     * @return
     */
    public JsonResult startRecord(MissionStatusRequest request) {
        String url = dspDomainUrl + SystemConstant.DSP_START_RECORD;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("requestId", request.getRequestId());
        jsonObject.put("pushUrl", "");
        jsonObject.put("pullUrl", request.getPullUrl());
        jsonObject.put("callbackUrl", dspCallbackUrl + SystemConstant.DSP_CALLBACK_RECORDING);

        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<DspCallbackRecordVo>> response;
        ParameterizedTypeReference<JsonResult<DspCallbackRecordVo>> parameterizedTypeReference =
                new ParameterizedTypeReference<>() {
                };
        try {
            response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, parameterizedTypeReference);
        } catch (Exception e) {
            log.info("调用dsp平台，开始录制接口异常，e:{}", e);
            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:{}", jsonResult);
            log.info("调用dsp平台，开始录制接口，失败", jsonResult.getMsg());
            throw new ServiceException("调用dsp平台，开始录制接口，失败");
        }
        return jsonResult;
    }

}
