<template>
    <el-dialog title="智能检索" :visible.sync="dialogVisibleAiCreateVideo" :append-to-body="true" width="90%"
        :before-close="handleClose" class="dialog_diy">
        <div style="box-sizing:border-box;padding:15px" v-loading="loading" element-loading-text="小可正在努力生成中，请稍等...">
            <div style="position: relative; width: 100%;height: 40px;margin-bottom: 10px;">
                <el-input class="inputC" style="height: 100%;" placeholder="搜索视频关键字（如需搜索多个可“，”隔开）" v-model="detail"
                    @keyup.enter.native="searchA()"></el-input>
                <div class="search_img" @click="searchA" style="right: 10px">
                    <img src="../../../assets/icon/search.png" alt />
                </div>
            </div>
            <div class="nav_box">
                <div class="nav" :class="{ active: navActive == 0 }" @click="navClick(0)">综合排序</div>
                <div class="nav" :class="{ active: navActive == 1 }" @click="navClick(1)">相关程度</div>
                <div class="nav" :class="{ active: navActive == 2 }" @click="navClick(2)">上传日期</div>
                <div class="nav" :class="{ active: navActive == 3 }" @click="navClick(3)">观看次数</div>
                <div class="nav" :class="{ active: navActive == 4 }" @click="navClick(4)">评分</div>
            </div>
            <div class="Box">
                <div class="video_box video_box2" v-for="(item, index) in data" :key="index">
                    <img :src="item.thumbnail.static" />
                    <span class="name" v-html="item.title"></span>
                    <span class="author">作者:{{ item.channel.title }}</span>
                    <span class="detail">{{ item.description }}</span>
                    <div class="tag" v-if="item.badges && item.badges.length > 0">
                        <el-tooltip :content="tag" placement="top" effect="dark" v-for="(tag, index) in item.badges.slice(0, 5)" :key="index">
                            <!-- content to trigger tooltip here -->
                            <span >{{ tag }}</span>
                        </el-tooltip>
                        
                    </div>
                    <div class="btn" :style="{marginTop: item.badges && item.badges.length > 0 ? '0' : 'auto'}">
                        <span @click="openUrl(item.id)">查看</span>
                        <span @click="checkUrl(item.title, item.id)">加入</span>
                    </div>
                </div>
                <div v-if="data.length == 0" class="no_data">暂无数据</div>
            </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="close">关 闭</el-button>
        </span>
    </el-dialog>
</template>

<script>
import { v4 as uuidv4 } from "uuid";
import _ from "lodash";

