package com.zcloud.controller.courseware;

import com.aliyun.vod20170321.models.GetVideoInfoResponse;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.courseware.DataCoursewareService;
import com.zcloud.service.courseware.QuestionService;
import com.zcloud.service.courseware.VideoCoursewareService;
import com.zcloud.service.curriculum.CurriculumService;
import com.zcloud.service.gateway.SynchronizeInformationService;
import com.zcloud.util.*;
import com.zcloud.util.ali.GetVideoInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * 说明：资料课件维护
 * 作者：luoxiaobao
 * 时间：2021-06-26
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/app/courseware")
public class AppCoursewareController extends BaseController {

	@Autowired
	private VideoCoursewareService videoCoursewareService;
	@Autowired
	private DataCoursewareService datacoursewareService;
	@Autowired
	private QuestionService questionService;
	@Autowired
	private Smb smb;
	@Autowired
	private CurriculumService curriculumService;
	@Autowired
	private SynchronizeInformationService synchronizeInformationService;
	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "资料课件维护",instructionsOperate = "资料课件维护",instructionsType = "列表")
	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());
		page.setPd(pd);
		List<PageData>	varList = new ArrayList<PageData>();
		if ("1".equals(pd.getString("COURSEWARETYPE"))) {
			varList = videoCoursewareService.list(page);
			for(PageData video : varList) {
				try{
					//获取视频封面
					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.syncVideoPlayAuth(authPd);
						map.put("responseBody", playAuth.get("responseBody"));
						map.put("message", "获取成功。");
					} else {
						PageData vidData = new PageData();
						vidData.put("videoId", video.get("VIDEOFILES"));
						GetVideoInfoResponse response = null;
						response = GetVideoInfo.getVideoInfo(vidData);
						if (response.body.video.coverURL != null) {
							video.put("VIDEOCAPTURE", response.body.video.coverURL);
						}
					}
				} catch (Exception e){
					e.printStackTrace();
				}

			}
		} else {
			varList = datacoursewareService.list(page);	//列出DataCourseware列表
		}
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	// @RequiresPermissions("courseware:add")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "资料课件维护",instructionsOperate = "资料课件维护",instructionsType = "新增")
	public Object add(@RequestParam(value="cfile",required=false) MultipartFile cfile,
					  @RequestParam(value="ccfile",required=false) MultipartFile ccfile) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("DATACOURSEWARE_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
		if (null != cfile && !cfile.isEmpty()) {
			String  ffile = DateUtil.getDays();
			//本地
//			String filePath = PathUtil.getProjectpath() + Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile;	//文件上传路径
//			String fileName = FileUpload.fileUp(file, filePath, this.get32UUID());				//执行上传
			//服务器
			String fileName = this.get32UUID()+cfile.getOriginalFilename().substring(cfile.getOriginalFilename().lastIndexOf("."));
			smb.sshSftp(cfile, fileName, Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile);
			pd.put("COURSEWAREFILES", Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile + "/" + fileName);
		}
		if (null != ccfile && !ccfile.isEmpty()) {
			String  ffile = DateUtil.getDays();
			//本地
//			String filePath = PathUtil.getProjectpath() + Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile;	//文件上传路径
//			String fileName = FileUpload.fileUp(file, filePath, this.get32UUID());				//执行上传
			//服务器
			String fileName = this.get32UUID()+ccfile.getOriginalFilename().substring(ccfile.getOriginalFilename().lastIndexOf("."));
			smb.sshSftp(ccfile, fileName, Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile);
			pd.put("COURSEWARECAPTURE", Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile + "/" + fileName);
		}
		datacoursewareService.save(pd);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	// @RequiresPermissions("courseware:del")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "资料课件维护",instructionsOperate = "资料课件维护",instructionsType = "删除")
	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 = datacoursewareService.findById(pd);
		smb.deleteFile(d.getString("COURSEWAREFILES"));
		smb.deleteFile(d.getString("COURSEWARECAPTURE"));
		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", "2");	//课件类型
		questionService.deleteByCoursewareIds(pd);
		datacoursewareService.delete(pd);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	// @RequiresPermissions("courseware:edit")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "资料课件维护",instructionsOperate = "资料课件维护",instructionsType = "修改")
	public Object edit(@RequestParam(value="cfile",required=false) MultipartFile cfile,
					   @RequestParam(value="ccfile",required=false) MultipartFile ccfile) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();

		PageData d = datacoursewareService.findById(pd);
		smb.deleteFile(d.getString("COURSEWAREFILES"));
		smb.deleteFile(d.getString("COURSEWARECAPTURE"));
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		if (null != cfile && !cfile.isEmpty()) {
			String  ffile = DateUtil.getDays();
			//本地
//			String filePath = PathUtil.getProjectpath() + Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile;	//文件上传路径
//			String fileName = FileUpload.fileUp(file, filePath, this.get32UUID());				//执行上传
			//服务器
			String fileName = this.get32UUID()+cfile.getOriginalFilename().substring(cfile.getOriginalFilename().lastIndexOf("."));
			smb.sshSftp(cfile, fileName, Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile);
			pd.put("COURSEWAREFILES", Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile + "/" + fileName);
		}
		if (null != ccfile && !ccfile.isEmpty()) {
			String  ffile = DateUtil.getDays();
			//本地
//			String filePath = PathUtil.getProjectpath() + Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile;	//文件上传路径
//			String fileName = FileUpload.fileUp(file, filePath, this.get32UUID());				//执行上传
			//服务器
			String fileName = this.get32UUID()+ccfile.getOriginalFilename().substring(ccfile.getOriginalFilename().lastIndexOf("."));
			smb.sshSftp(ccfile, fileName, Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile);
			pd.put("COURSEWARECAPTURE", Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile + "/" + fileName);
		}
		datacoursewareService.edit(pd);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "资料课件维护",instructionsOperate = "资料课件维护",instructionsType = "去修改页面获取数据")
	public Object goEdit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = datacoursewareService.findById(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/getVideoCourseware")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "资料课件维护",instructionsOperate = "资料课件维护",instructionsType = "去修改页面获取数据")
	public Object getVideoCourseware() 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读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/getDataCourseware")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "资料课件维护",instructionsOperate = "资料课件维护",instructionsType = "去修改页面获取数据")
	public Object getDataCourseware() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = datacoursewareService.findById(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**批量删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAll")
	// @RequiresPermissions("courseware:del")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "资料课件维护",instructionsOperate = "资料课件维护",instructionsType = "批量删除")
	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 = datacoursewareService.findByIds(pd);
			for (PageData d : pdList) {
				smb.deleteFile(d.getString("COURSEWAREFILES"));
				smb.deleteFile(d.getString("COURSEWARECAPTURE"));
			}
			pd.put("COURSEWARETYPE", "2");	//课件类型
			questionService.deleteByCoursewareIds(pd);
			datacoursewareService.deleteAll(pd);
			errInfo = "success";
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**导出到excel
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/excel")
	// @RequiresPermissions("toExcel")
	@LogAnno(menuType= "手机",menuServer= "资料课件维护",instructionsOperate = "资料课件维护",instructionsType = "导出到excel")
	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 = datacoursewareService.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("COURSEWAREFILES"));	    //4
			vpd.put("var5", varOList.get(i).getString("COURSEWARECAPTURE"));	    //5
			vpd.put("var6", varOList.get(i).getString("COURSEWAREUSERS"));	    //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
	@LogAnno(menuType= "手机",menuServer= "资料课件维护",instructionsOperate = "资料课件维护",instructionsType = "列表")
	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 = datacoursewareService.getSelect(pd);	//列出DataCourseware列表
		map.put("list", varList);
		map.put("result", errInfo);
		return map;
	}

	/**列表（全部视频课件+资料课件）
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/getAllCourseware")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "资料课件维护",instructionsOperate = "资料课件维护",instructionsType = "全部视频课件和资料列表")
	public Object getAllCourseware(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 = datacoursewareService.getAllCourseware(pd);	//列出DataCourseware列表
		map.put("list", varList);
		map.put("result", errInfo);
		return map;
	}

}
