package com.zcloud.controller.video;

import com.aliyun.vod20170321.models.*;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.SubmitTranscodeJobsResponse;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.PageData;
import com.zcloud.service.courseware.VideoCoursewareService;
import com.zcloud.service.curriculum.CurriculumService;
import com.zcloud.service.gateway.SynchronizeInformationService;
import com.zcloud.util.Tools;
import com.zcloud.util.ali.AudioOrVideoCreateUpload;
import com.zcloud.util.ali.GetPlayInfo;
import com.zcloud.util.ali.SubmitTrans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/app/audioOrVideo")
public class AppAudioOrVideoController  extends BaseController {

	@Autowired
	private VideoCoursewareService videocoursewareService;
	@Autowired
	private CurriculumService curriculumService;
	@Autowired
	private SynchronizeInformationService synchronizeInformationService;

    /**
     * 获取音/视频上传地址和凭证
     * @param client 发送请求客户端
     * @return CreateUploadVideoResponse 获取音/视频上传地址和凭证响应数据
     * @throws Exception
     */
	@RequestMapping(value="/createUploadVideo")
	@ResponseBody
	public Object createUploadVideo() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		com.aliyun.vod20170321.Client client = AudioOrVideoCreateUpload.createClient();
		CreateUploadVideoRequest createUploadVideoRequest = new CreateUploadVideoRequest()
			.setFileName(pd.getString("FileName"))
			.setTitle(pd.getString("Title"));
		// 复制代码运行请自行打印 API 的返回值
		CreateUploadVideoResponse  resp=  client.createUploadVideo(createUploadVideoRequest);
		PageData data = new PageData();
		data.put("requestId", resp.body.requestId);
		data.put("uploadAddress", resp.body.uploadAddress);
		data.put("uploadAuth",  resp.body.uploadAuth);
		data.put("videoId",  resp.body.videoId);
		map.put("data", data);
		map.put("result", errInfo);
		return map;
	}
    /**
     * 刷新音/视频上传凭证
     * @param client 发送请求客户端
     * @return RefreshUploadVideoResponse 刷新音/视频上传凭证响应数据
     * @throws Exception
     */
	@RequestMapping(value="/refreshUploadVideo")
	@ResponseBody
	public Object refreshUploadVideo() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		com.aliyun.vod20170321.Client client = AudioOrVideoCreateUpload.createClient();
        RefreshUploadVideoRequest request = new RefreshUploadVideoRequest().setVideoId(pd.getString("VideoId"));
		// 复制代码运行请自行打印 API 的返回值
        RefreshUploadVideoResponse resp=client.refreshUploadVideo(request);
		//com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));
        PageData data = new PageData();
        data.put("requestId", resp.body.requestId);
        data.put("uploadAddress", resp.body.uploadAddress);
        data.put("uploadAuth",  resp.body.uploadAuth);
        data.put("videoId",  resp.body.videoId);
        map.put("data", data);
		map.put("result", errInfo);
		return map;
	}

	@RequestMapping(value="/submitTrans")
	@ResponseBody
	public Object submitTrans() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		DefaultAcsClient client = SubmitTrans.initVodClient();
		SubmitTranscodeJobsResponse response = new SubmitTranscodeJobsResponse();
		try {
			response = SubmitTrans.submitTranscodeJobs(client, pd);
			// 任务ID
			System.out.println("JobId = " + response.getTranscodeJobs().get(0).getJobId());
		} catch (Exception e) {
			System.out.println("ErrorMessage = " + e.getLocalizedMessage());
		}
		map.put("result", errInfo);
		return map;
	}
	@RequestMapping(value="/getVideoPlayAuth")
	@ResponseBody
	public Object getVideoPlayAuth() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
		try {
			response = AudioOrVideoCreateUpload.getVideoPlayAuth(pd);
			// 任务ID
			//System.out.println("JobId = " + response.getTranscodeJobs().get(0).getJobId());
		} catch (Exception e) {
			System.out.println("ErrorMessage = " + e.getLocalizedMessage());
		}
		map.put("result", errInfo);
		return map;
	}

	@RequestMapping(value="/getPlayInfo")
	@ResponseBody
	public Object getPlayInfo() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData video = videocoursewareService.findById(pd);
		if(video.get("VIDEOCOURSEWARE_ID_REMOTE") != null){//有远程ID 则获取远程auth
			PageData curriculum = curriculumService.findById(pd);
			PageData authPd = new PageData();
			authPd.put("VIDEOCOURSEWARE_ID",video.get("VIDEOCOURSEWARE_ID_REMOTE"));
			authPd.put("CURRICULUM_ID",video.get("CURRICULUM_ID_REMOTE"));
			PageData playAuth = synchronizeInformationService.syncVideoInfo(authPd);
			map.put("COVERURL", playAuth.get("COVERURL"));
			map.put("PLAYURL", playAuth.get("PLAYURL"));
			map.put("message", "获取成功。");
		}else {
			GetPlayInfoResponse response = new GetPlayInfoResponse();
			try {

				response = GetPlayInfo.getPlayInfo(pd);

				map.put("COVERURL", response.getVideoBase().getCoverURL());
				List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
				for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
					if (playInfo != null && Tools.notEmpty(playInfo.getPlayURL())
							&& Tools.notEmpty(playInfo.getFormat()) && "mp4".equals(playInfo.getFormat())) {
						map.put("PLAYURL", playInfo.getPlayURL());
						break;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
//			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
		map.put("result", errInfo);
		return map;
	}

	public static void main(String[] args) {
		System.out.println("42e1940a50994a1b9eb7d6cb0e663816".hashCode());
	}
}
