package com.tuoheng.admin.service.inspection.update.flyer;

import com.tuoheng.admin.entity.dto.StreamingDto;
import com.tuoheng.admin.enums.ChannelStatusEnum;
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.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Locale;

@Slf4j
@Service
public class DeliverStreamingService {

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

    @Autowired
    private GetLiveStatusService getLiveStatusService;

    @Value("${tuoheng.live-channel-domain-url:}")
    private String channel_url;

    /**
     * 释放小程序选择的通道
     *
     * @param code 通道编码
     */
    public void deliver(String code) {
        try {
            StreamingDto streaming = getLiveStatusService.getLiveStatus(code);
            if (ChannelStatusEnum.USING.getCode() != streaming.getStatus()
                    || ChannelStatusEnum.DEACTIVATING.getCode() == streaming.getStatus()) {
                return;
            }
            String url = String.format(Locale.ENGLISH, "%s%s", channel_url, LiveChannelConstant.STREAMING_DELIVER_URL);
            StreamingDto streamingDto = new StreamingDto();
            streamingDto.setCode(code);
            HttpEntity<StreamingDto> httpEntity = new HttpEntity<>(streamingDto);
            ResponseEntity<JsonResult> response = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, JsonResult.class);
            if (response == null || !response.hasBody()) {
                log.error("释放通道失败,响应体为空!");
                throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "释放通道失败，请重试");
            }
            if (response == null || !response.hasBody() || response.getBody().getCode() != JsonResult.SUCCESS) {
                log.error("释放通道失败,响应状态码：{}", response.getBody().getCode());
                throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "释放通道失败，请重试");
            }
        } catch (Exception e) {
            log.error("释放通道失败", e);
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "释放通道失败，请重试");
        }
    }

}
