package com.tuoheng.miniprogram.service.impl;


import com.aliyun.oss.ClientException;
import com.aliyun.tea.TeaModel;
import com.aliyun.vod20170321.Client;
import com.aliyun.vod20170321.models.GetPlayInfoRequest;
import com.aliyun.vod20170321.models.GetPlayInfoResponse;
import com.aliyun.vod20170321.models.ListLiveRecordVideoRequest;
import com.aliyun.vod20170321.models.ListLiveRecordVideoResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.JacksonUtil;
import com.tuoheng.common.core.utils.StringUtils;
import com.tuoheng.miniprogram.config.AliyuncsVodConfig;
import com.tuoheng.miniprogram.enums.AliyunVodUploadStatusEnum;
import com.tuoheng.miniprogram.service.IAliyuncsVodService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Author: 吴彬
 * @CreateTime: 2022-08-31  08:35
 * @Description: 阿里云点播服务 实现类
 * @Version: 1.0
 */
@Slf4j
@Service
public class AliyuncsVodServiceImpl implements IAliyuncsVodService {

    @Autowired
    @Qualifier("vodClient")
    private Client vodClient;

    //填入AccessKey信息
    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        String regionId = "cn-shanghai";  // 点播服务接入地域
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }


    @Override
    public CreateUploadVideoResponse     createUploadVideo(String title, String fileName) throws ClientException {
        CreateUploadVideoResponse response = new CreateUploadVideoResponse();
        try {
            DefaultAcsClient client = initVodClient(AliyuncsVodConfig.accessKeyId, AliyuncsVodConfig.accessKeySecret);

            CreateUploadVideoRequest request = new CreateUploadVideoRequest();
            request.setTitle(title);
            request.setFileName(fileName);
            response = client.getAcsResponse(request);

            log.info("VideoId = " + response.getVideoId());
            log.info("UploadAddress = " + response.getUploadAddress());
            log.info("UploadAuth = " + response.getUploadAuth());
            log.info("RequestId = " + response.getRequestId());
        } catch (Exception e) {
            log.error("ErrorMessage = " + e.getLocalizedMessage());
        }
        return response;
    }

    @Override
    public RefreshUploadVideoResponse refreshUploadVideo(String videoId) {
        RefreshUploadVideoResponse response = new RefreshUploadVideoResponse();
        try {
            DefaultAcsClient client = initVodClient(AliyuncsVodConfig.accessKeyId, AliyuncsVodConfig.accessKeySecret);

            RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
            //音频或视频ID
            request.setVideoId(videoId);
            response = client.getAcsResponse(request);

            log.info("VideoId = " + response.getVideoId());
            log.info("UploadAddress = " + response.getUploadAddress());
            log.info("UploadAuth = " + response.getUploadAuth());
            log.info("RequestId = " + response.getRequestId());

        } catch (Exception e) {
            log.error("ErrorMessage = " + e.getLocalizedMessage());
        }
        return response;

    }

    @Override
    public String getVodVideoId(String appName, String domainName, String streamName) {
        try {
            ListLiveRecordVideoRequest listLiveRecordVideoRequest = new ListLiveRecordVideoRequest();
            listLiveRecordVideoRequest.setAppName(appName);
            listLiveRecordVideoRequest.setDomainName(domainName);
            listLiveRecordVideoRequest.setStreamName(streamName);
            listLiveRecordVideoRequest.setPageNo(1);
            listLiveRecordVideoRequest.setPageSize(1);
            ListLiveRecordVideoResponse resp = vodClient.listLiveRecordVideo(listLiveRecordVideoRequest);
            String vodVideoId = (String)((Map)((Map)((List)((Map) ((Map) TeaModel.buildMap(resp).get("body")).get("LiveRecordVideoList"))
                    .get("LiveRecordVideo")).get(0)).get("Video")).get("VideoId");
            return vodVideoId;
        } catch (Exception e){
            log.error("获取vod视频videoId失败", e);
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "获取vod视频videoId失败!");
        }
    }

    @Override
    public String getVodVideoUrl(String vodVideoId) {
        if(StringUtils.isEmpty(vodVideoId)){
            log.error("vodVideoId is null, vodVideoId:{}", vodVideoId);
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "vodVideoId is null!");
        }
        GetPlayInfoRequest getPlayInfoRequest = new GetPlayInfoRequest();
        getPlayInfoRequest.setVideoId(vodVideoId);
        long startTime = System.currentTimeMillis();
        while(true){
            try {
                Thread.sleep(5000);
                long currentTime = System.currentTimeMillis();
                if(currentTime - startTime > 5*60*1000){
                    log.error("根据videoId获取视频地址超时!");
                    throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "根据videoId获取视频地址超时!");
                }
                GetPlayInfoResponse response = vodClient.getPlayInfo(getPlayInfoRequest);
                log.info("GetPlayInfoResponse: {}", JacksonUtil.obj2StringPretty(response));
                return response.getBody().getPlayInfoList().getPlayInfo().get(0).getPlayURL();
            } catch (Exception e){
                if(e.getMessage().contains(AliyunVodUploadStatusEnum.UPLOADFAIL.getName())
                        || e.getMessage().contains(AliyunVodUploadStatusEnum.TRANSCODEFAIL.getName())
                        || e.getMessage().contains(AliyunVodUploadStatusEnum.BLOCKED.getName())
                        || e.getMessage().contains(AliyunVodUploadStatusEnum.PRODUCEFAIL.getName())){
                    log.error("根据videoId获取视频地址失败!", e);
                    throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "根据videoId获取视频地址失败!");
                }
                log.error("", e);
            }
        }
    }
}