export default {
    components: {
    },
    props: {
        dialogVisibleAiCreateVideo: {
            type: Boolean,
            default: false
        },
        courseName: {
            type: String,
            default: ""
        },
        courseState: {
            type: Number,
        },
        lineCount: {
            type: Number,
        },
        unitJson: {
            type: Array,
        }
    },
    // 根据用户给你的参考资料
    data() {
        return {
            userid: this.$route.query.userid,
            radio: 0,
            aiJson: {
                ppt: ``,
                word: '',
                video: ''
            },
            aiUrl: {
                ppt: '',
                word: '',
                video: ''
            },
            detail: "",
            loading: false,
            url: "",
            data: [],
            uJson: {},
            navActive: 0
        }
    },
    watch: {
        dialogVisibleAiCreateVideo(newValue, oldValue) {
            if (newValue) {
                this.detail = ""
                this.data = []
                this.againEva()
            }
        },
    },
    methods: {
        handleClose(done) {
            this.close()
            done();
        },
        close() {
            this.$emit('update:dialogVisibleAiCreateVideo', false)
        },
        openUrl(url) {
            window.open('https://www.youtube.com/embed/'+url)
            // window.open(`//www.bilibili.com/video/${url}`)
        },
        checkUrl(name, id) {
            let json = {
                name: "链接",
                title: name.replace(/<[^>]*>?/gm, ''),
                url: 'https://www.youtube.com/embed/'+id,
                // url: `//player.bilibili.com/player.html?isOutside=true&bvid=${id}`,
                type: 8,
            }
            this.$emit('createAiVideo', json)
            this.$message.success('加入成功')
        },
        changeRadio() {
            if (this.radio == 0) {
                this.detail = this.aiJson.ppt
            }
            if (this.radio == 1) {
                this.detail = this.aiJson.word
            }
            if (this.radio == 2) {
                this.detail = this.aiJson.video
            }
        },
        // async aiGet() {
        //     let _this = this
        //     _this.loading = true
        //     this.ajax
        //         .get(`https://www.googleapis.com/youtube/v3/search?key=AIzaSyBUvNQ5Wyua4PbStE2vp3t7MIY4htry-4M&part=snippet&q=${this.detail}&maxResults=10&type=video&order=relevance&regionCode=HK`)
        //         .then((response) => {
        //             console.log(response);
        //             _this.data = response.data.items
        //             _this.loading = false

        //         })
        //         .catch((error) => {
        //             _this.loading = false
        //             console.log(error);
        //         });
        // },
        async aiGet() {
            let _this = this
            _this.loading = true
            this.ajax.post(`https://gpt4.cocorobo.cn/get_network_search`, {
                engine: "bilibili",
                keyword: this.detail
            }).then(response => {
                console.log(response);
                _this.data = response.data.FunctionResponse
                _this.loading = false

            })
                .catch((error) => {
                    _this.loading = false
                    console.log(error);
                });
        },
        // async aiGet2(msg) {
        //     let _this = this
        //     _this.loading = true
        //     this.ajax
        //         .get(`https://www.googleapis.com/youtube/v3/search?key=AIzaSyBUvNQ5Wyua4PbStE2vp3t7MIY4htry-4M&part=snippet&q=${msg}&maxResults=10&type=video&order=relevance&regionCode=HK`)
        //         .then((response) => {
        //             console.log(response);
        //             _this.data = response.data.items
        //             _this.loading = false

        //         })
        //         .catch((error) => {
        //             _this.loading = false
        //             console.log(error);
        //         });
        // },
        async aiGet2(msg) {
            let _this = this
            return new Promise((resolve, reject) => {
                this.ajax.post(`https://gpt4.cocorobo.cn/get_network_search`, {
                    engine: "youtubeNew",
                    keyword: msg,
                    // page: 1,
                    // page_size: 20,
                    order: this.navActive,
                    // duration: 0,
                }).then(response => {
                    console.log(response);
                    // _this.data = [..._this.data,...response.data.FunctionResponse]
                    resolve(response.data.FunctionResponse)
                })
                    .catch((error) => {
                        resolve([])
                        console.log(error);
                    });
            });
        },
        navClick(item) {
            if(this.navActive == item){
                return
            }
            this.navActive = item
            this.searchA()
        },
        async searchA(){
            let _this = this
            try {
                if(!_this.detail){
                    _this.$message.error("请输入关键字")
                    return
                }
                _this.loading = true
                let _content = ""
                if(_this.detail.split("，").length>1){
                    _content = _this.detail.split("，")
                }else{
                    _content = _this.detail.split(",")
                }
                _this.data = []
                let data2 = []
                for (var a = 0; a < _content.length; a++) {
                    let _data = await _this.aiGet2(_content[a])
                    data2[a] = _data
                }
                _this.data = _.flatMap(_.zip(...data2), (pair) => pair.filter(value => value !== undefined))
                // _this.data = _this.data.sort(
                //     function (a, b) {
                //         return b.play - a.play;
                //     }
                // );
                _this.againEva2();
                // _this.loading = false
            } catch (error){
                console.log(error);
                _this.loading = false
            }
            
        },
        againEva() {
            let _this = this
            _this.loading = true
            let message = `从以下内容中识别出1~2个学科知识点关键词，用于检索知识点相关视频。注意，你仅需要返回关键词，“，”分开。教案：${_this.unitJson[0].chapterInfo[0].taskJson[_this.lineCount].taskDetail3.replaceAll('#', '').replaceAll('*', '').replaceAll('-', '').replaceAll('\n', '')}`
            let parm = {
                assistant_id: 'f8e1ebb2-2e0d-11ef-8bf4-12e77c4cb76b',
                message: [{ "type": "text", "text": message.replaceAll('\n', " ").replaceAll('*', "") }],
                session_name: uuidv4(),
                userId: _this.userid,
                file_ids: [],
                model: 'gpt-4o-2024-08-06',
            }
            _this.ajax
                .post("https://gpt4.cocorobo.cn/ai_agent_park_chat", parm)
                .then(async (response) => {
                    console.log(response);
                    let data = response.data.FunctionResponse
                    if (data.message) {
                        console.log(data.message);

                        let content = data.message;
                        _this.detail = _this.courseName+"，" + content
                        let _content = content.split("，")
                        if(content.split("，").length>1){
                            _content = content.split("，")
                        }else{
                            _content = content.split(",")
                        }
                        _this.data = []
                        let data2 = []
                        _content.unshift(_this.courseName)
                        for (var a = 0; a < _content.length; a++) {
                            let _data = await _this.aiGet2(_content[a])
                            data2[a] = _data
                        }
                        _this.data = _.flatMap(_.zip(...data2), (pair) => pair.filter(value => value !== undefined))
                        // _this.data = _this.data.sort(
                        //     function (a, b) {
                        //         return b.play - a.play;
                        //     }
                        // );
                        _this.againEva2();
                    }else {
                        _this.$message.error("哎呀，请求太多了，服务器忙不过来了，请自行搜索关键词")
                        _this.loading = false
                    }
                    // _this.loading = false

                })
                .catch((error) => {
                    console.log(error);
                    _this.$message.error("哎呀，请求太多了，服务器忙不过来了，请自行搜索关键词")
                    _this.loading = false
                });
        },
        againEva2() {
            let _this = this
            _this.loading = true
            let message = `ATTENTION: Use '##' to SPLIT SECTIONS, not '#'.Output format carefully referenced "Format example".
针对以下视频数组内容，删除其中不适合k12年级的学生在教室里看到的条目，返回以下视频数组不符合的视频的id，视频数组：${JSON.stringify(_this.data)}

# Format example
[{id:""},{id:""}]
`
            let parm = {
              model: 'gpt-4o-2024-08-06',
              temperature: 0,
              max_tokens: 4096,
              top_p: 1,
              frequency_penalty: 0,
              presence_penalty: 0,
              messages: [{
                content: message.replaceAll('\n', " ").replaceAll('*', ""),
                role: 'user'
              }],
              uid: uuidv4(),
              stream: false,
              mind_map_question: "",
            }
            _this.ajax
                .post("https://gpt4.cocorobo.cn/chat", parm)
                .then(async (response) => {
                    console.log(response);
                    let data = response.data.FunctionResponse
                    if (data.choices && data.choices.length && data.choices[0].message) {
                        console.log(data.choices[0].message.content);
                        let dArray = []
                        try {
                            dArray = JSON.parse(data.choices[0].message.content.replaceAll('```json','').replaceAll('```',''))
                        } catch (error) {
                            console.log("error_________________" + error);
                            try {
                                let regex = new RegExp("(?<=```json)([\\s\\S]*?)(?=```)");
                                let match = data.choices[0].message.content.match(regex);
                                dArray = JSON.parse(match[0]);
                            } catch (error) {
                                console.log("error_________________" + error);
                            }
                        }

                        let id = []
                        for(var i = 0; i < dArray.length; i++){
                            id.push(dArray[i].id)
                        }
                        _this.data = _this.data.filter(el => {
                            return id.indexOf(el.id) === -1
                        })
                        _this.$forceUpdate()
                    }
                    _this.loading = false
                })
                .catch((error) => {
                    console.log(error);
                    // _this.$message.error("哎呀，请求太多了，服务器忙不过来了，请自行搜索关键词")
                    _this.loading = false
                });
        },
    },
    mounted () {
        
    },
}
</script>

