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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.dto.StreamingDto;
import com.tuoheng.admin.entity.Business;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.entity.InspectionFile;
import com.tuoheng.admin.entity.LiveChannel;
import com.tuoheng.admin.enums.ChannelStatusEnum;
import com.tuoheng.admin.mapper.BusinessMapper;
import com.tuoheng.admin.mapper.InspectionFileMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.mapper.LiveChannelMapper;
import com.tuoheng.admin.request.inspection.UpdateTaskByCodeRequest;
import com.tuoheng.admin.vo.DspCallbackVo;
import com.tuoheng.common.core.common.BaseEntity;
import com.tuoheng.common.core.constant.CommonConstants;
import com.tuoheng.common.core.enums.HttpStatusEnum;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JacksonUtil;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
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.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.*;

@Slf4j
@Service
public class OnlineCompleteService {

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionFileMapper inspectionFileMapper;

    @Autowired
    private LiveChannelMapper liveChannelMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private DeliverStreamingService deliverStreamingService;

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

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

    public void handle(Inspection inspection) {
        LiveChannel channel = liveChannelMapper.selectOne(new LambdaQueryWrapper<LiveChannel>()
                .eq(LiveChannel::getInspectionId, inspection.getId())
                .eq(LiveChannel::getMark, 1));
        Optional.ofNullable(channel).orElseThrow(
                () -> new ServiceException(HttpStatus.BAD_REQUEST.value(), "获取通道信息失败！"));
        try {
            log.info("=========================发送DSP停止业务=========================");
            // 查询业务
            Business business = businessMapper.selectOne(new LambdaQueryWrapper<Business>()
                    .eq(Business::getType, 1)
                    .eq(Business::getTypeId, inspection.getId())
                    .orderByDesc(BaseEntity::getCreateTime)
                    .last("limit 1"));
            if (StringUtils.isNotNull(business)) {
                // 发送停止DSP分析服务
                log.info("调用DSP服务");
                String url = String.format("%s/api/web/serviceInst/%s/stop/", dspDomainUrl, business.getMsgId());
                ResponseEntity<JsonResult> response = restTemplate.exchange(url, HttpMethod.PUT, null, new ParameterizedTypeReference<JsonResult>() {
                });
                log.info(String.format("请求结果：%s", response.getBody()));
                if (response == null || !response.hasBody()) {
                    log.error("停止DSP分析服务失败,响应体为空!");
                    throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "停止DSP分析服务失败，请重试");
                }
                JsonResult jsonResult = response.getBody();
                log.info(String.format("结果对象转换：%s", jsonResult.getData()));
                if (jsonResult.getCode() != 0) {
                    log.error("停止DSP分析服务失败, response:{}", JacksonUtil.obj2json(jsonResult));
                    throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "停止DSP分析服务失败，请重试");
                }
            }
        } finally {
        }
    }
}
