package com.zcloud.controller.onlinexxks;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.service.gateway.SynchronizeInformationService;
import com.zcloud.service.onlinexxks.ChapterService;
import com.zcloud.service.onlinexxks.CurriculumService;
import com.zcloud.service.onlinexxks.KcmiddlekjService;
import com.zcloud.service.onlinexxks.VideoCoursewareService;
import com.zcloud.util.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * @author fangjiakai
 * @date 2022/9/19/019 11:56
 */
@Controller
@RequestMapping("/videoRes")
public class VideoResController extends BaseController {

    @Value("${customer.id}")
    private String customerId;

    @Value("${customer.SECRET_KEY}")
    private String customer_secret_key;

    @Value("${customer.url}")
    private String url;

    @Value("${customer.domain}")
    private String domain;

    @Autowired
    private CurriculumService curriculumService;
    @Autowired
    private VideoCoursewareService videocoursewareService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private KcmiddlekjService kcmiddlekjService;
    @Autowired
    private SynchronizeInformationService synchronizeInformationService;

    /**列表
     * @param page
     * @throws Exception
     */
    @RequestMapping(value="/list")
    @RequiresPermissions("videoRes: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());
        page.setPd(pd);
        Map<String, String> request = new HashMap<String, String>();
        request.put("id", this.customerId);
        String key = MD5.md5(this.customer_secret_key + domain);
        request.put("SECRET_KEY", key);
        request.put("KEYWORDS", KEYWORDS);
        request.put("showCount", String.valueOf(page.getShowCount()));
        request.put("currentPage", String.valueOf(page.getCurrentPageForApi()));
        String response = HttpRequestUtil.doPost(url + "/curriculum/getCurList", JSONObject.toJSONString(request));
        JSONObject responseResult = JSONObject.parseObject(response);
        if(responseResult != null && responseResult.get("code") != null && Tools.notEmpty(responseResult.get("code").toString()) && "0".equals(responseResult.get("code"))){
            page.setCurrentPage(Integer.parseInt(responseResult.getJSONObject("page").getString("currentPage")));
            page.setTotalPage(Integer.parseInt(responseResult.getJSONObject("page").getString("totalPage")));
            page.setTotalResult(Integer.parseInt(responseResult.getJSONObject("page").getString("totalResult")));
            map.put("varList", responseResult.getJSONArray("curriculumList"));
        } else {
//            System.out.println(responseResult.get("code"));
            map.put("msg", "请求出错，请联系管理员。");
        }
//        List<PageData> varList = videocoursewareService.list(page);	//列出VideoCourseware列表
        map.put("page", page);
        map.put("result", errInfo);
        return map;
    }