<style scoped>
@media screen and (max-width: 1080px) {
.video_box {
    width: calc(100% / 3 - 10px) !important;
  }
}
@media screen and (max-width: 760px) {
.video_box {
    width: calc(100% / 2 - 10px) !important;
  }
}
.dialog_diy>>>.el-dialog {
    height: auto;
    margin: 50px auto 0 !important;
}

.dialog_diy>>>.el-dialog__header {
    background: #454545 !important;
    padding: 15px 20px;
}

.dialog_diy>>>.el-dialog__body {
    height: calc(100% - 124px);
    box-sizing: border-box;
    padding: 0px;
}


.dialog_diy>>>.el-dialog__title {
    color: #fff;
}

.dialog_diy>>>.el-dialog__headerbtn {
    top: 19px;
}

.dialog_diy>>>.el-dialog__headerbtn .el-dialog__close {
    color: #fff;
}

.dialog_diy>>>.el-dialog__headerbtn .el-dialog__close:hover {
    color: #fff;
}


.dialog_diy>>>.el-dialog__body,
.dialog_diy>>>.el-dialog__footer {
    background: #fafafa;
}

.binfo_input {
    width: 100%;
    margin: 0;
    padding: 5px 7px;
    display: block;
    min-width: 0;
    outline: none;
    box-sizing: border-box;
    background: none;
    border: none;
    border-radius: 4px;
    background: #fff;
    font-size: 15px;
    resize: none;
    font-family: "Microsoft YaHei";
    min-height: 48px;
    /* border: 1px solid #3682fc00; */
    border: 1.5px solid #cad1dc;
}

