package cn.com.ctop.manage.modules.edu.service.impl;

import cn.com.ctop.common.module.utils.HttpUtils2;
import cn.com.ctop.manage.modules.edu.entity.EduLesson;
import cn.com.ctop.manage.modules.edu.mapper.EduLessonMapper;
import cn.com.ctop.manage.modules.edu.service.IEduLessonService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 在线培训
 * @author jeecg-boot
 * @date   2020-03-19
 * @version V1.0
 */
@Service
public class EduLessonServiceImpl extends ServiceImpl<EduLessonMapper, EduLesson> implements IEduLessonService {
    @Autowired
    private EduLessonMapper eduLessonMapper;

    @Override
    public List<String> getTitleList(String media){
        return eduLessonMapper.getTitleList(media);
    }

    @Override
    public List<String> getTopicList(String media, String title) {
        return eduLessonMapper.getTopicList(media,title);
    }

    @Override
    public void getKuaishouEduLesson(String url){
        Map<String,String> headMap = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        headMap.put("Cookie","did=web_fw97qjh9jbc3ne7dg0; userId=1153842485; kuaishou.college_st=ChNrdWFpc2hvdS5jb2xsZWdlLnN0EpABZ2njtVDiaYnwbiQTvnW3TUQhkzO8NghQARfbKkH9a2IhQBIu8DdtCvnvFcHIP4ejDTStz6sTrrt80s_edSdepKEmZjOOPfVGkOQw11YJ2GiN546ewm4xpg2Vdm5D58WodpnQjfYLo_BzfBkiaeX3uItkKtGSFrNJkeJD6cUaJoslsDLNM8NO7wFNfZ8Kcxg5GhIjLQpcM9v7BdoZNqxObBaB12YiIJ6lZ2Nysm96bD_oGE-YnsGWyiqIja8HvakoWiCVdmKVKAUwAQ; kuaishou.college_ph=698388e984d93489326f14192cc580cf5079");
        String result = HttpUtils2.httpGetRequest(url,headMap, jsonObject);
        ObjectMapper mapper = new ObjectMapper();
        try {

            JsonNode rootNode = mapper.readTree(result);
            int code = rootNode.get("code").asInt();
            if(code != 0){
                return;
            }
            Iterator<JsonNode> resultList = rootNode.get("result").elements();
            while (resultList.hasNext()){
                JsonNode resultNode = resultList.next();
                String directory = resultNode.get("directory").asText();
                Iterator<JsonNode> list = resultNode.get("lists").elements();
                while (list.hasNext()){
                    JsonNode listNode = list.next();
                    String id = listNode.get("id").asText();
                    String title = listNode.get("title").asText();
                    String intro = listNode.get("intro").asText();
                    String coverImageUrl = listNode.get("coverImageUrl").asText();
                    String detailUrl = "https://daxue.kuaishou.com/api/commercial/course/";
                    String detailResult = HttpUtils2.httpGet(detailUrl+id,null,headMap);
                    JsonNode detailNode = mapper.readTree(detailResult);
                    code = detailNode.get("code").asInt();
                    if(code != 0){
                        continue;
                    }
                    String videoUrl = detailNode.get("result").get("videoVO").get("videoUrl").asText();
                    EduLesson eduLesson = new EduLesson();
                    eduLesson.setTitle(directory);
                    eduLesson.setName(title);
                    eduLesson.setIntro(intro);
                    eduLesson.setLessonId(id);
                    eduLesson.setFileUrl(videoUrl);
                    eduLesson.setCoverUrl(coverImageUrl);
                    eduLesson.setMedia("快手大学");
                    eduLesson.setFileType("1");
                    QueryWrapper<EduLesson> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("lesson_id",id);
                    EduLesson eduLesson1 = this.getOne(queryWrapper);
                    if (eduLesson1 == null){
                        save(eduLesson);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void getBytedanceEduLesson(String url){
//        String url = "https://school.oceanengine.com/academy/v2/course/learning_path_json/1/";
        Map<String,String> headMap = new HashMap<>();
        headMap.put("Cookie","gr_user_id=aaccc127-673c-432b-9a5c-8a5e537d6e88; grwng_uid=6b421ac6-8c56-46c1-af6d-9165e3256337; Hm_lvt_c251f3beaafbfeb49ed17b7b9eccc320=1584439500,1584440073,1584495600,1584599208; sso_uid_tt=64cb330a60822929dd9045a3b03ddae2; sso_uid_tt_ss=64cb330a60822929dd9045a3b03ddae2; toutiao_sso_user=357df3ec5e0d04e1883753b7158db365; toutiao_sso_user_ss=357df3ec5e0d04e1883753b7158db365; sid_guard=88c8f36a54e352b53ef0af4374ec1678%7C1584437402%7C5184000%7CSat%2C+16-May-2020+09%3A30%3A02+GMT; uid_tt=f66332546a2ade016fcce281671f7bae; uid_tt_ss=f66332546a2ade016fcce281671f7bae; sid_tt=88c8f36a54e352b53ef0af4374ec1678; sessionid=88c8f36a54e352b53ef0af4374ec1678; sessionid_ss=88c8f36a54e352b53ef0af4374ec1678; academy_session_id=e2ee203cafe44418a4e4accf0b63560a; gr_session_id_bcf54a2fc11eee09=c18a9e8b-12e1-4960-a126-b0d1b6bf3d09; gr_session_id_bcf54a2fc11eee09_c18a9e8b-12e1-4960-a126-b0d1b6bf3d09=true; gr_cs1_c18a9e8b-12e1-4960-a126-b0d1b6bf3d09=user_id%3A74099510334; csrf_token=A8YNIzGd7y7XGIh6WINH9CE6bBmvKlLa; Hm_lpvt_c251f3beaafbfeb49ed17b7b9eccc320=1584599265");
        String result = HttpUtils2.httpGet(url,null,headMap);
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode rootNode = mapper.readTree(result);
            String status = rootNode.get("status").asText();
            if (status == null || !"success".equals(status)) {
                return;
            }
            String title = rootNode.get("data").get("title").asText();
            Iterator<JsonNode> dataList = rootNode.get("data").get("data").elements();
            while (dataList.hasNext()){
                JsonNode dataNode = dataList.next();
                String topic = dataNode.get("topic").asText();
                Iterator<JsonNode> coursesList = dataNode.get("courses").elements();
                while (coursesList.hasNext()){
                    JsonNode coursesNode = coursesList.next();
                    String id = coursesNode.get("course_id").asText();
                    String name = coursesNode.get("course_name").asText();
                    String detailUrl = "https://school.oceanengine.com/academy/v2/course/detail/";
                    String detailResult = HttpUtils2.httpGet(detailUrl+id,null,headMap);
                    JsonNode detailNode = mapper.readTree(detailResult);
                    status = detailNode.get("status").asText();
                    if (status == null || !"success".equals(status)) {
                        return;
                    }
                    JsonNode courseNode = detailNode.get("data").get("course_data");
                    String videoUrl = null;
                    String videoId = null;
                    if (courseNode.get("video_info") == null){
                        videoUrl = courseNode.get("file_url").asText();
                    }else {

                        videoId = courseNode.get("video_info").get("video_unique").asText();
                        videoUrl = "http://i.snssdk.com/video/playcode/1/toutiao/"+videoId+"?auto_play=1";
//                        videoId = courseNode.get("video_info").has("video_id")==false?courseNode.get("file_url").asText():courseNode.get("video_data").get("video_id").asText();
                    }

                    String createDate = courseNode.get("create_time").asText();
                    String coverUrl = courseNode.get("cover_url").asText();
                    String creator = courseNode.get("speaker").get("name").asText();
                    String intro = courseNode.get("intro").asText();
                    String fileType = courseNode.get("type").toString();
//                    String name = courseNode.get("name").asText();
                    EduLesson eduLesson = new EduLesson();
                    eduLesson.setFileId(videoId);
                    eduLesson.setCoverUrl(coverUrl);
                    eduLesson.setPublicTime(DateUtils.parseDate(createDate,"yyyy-MM-dd HH:mm:ss"));
                    eduLesson.setCreator(creator);
                    eduLesson.setFileUrl(videoUrl);
                    eduLesson.setMedia("巨量引擎");
                    eduLesson.setLessonId(id);
                    eduLesson.setTitle(title);
                    eduLesson.setTopic(topic);
                    eduLesson.setFileType(fileType);
                    eduLesson.setIntro(intro);
                    eduLesson.setName(name);
                    QueryWrapper<EduLesson> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("lesson_id",id);
                    EduLesson eduLesson1 = this.getOne(queryWrapper);
                    if (eduLesson1 == null){
                        save(eduLesson);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //培训视频上传接口
    @Override
    public String uploadLesson(EduLesson eduLesson) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        eduLesson.setLessonId(uuid);
        eduLesson.setCreator(sysUser.getRealname());

        save(eduLesson);
        return uuid;
    }


}
