package com.zcloud.controller.onlinexxks;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.zcloud.service.gateway.SynchronizeInformationService;
import com.zcloud.util.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.aliyun.vod20170321.models.GetVideoInfoResponse;
import com.aliyun.vod20170321.models.GetVideoPlayAuthResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetTranscodeSummaryResponse;
import com.aliyuncs.vod.model.v20170321.GetTranscodeSummaryResponse.TranscodeSummary;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.service.onlinexxks.CoursewareRelationService;
import com.zcloud.service.onlinexxks.QuestionService;
import com.zcloud.service.onlinexxks.VideoCoursewareService;

import com.zcloud.util.ali.AudioOrVideoCreateUpload;
import com.zcloud.util.ali.GetVideoInfo;
import com.zcloud.util.ali.SubmitTrans;

/**
 * 说明：视频课件维护
 * 作者：luoxiaobao
 * 时间：2021-06-26
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/videocourseware")
public class VideoCoursewareController extends BaseController {

	@Autowired
	private VideoCoursewareService videocoursewareService;
	@Autowired
	private QuestionService questionService;
//	@Autowired
//	private KcmiddlekjService kcmiddlekjService;
	@Autowired
	private CoursewareRelationService coursewarerelationService;
	@Autowired
	private SynchronizeInformationService synchronizeInformationService;
	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	@RequiresPermissions("courseware:add")
	@ResponseBody
	@Transactional
	public Object add() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("VIDEOCOURSEWARE_ID", this.get32UUID());  //主键
		pd.put("CREATOR", Jurisdiction.getUsername());  //添加人
		pd.put("CREATTIME", DateUtil.date2Str(new Date()));  //添加时间
		pd.put("OPERATOR", Jurisdiction.getUsername());  //修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));  //修改时间
		pd.put("ISDELETE", "0");  //是否删除(0:有效 1：删除)
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());  //企业ID
		pd.put("STATE", "0");  //课件状态 0启用、1禁用
		pd.put("PRICE", "0");  //价格，暂时为0
		pd.put("ISPLATFORM", "0");  //是否是平台主键
		pd.put("ISPERFECT", "1");

		// 判断视频是否上传
		if (pd.get("videoId") != null) {
			pd.put("VIDEOFILES", pd.get("videoId"));
			Boolean getVideoInfo = false;
			GetVideoInfoResponse response = null;
			for (int i = 0; i < 30; i++) {
				try {
					response = GetVideoInfo.getVideoInfo(pd);
				} catch (Exception e) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					map.put("msg", "获取视频信息失败，请稍后重试。");
					map.put("type", "warning");
					return map;
				}
				if (response.body.video.duration != null && 0.0 != response.body.video.duration) {
					pd.put("VIDEOTIME", response.body.video.duration);
					Double videoTime = Double.valueOf(response.body.video.duration);
					pd.put("CLASSHOUR", Math.floor(videoTime / 60));
					getVideoInfo = true;
					break;
				} else {
					Thread.sleep(3000);
				}
			}

			if (!getVideoInfo) {
				map.put("msg", "视频上传失败，请稍后重试。");
				map.put("type", "warning");
				return map;
			} else {
				// 处理视频转码
				try {
					DefaultAcsClient client = SubmitTrans.initVodClient();
					SubmitTrans.submitTranscodeJobs(client, pd);
				} catch (Exception e) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					map.put("msg", "视频转码失败，请稍后重试。");
					map.put("type", "warning");
					return map;
				}
			}
		}

		// 保存数据
		coursewarerelationService.saveByCourseware(pd, "1");  //存储课件和字典的关系表
		videocoursewareService.save(pd);
		map.put("msg", "上传成功。");
		map.put("type", "success");
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	@RequiresPermissions("courseware:del")
	@ResponseBody
	public Object delete() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData d = videocoursewareService.findById(pd);
		Smb.delete(d.getString("VIDEOFILES"));
		Smb.delete(d.getString("VIDEOCAPTURE"));
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		String ArrayDATA_IDS[] = { pd.getString("VIDEOCOURSEWARE_ID") };
		pd.put("ArrayDATA_IDS", ArrayDATA_IDS);	//待删除ids
		pd.put("COURSEWARETYPE", "1");	//课件类型

		pd.put("CURRICULUM_ID", pd.getString("VIDEOCOURSEWARE_ID"));	//课件类型
//		String count = kcmiddlekjService.countByCourseWareId(pd);
//		if(!"0".equals(count)){
//			map.put("result", "erroe");				//返回结果
//			map.put("msg", "该课程已经在课件中发布！");
//			return map;
//		}
		coursewarerelationService.saveByCourseware(pd,"1");//存储课件和字典的关系表 没有添加的数据，所有可以当删除使用
		questionService.deleteByCoursewareIds(pd);
		videocoursewareService.delete(pd);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	@RequiresPermissions("courseware:edit")
	@ResponseBody
	public Object edit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData d = videocoursewareService.findById(pd);
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间

		if(pd != null && pd.get("isEditVideo") != null && Tools.notEmpty(pd.get("isEditVideo").toString()) && "true".equals(pd.get("isEditVideo").toString())) {
			pd.put("VIDEOFILES", pd.get("videoId"));
			//获取视频封面及时长（每3秒访问一次阿里云，最多访问20次。）
//			GetVideoPlayAuthResponse response = null;
//			for (int i = 0; i < 120; i++) {
//				response = AudioOrVideoCreateUpload.getVideoPlayAuth(pd);
//				if(response.body.videoMeta.coverURL != null && response.body.videoMeta.duration != null) {
//					pd.put("VIDEOCAPTURE", response.body.videoMeta.coverURL);
//					pd.put("VIDEOTIME", response.body.videoMeta.duration);
//					System.out.println(i+"a------------------------"+response.body.videoMeta.coverURL);
//					break;
//				}else {
//					System.out.println(i+"b------------------------"+response.body.videoMeta.coverURL);
//					Thread.sleep(1000);
//				}
//			}
			Boolean getVideoInfo = false;
			//获取视频封面及时长（每2秒访问一次阿里云，最多访问30次。）
			GetVideoInfoResponse response = null;
			for (int i = 0; i < 30; i++) {
				try {
					response = GetVideoInfo.getVideoInfo(pd);
				} catch (Exception e) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				}
				if(response.body.video.duration != null && 0.0 != response.body.video.duration) {
//					pd.put("VIDEOCAPTURE", response.body.video.coverURL.substring(0, response.body.video.coverURL.indexOf("?")));
					pd.put("VIDEOTIME", response.body.video.duration);
					Double videoTime = Double.valueOf(response.body.video.duration);
					pd.put("CLASSHOUR", Math.floor(videoTime / 60));
					getVideoInfo = true;
					break;
				}else {
					Thread.sleep(3000);
				}
			}
			if(getVideoInfo) {
				coursewarerelationService.saveByCourseware(pd,"1");//存储课件和字典的关系表
				pd.put("ISPERFECT","1");
				videocoursewareService.edit(pd);
				map.put("msg", "上传成功。");
				map.put("type", "success");
				try {
					DefaultAcsClient client = SubmitTrans.initVodClient();
					// 视频转码
					SubmitTrans.submitTranscodeJobs(client, pd);
				} catch (Exception e) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				}
			} else {
				map.put("msg", "视频上传失败，请稍后重试。");
				map.put("type", "warning");
			}
		} else {
			coursewarerelationService.saveByCourseware(pd,"1");//存储课件和字典的关系表
			pd.put("ISPERFECT","1");
			videocoursewareService.edit(pd);
			map.put("msg", "修改成功。");
			map.put("type", "success");
		}

		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	@RequiresPermissions("courseware:list")
	@ResponseBody
	public Object list(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		page.setPd(pd);
		List<PageData>	varList = videocoursewareService.list(page);	//列出VideoCourseware列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	/**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	@ResponseBody
	public Object goEdit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = videocoursewareService.findById(pd);	//根据ID读取
		pd.put("RECORD_ID",pd.getString("VIDEOCOURSEWARE_ID"));
		Boolean getVideoInfo = false;
		//获取视频封面
		PageData vidData = new PageData();
		vidData.put("videoId", pd.get("VIDEOFILES"));
		GetVideoInfoResponse response = null;
		if(Tools.isEmpty(pd.getString("CURRICULUM_ID_REMOTE"))){ //商场添加的
			try {
				response = GetVideoInfo.getVideoInfo(vidData);
			} catch (Exception e) {
				e.printStackTrace();
				map.put("result", "error");
				map.put("msg", "视频获取失败");
				return map;
//			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
			if(response.body.video.coverURL != null) {
				pd.put("VIDEOCAPTURE", response.body.video.coverURL);
			}
		} else {
			pd.put("CURRICULUM_ID",pd.get("CURRICULUM_ID_REMOTE"));
			PageData playAuth = synchronizeInformationService.syncVideoInfo(pd);
			if(playAuth.getString("code").equals("0")){
				Object picture = playAuth.get("video");
				pd.put("VIDEOCAPTURE", ((JSONObject) picture).get("VIDEOCAPTURE"));
				map.put("message", "获取成功。");
			}else{
				map.put("result", "error");
				map.put("msg", "课程已过期");
				return map;
			}

		}
		List<PageData> coursewareAllList = coursewarerelationService.listAll(pd);//课件字典关系信息，全部的信息
		map.put("coursewareAllList", coursewareAllList);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**获取视频播放地址
	 * @param
	 * @throws Exception
	 */
	@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();

		GetTranscodeSummaryResponse tranRes = new GetTranscodeSummaryResponse();
		GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
		try {
			DefaultAcsClient client = SubmitTrans.initVodClient();
			tranRes = SubmitTrans.getTranscodeSummary(client, pd);
			if (tranRes.getTranscodeSummaryList() != null && tranRes.getTranscodeSummaryList().size() > 0) {
				TranscodeSummary summary = tranRes.getTranscodeSummaryList().get(0);
				if(summary.getTranscodeStatus() != null && Tools.notEmpty(summary.getTranscodeStatus())) {
					if("Processing".equals(summary.getTranscodeStatus())) {
						map.put("msg", "视频正在转码请稍后再试。");
						map.put("type", "warning");
						return map;
					}
				}
			} else {
				try {
					// 视频转码
					SubmitTrans.submitTranscodeJobs(client, pd);
				} catch (Exception e) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				}
				map.put("msg", "视频正在转码请稍后再试。");
				map.put("type", "warning");
				return map;
			}

			response = AudioOrVideoCreateUpload.getVideoPlayAuth(pd);
		} catch (Exception e) {
			// TODO: handle exception
		}
		if(response != null && response.body != null && response.body.playAuth != null) {
			map.put("msg", "获取成功。");
			map.put("type", "success");
			map.put("playAuth", response.body.playAuth);
		} else {
			map.put("msg", "视频获取失败，请稍后重试。");
			map.put("type", "warning");
		}
		map.put("result", errInfo);
		return map;
	}


	/**批量删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAll")
	@RequiresPermissions("courseware:del")
	@ResponseBody
	public Object deleteAll() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		String DATA_IDS = pd.getString("DATA_IDS");
		if(Tools.notEmpty(DATA_IDS)){
			String ArrayDATA_IDS[] = DATA_IDS.split(",");
			pd.put("ArrayDATA_IDS", ArrayDATA_IDS);	//待删除ids
			List<PageData> pdList = videocoursewareService.findByIds(pd);
			for (PageData d : pdList) {
				Smb.delete(d.getString("VIDEOFILES"));
				Smb.delete(d.getString("VIDEOCAPTURE"));
			}
			pd.put("COURSEWARETYPE", "1");	//课件类型
			questionService.deleteByCoursewareIds(pd);
			videocoursewareService.deleteAll(pd);
			errInfo = "success";
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**导出到excel
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/excel")
	@RequiresPermissions("toExcel")
	public ModelAndView exportExcel() throws Exception{
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		Map<String,Object> dataMap = new HashMap<String,Object>();
		List<String> titles = new ArrayList<String>();
		titles.add("课件名称");	//1
		titles.add("主讲人");	//2
		titles.add("课件介绍");	//3
		titles.add("课件文件路径");	//4
		titles.add("课件截图");	//5
		titles.add("使用人员");	//6
		titles.add("添加人");	//7
		titles.add("添加时间");	//8
		titles.add("修改人");	//9
		titles.add("修改时间");	//10
		titles.add("是否删除(0:有效 1：删除)");	//11
		titles.add("企业ID");	//12
		dataMap.put("titles", titles);
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		List<PageData> varOList = videocoursewareService.listAll(pd);
		List<PageData> varList = new ArrayList<PageData>();
		for(int i=0;i<varOList.size();i++){
			PageData vpd = new PageData();
			vpd.put("var1", varOList.get(i).getString("COURSEWARENAME"));	    //1
			vpd.put("var2", varOList.get(i).getString("SPEAKER"));	    //2
			vpd.put("var3", varOList.get(i).getString("COURSEWAREINTRODUCE"));	    //3
			vpd.put("var4", varOList.get(i).getString("VIDEOFILES"));	    //4
			vpd.put("var5", varOList.get(i).getString("VIDEOCAPTURE"));	    //5
			vpd.put("var6", varOList.get(i).getString("VIDEOUSERS"));	    //6
			vpd.put("var7", varOList.get(i).getString("CREATOR"));	    //7
			vpd.put("var8", varOList.get(i).getString("CREATTIME"));	    //8
			vpd.put("var9", varOList.get(i).getString("OPERATOR"));	    //9
			vpd.put("var10", varOList.get(i).getString("OPERATTIME"));	    //10
			vpd.put("var11", varOList.get(i).get("ISDELETE").toString());	//11
			vpd.put("var12", varOList.get(i).getString("CORPINFO_ID"));	    //12
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv,dataMap);
		return mv;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/getSelect")
	@ResponseBody
	public Object getSelect(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		List<PageData>	varList = videocoursewareService.getSelect(pd);	//列出VideoCourseware列表
		map.put("list", varList);
		map.put("result", errInfo);
		return map;
	}
	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/editState")
	@RequiresPermissions("courseware:edit")
	@ResponseBody
	public Object editState() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		videocoursewareService.editByState(pd);
		map.put("result", errInfo);
		return map;
	}
}