.binfo_textarea {
    border: 1.5px solid #cad1dc;
    font-size: 15px;
    resize: none;
    /* background: #f6f6f6; */
    font-family: "Microsoft YaHei";
}

.binfo_input:focus-visible {
    border: 1.5px solid #3681fc !important;
}


.t_box {
    display: flex;
    margin-bottom: 15px;
}

.t_box>span:nth-child(1) {
    min-width: 80px;
    font-size: 16px;
    color: #000;
}

.inputC>>>.el-input__inner {
    padding: '0 35px 0 15px'
}

.search_img {
    width: 20px;
    height: 20px;
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
}

.search_img>img {
    width: 100%;
    height: 100%;
}


.Box {
    width: 100%;
    height: 500px;
    overflow: auto;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    flex-wrap: wrap;
    padding: 5px;
    box-sizing: border-box;
}

.video_box {
    width: calc(100% / 4 - 10px);
    /* overflow: hidden; */
    margin-right: 10px;
    display: flex;
    flex-direction: column;
    margin-bottom: 15px;
    cursor: pointer;
}

.video_box>img {
    height: 200px;
    object-fit: cover;
}

.video_box>.detail {
    color: #cecece;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3; /* 显示3行文本 */
    overflow: hidden;
    text-overflow: ellipsis; /* 超出部分显示点点点 */
    margin: 0 0 5px;
}

.video_box>.name {
    color: #000;
    margin: 5px 0;
    height: 32px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; /* 显示3行文本 */
    overflow: hidden;
    text-overflow: ellipsis; /* 超出部分显示点点点 */
}

.video_box>.author{
    margin: 0 0 5px;
    width: 100%;
    display: block;
    overflow: hidden;
    text-overflow: ellipsis; /* 超出部分显示点点点 */
    white-space: nowrap;
}

.video_box>.tag{
    display: flex;
    flex-wrap: nowrap;
    margin-top: auto;
    width: 100%;
}

.video_box>.tag>span{
    background: #eef3fb;
    color: #0061ff;
    padding: 5px 10px;
    border-radius: 15px;
    font-size: 0.9em;
    margin: 0 5px 5px 0;
    max-width: 100%;
    overflow: hidden;
    box-sizing: border-box;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
}

.btn {
    width: 100%;
    height: 35px;
    display: flex;
    align-items: center;
    /* margin-top: auto; */
}

.btn>span:hover {
    background: #4087f1;
}

.btn>span {
    width: 100%;
    height: 100%;
    background: #3681fc;
    color: #fff;
    border-radius: 5px;
    margin-top: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

.btn>span+span {
    margin-left: 10px;
}

.video_box2 {
    box-shadow: 0px 0px 4px 2px #d2d2d282;
    padding: 5px 10px 10px;
    box-sizing: border-box;
    border-radius: 5px;
}


.nav_box {
    display: flex;
    margin-bottom: 10px;
    align-content: center;
}

.nav_box .nav{
    padding: 8px 10px;
    color: #060e17;
    border-radius: 5px;
    cursor: pointer;
}

.nav_box .nav.active{
    background: #eef3fb;
    font-weight: bold;
    color: #0061ff;
}

.nav_box .nav + .nav{
    margin-left: 20px;
}

.no_data{
    height: 500px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 500px;
}
</style>