    /**去修改页面获取数据
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/goEdit")
    @RequiresPermissions("videoRes:edit")
    @ResponseBody
    public Object goEdit() throws Exception{
        Map<String,Object> map = new HashMap<String,Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();

        Map<String, String> request = new HashMap<String, String>();
        request.put("CURRICULUM_ID", pd.get("CURRICULUM_ID").toString());
        request.put("id", this.customerId);
        String key = MD5.md5(this.customer_secret_key + domain);
        request.put("SECRET_KEY", key);
        String response = HttpRequestUtil.doPost(url + "/curriculum/getCurInfo", JSONObject.toJSONString(request));
        JSONObject responseResult = JSONObject.parseObject(response);
        if(responseResult != null && responseResult.get("code") != null && Tools.notEmpty(responseResult.get("code").toString()) && "0".equals(responseResult.get("code"))){

            map.put("pd", responseResult.getJSONObject("pd"));
            map.put("chapterList", responseResult.getJSONArray("chapterList"));
        } else {
            errInfo = "warning";
            map.put("msg", "请求出错，请联系管理员。");
        }
//        map.put("chapterList", chapterList);
        map.put("result", errInfo);
        return map;
    }

    /**去修改页面获取数据
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/syncCurriculum")
    @RequiresPermissions("videoRes:edit")
    @ResponseBody
    public Object syncCurriculum() throws Exception{

        Map<String,Object> map = new HashMap<String,Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        PageData curRemote = new PageData();
        curRemote.put("CURRICULUM_ID_REMOTE", pd.get("CURRICULUM_ID"));
        // 验证是否添加过此课程
        PageData curriculumRes = curriculumService.findByRemoteId(curRemote);
        if(curriculumRes != null && curriculumRes.get("CURRICULUM_ID") != null && Tools.notEmpty(curriculumRes.get("CURRICULUM_ID").toString())){
            map.put("msg","该课程已添加。无需二次添加。");
            errInfo = "warning";
        } else {
            Map<String, String> request = new HashMap<String, String>();
            request.put("CURRICULUM_ID", pd.get("CURRICULUM_ID").toString());
            request.put("id", this.customerId);
            String key = MD5.md5(this.customer_secret_key + domain);
            request.put("SECRET_KEY", key);
            String response = HttpRequestUtil.doPost(url + "/curriculum/getCurInfo", JSONObject.toJSONString(request));
            JSONObject responseResult = JSONObject.parseObject(response);
            if (responseResult != null && responseResult.get("code") != null && Tools.notEmpty(responseResult.get("code").toString()) && "0".equals(responseResult.get("code"))) {
                JSONObject curricullum = responseResult.getJSONObject("pd");
                List<JSONObject> chapterList = JSON.parseArray(responseResult.getString("chapterList"), JSONObject.class);
                PageData cur = new PageData();
                PageData idDate = new PageData();
                // 保存课程
                if (curricullum != null && curricullum.get("CURRICULUM_ID") != null) {
                    cur.put("CURRICULUM_ID", this.get32UUID());
                    cur.put("CURRICULUM_ID_REMOTE", curricullum.get("CURRICULUM_ID"));
                    cur.put("CURRICULUMNAME", curricullum.getString("CURRICULUMNAME"));
                    cur.put("CURRICULUMINTRODUCE", curricullum.getString("CURRICULUMINTRODUCE"));
//                    cur.put("CATALOGUELEVEL", curricullum.getString("CATALOGUELEVEL"));
//                    cur.put("VIDEOTIME", curricullum.getString("VIDEOTIME"));
                    cur.put("ISDELETE", "0");
                    cur.put("CREATOR", Jurisdiction.getUsername());    //添加人
                    cur.put("CREATTIME", DateUtil.date2Str(new Date()));    //添加时间
                    cur.put("OPERATOR", Jurisdiction.getUsername());    //修改人
                    cur.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
                    cur.put("ISCOMPLETE", "0");
                    cur.put("STATE", "1");

                }
                double totalVideoTime = 0.0;
                // 保存章节及视频
                if (chapterList != null && chapterList.size() > 0) {
                    int sort = 0;

                    for (JSONObject chapterJson : chapterList) {
                        // 关联课件时，查询课件是否保存过，如果没保存过，进行保存
                        if (chapterJson.get("VIDEOCOURSEWARE_ID") != null && Tools.notEmpty(chapterJson.get("VIDEOCOURSEWARE_ID").toString())) {
                            chapterJson.put("SORT",sort++);
                            chapterJson.put("CURRICULUM_ID", cur.get("CURRICULUM_ID"));
                            // 保存章节数据
                            PageData chapter = saveChapter(chapterJson);
                            chapterJson.put("CURRICULUM_ID_REMOTE", curricullum.get("CURRICULUM_ID")); //赋值课程ID用于存视频课件表CURRICULUM_ID_REMOTE
                            chapterJson.put("TIMEOUT_REMOTE",curricullum.get("VALID_DATE"));
                            PageData video = saveVideo(chapterJson);
                            totalVideoTime+=Double.parseDouble(video.getString("VIDEOTIME"));
                            saveMiddle(cur,chapter,video);
                        }

                        // 查看是否有下级章节
                        if (chapterJson.get("nodes") != null && Tools.notEmpty(chapterJson.get("nodes").toString())) {
                            List<JSONObject> nodes = (List<JSONObject>) JSON.parse(chapterJson.get("nodes").toString());
                            if (nodes != null && nodes.size() > 0) {
                                for (JSONObject node : nodes) {
                                    // 关联课件时，查询课件是否保存过，如果没保存过，进行保存
                                    if (node.get("VIDEOCOURSEWARE_ID") != null && Tools.notEmpty(node.get("VIDEOCOURSEWARE_ID").toString())) {
                                        node.put("SORT",sort++);
                                        node.put("CURRICULUM_ID", cur.get("CURRICULUM_ID"));
                                        // 保存章节数据
                                        node.put("CURRICULUM_ID_REMOTE", curricullum.get("CURRICULUM_ID")); //赋值课程ID用于存视频课件表CURRICULUM_ID_REMOTE
                                        node.put("TIMEOUT_REMOTE",curricullum.get("VALID_DATE"));
                                        PageData chapter = saveChapter(node);
                                        PageData video = saveVideo(node);
                                        totalVideoTime+=Double.parseDouble(video.getString("VIDEOTIME"));
                                        saveMiddle(cur,chapter,video);
                                    }
                                }
                            }
                        }
                    }
                }
                cur.put("CLASSHOUR", Math.floor(totalVideoTime / 60));
                curriculumService.save(cur);
            } else {
                errInfo = "warning";
                map.put("msg", "请求出错，请联系管理员。");
            }
        }
        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();

        PageData playAuth = synchronizeInformationService.syncVideoPlayAuth(pd);
        map.put("responseBody", playAuth.get("responseBody"));
        map.put("message", "获取成功。");
        map.put("type", "success");
//        map.put("chapterList", chapterList);
        map.put("result", errInfo);
        return map;
    }


    private PageData saveChapter(JSONObject oldCha) throws Exception {
        PageData newCha = new PageData();
        newCha.put("CHAPTER_ID", this.get32UUID());
        newCha.put("CHAPTER_ID_REMOTE",  oldCha.get("CHAPTER_ID"));
        newCha.put("CURRICULUM_ID", oldCha.get("CURRICULUM_ID"));
        newCha.put("ISDELETE", "0");
        newCha.put("CREATOR", Jurisdiction.getUsername());	//添加人
        newCha.put("CREATTIME", DateUtil.date2Str(new Date()));	//添加时间
        newCha.put("OPERATOR", Jurisdiction.getUsername());	//修改人
        newCha.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
        newCha.put("NAME", oldCha.getString("NAME"));
        newCha.put("SORT", oldCha.getString("SORT"));
        chapterService.save(newCha);
        return newCha;
    }

    private PageData saveVideo(JSONObject oldVIdeo) throws Exception {
        PageData videoRemote = new PageData();
        videoRemote.put("VIDEOCOURSEWARE_ID_REMOTE", oldVIdeo.get("VIDEOCOURSEWARE_ID"));

        PageData video = new PageData();
        video = videocoursewareService.findByRemoteId(videoRemote);
        if(video == null || video.get("VIDEOCOURSEWARE_ID") == null){// 课件为空时，保存此课件
            video = new PageData();
            video.put("VIDEOCOURSEWARE_ID_REMOTE", oldVIdeo.get("VIDEOCOURSEWARE_ID"));
            video.put("VIDEOCOURSEWARE_ID", this.get32UUID());
            video.put("ISDELETE", "0");
            video.put("CREATOR", Jurisdiction.getUsername());	//添加人
            video.put("CREATTIME", DateUtil.date2Str(new Date()));	//添加时间
            video.put("OPERATOR", Jurisdiction.getUsername());	//修改人
            video.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
            video.put("STATE", "0");
            video.put("ISCOMPLETE", "0");
            video.put("COURSEWARENAME", oldVIdeo.get("COURSEWARENAME"));
            video.put("COURSEWAREINTRODUCE", oldVIdeo.get("COURSEWAREINTRODUCE"));
            video.put("VIDEOFILES", oldVIdeo.get("VIDEOFILES"));
            video.put("CLASSHOUR", Math.floor(Double.parseDouble(oldVIdeo.getString("VIDEOTIME"))/60));
            video.put("VIDEOTIME", oldVIdeo.get("VIDEOTIME"));
            video.put("CURRICULUM_ID_REMOTE", oldVIdeo.get("CURRICULUM_ID_REMOTE"));
            video.put("TIMEOUT_REMOTE", oldVIdeo.get("TIMEOUT_REMOTE"));
            video.put("ISPERFECT","0");  //课件添加过来默认没有完善
            videocoursewareService.save(video);
        } else {
            video.put("VIDEOCOURSEWARE_ID",video.get("VIDEOCOURSEWARE_ID"));
            video.put("CURRICULUM_ID_REMOTE", oldVIdeo.get("CURRICULUM_ID_REMOTE"));
            video.put("TIMEOUT_REMOTE", oldVIdeo.get("TIMEOUT_REMOTE"));
            videocoursewareService.editTimeOut(video);
        }
        return video;
    }

    private void saveMiddle(PageData cur, PageData chapter, PageData video)throws Exception {
        PageData middle = new PageData();
        middle.put("KCMIDDLEKJ_ID", this.get32UUID());
        middle.put("CURRICULUMID", cur.get("CURRICULUM_ID"));
        middle.put("CHAPTER_ID", chapter.get("CHAPTER_ID"));
        middle.put("COURSEWAREID", video.get("VIDEOCOURSEWARE_ID"));
        middle.put("COURSEWARETYPE", "1");

        middle.put("ISDELETE", "0");
        middle.put("CREATOR", Jurisdiction.getUsername());	//添加人
        middle.put("CREATTIME", DateUtil.date2Str(new Date()));	//添加时间
        middle.put("OPERATOR", Jurisdiction.getUsername());	//修改人
        middle.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间

        kcmiddlekjService.save(middle);
    }
}
