<template>
    <div>
        <el-dialog title="AI生成PPT" :visible.sync="dialogVisibleAiCreate2" :append-to-body="true" width="700px" :before-close="handleClose" class="dialog_diy">
            <div style="height: 500px; padding: 15px" v-loading="loading" element-loading-text="小可正在努力生成中，请稍等...">
                <div class="c_pub_button_confirm stopBtn" v-if="loading && stopPpt" @click="cancelAjax()">停止</div>

                <!-- <div class="t_box">
                    <span>选择：</span>
                    <el-radio-group v-model="radio" @change="changeRadio">
                        <el-radio :label="0">PPT</el-radio>
                        <el-radio :label="1">教案</el-radio>
                        <el-radio :label="2">视频</el-radio>
                    </el-radio-group>
                </div> -->

                <div class="t_box" v-if="steps == 1" style="height: 100%">
                    <textarea style="height: 100%; width: calc(100% - 260px)" rows="10" class="binfo_input binfo_textarea" cols placeholder="请生成大纲" v-model="outline"></textarea>
                    <div class="template_box">
                        <span class="title">选择模板</span>
                        <div class="template_list">
                            <div class="template_item" :class="{ active: index == templateIndex }" v-for="(item, index) in templateList" :key="index" @click="changeTemplate(index)">
                                <img :src="item.img" alt="" />
                            </div>
                        </div>
                    </div>
                </div>

                <div style="height: 100%" v-else>
                    <wOffice v-if="url" :url="url"></wOffice>
                </div>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="aiGet()" type="primary" :disabled="loading || tloading">重新生成大纲</el-button>
                <el-button @click="aiGetPPt()" type="primary" :disabled="loading || tloading">{{ url ? "重新生成PPT" : "生成PPT" }}</el-button>
                <el-button @click="steps = 1" type="primary" v-if="steps == 2">上一步</el-button>
                <el-button @click="steps = 2" type="primary" v-else-if="steps == 1 && url">下一步</el-button>
                <el-button @click="confirm" type="primary">确 定</el-button>
                <el-button @click="closeT" type="primary">收 起</el-button>
                <el-button @click="closeAiPpt">关 闭</el-button>
            </span>
        </el-dialog>
        <div v-if="tanDialog" @click="dialogVisibleAiCreate2 = true" class="tanDialog">
            <span>任务{{ lineCount + 1 }}的生成ppt </span><button class="c_pub_button_confirm">打开</button>
        </div>
    </div>
</template>

<script>
import Pptxgen from "pptxgenjs";
import wOffice from "../components/wOffice.vue";
import { v4 as uuidv4 } from "uuid";
var OpenCC = require("opencc-js");

let converter2 = OpenCC.Converter({
    from: 'cn',
    to: 'hk'
})

export default {
    components: {
        wOffice,
    },
    props: {
        dialogVisibleAiCreate: {
            type: Boolean,
            default: false,
        },
        courseName: {
            type: String,
            default: "",
        },
        infoData: {
            type: Array,
            default: "",
        },
        courseTypeId: {
            type: Array,
            default: "",
        },
        CourseTypeJson: {
            type: Object,
            default: () => ({}),
        },
        courseState: {
            type: Number,
        },
        lineCount: {
            type: Number,
        },
        unitJson: {
            type: Array,
        },
        languageSetting: {
            type: Number,
            default: 0,
        }
    },
    // 根据用户给你的参考资料
    data() {
        return {
            dialogVisibleAiCreate2: false,
            tanDialog: false,
            userid: this.$route.query.userid,
            radio: 0,
            aiJson: {
                ppt: `## 任务
请生成关于${this.courseName}，为教师生成这节课的教学ppt，页数在20页左右。PPT的内容主要是讲解该课程中所有可能涉及到的知识点。

## 工作流
1. 从用户提供的参考资料中提取10个最重要的知识点（知识点水平限制在小学和初中），并输出。
2. 针对10个知识点中的每个，你使用1~3页ppt详细的对知识点进行讲解。你的讲解词应该在100token左右
3. 讲解完所有知识点后，再根据知识点出5道单选题（放在5页ppt中）

## 限制
- 你不能输出错误的知识，如果你实在不清楚，输出“对不起，我不确定”
- 你不能输出违反伦理的内容`,
                word: "",
                video: "",
            },
            aiUrl: {
                ppt: "",
                word: "",
                video: "",
            },
            detail: "",
            loading: false,
            tloading: false,
            tcancelSource: null,
            stopPpt: null,
            url: "",
            uJson: {},
            outline: "",
            steps: 1,
            // templateList: [
            //     // { img: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/model1-11719468995661.png', img2: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/model1-21719469026755.png',color:'17094F' },
            //     // { img: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/model2-11719469051869.png', img2: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/model2-21719469040181.png',color:'052B37' },
            //     // { img: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/model3-11719469071576.png', img2: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/model3-21719469092087.png',color:'1D5869' },
            //     // { img: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/model4-11719469106190.png', img2: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/model-4-21719469125318.png',color:'372213' },
            //     // { img: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/model5-11719295908696.png', img2: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/model5-21719295930345.png',color:'674D40' },
            //     { img: require('../../../assets/icon/ppt/model1-1.png'), img2: require('../../../assets/icon/ppt/model1-2.png'),color:'17094F' },
            //     { img: require('../../../assets/icon/ppt/model2-1.png'), img2: require('../../../assets/icon/ppt/model2-2.png'),color:'052B37' },
            //     { img: require('../../../assets/icon/ppt/model3-1.png'), img2: require('../../../assets/icon/ppt/model3-2.png'),color:'1D5869' },
            //     { img: require('../../../assets/icon/ppt/model4-1.png'), img2: require('../../../assets/icon/ppt/model4-2.png'),color:'372213' },
            //     { img: require('../../../assets/icon/ppt/model5-1.png'), img2: require('../../../assets/icon/ppt/model5-2.png'),color:'674D40' },
            // ],
            templateList: [{
                    img: require('../../../assets/icon/ppt/model6-1.png'),
                    img1: {
                        img: require('../../../assets/icon/ppt/model6-1-2.png'),
                        setting: {
                            x: "35%",
                            y: 2.3,
                            w: "60%",
                            bold: true,
                            color: 'EA7A93',
                            fontSize: 38,
                            fontFace: '黑体',
                            align: "center",
                        }
                    },
                    img2: [{
                            img: require('../../../assets/icon/ppt/model6-2.png'),
                            title: {
                                x: "5%", // 横坐标
                                y: 1.1,
                                w: "90%",
                                color: '4F73DA',
                                bold: true,
                                fontSize: 35, // 字号
                                fontFace: '黑体',
                                align: "center",
                            },
                            subTitle: {
                                x: "5%", // 横坐标
                                y: 1.8,
                                w: "90%",
                                color: "333333",
                                fontSize: 20, // 字号
                                fontFace: '黑体',
                                align: "center",
                            },
                            content: {
                                x: "20%", // 横坐标
                                y: 3.2,
                                w: "60%",
                                color: "333333",
                                fontSize: 18, // 字号
                                fontFace: '黑体',
                                align: "left",
                            }
                        }, //内容页1
                        {
                            img: require('../../../assets/icon/ppt/model6-2.png'),
                            title: {
                                x: "2.5%", // 横坐标
                                y: 2.3,
                                w: "30%",
                                color: 'ffffff',
                                bold: true,
                                fontSize: 35, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            subTitle: {
                                x: "2.5%", // 横坐标
                                y: 3.1,
                                w: "30%",
                                color: "ffffff",
                                fontSize: 20, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            content: {
                                x: "45%", // 横坐标
                                y: 2.8,
                                w: "45%",
                                color: "333333",
                                fontSize: 18, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            square: {
                                x: 0,
                                y: 0,
                                w: "35%",
                                h: "100%",
                                fill: { color: "4F73DA" }
                            },
                            square2: {
                                x: "35%",
                                y: 0,
                                w: "2.5%",
                                h: "100%",
                                fill: { color: "C2CFEF" }
                            }
                        }, //内容页2
                        {
                            img: require('../../../assets/icon/ppt/model6-2.png'),
                            title: {
                                x: "5%", // 横坐标
                                y: 1,
                                w: "60%",
                                color: '4F73DA',
                                bold: true,
                                fontSize: 35, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            subTitle: {
                                x: "5%", // 横坐标
                                y: 1.7,
                                w: "60%",
                                color: "333333",
                                fontSize: 20, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            content: {
                                x: "5%", // 横坐标
                                y: 2.5,
                                w: "60%",
                                color: "333333",
                                fontSize: 18, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            image: {
                                x: "70%",
                                y: "22%",
                                w: "30%",
                                h: "56%",
                                sizing: "contain",
                                path: require('../../../assets/icon/ppt/model6-3.png')
                            },
                        }, //内容页3
                        {
                            img: require('../../../assets/icon/ppt/model6-2.png'),
                            title: {
                                x: "10%", // 横坐标
                                y: "4%",
                                h: 0.75,
                                w: "80%",
                                color: 'ffffff',
                                fill: { color: "4F73DA" },
                                bold: true,
                                fontSize: 35, // 字号
                                fontFace: '黑体',
                                align: "center",
                            },
                            subTitle: {
                                x: "10%", // 横坐标
                                y: 1.5,
                                w: "80%",
                                color: "333333",
                                fontSize: 20, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            content: {
                                x: "10%", // 横坐标
                                y: 2.3,
                                w: "80%",
                                color: "333333",
                                fontSize: 18, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            image: {
                                x: "2.5%",
                                y: "10%",
                                w: "95%",
                                h: "80%",
                                sizing: "contain",
                                path: require('../../../assets/icon/ppt/model6-4.png')
                            },
                        }, //内容页4
                        {
                            img: require('../../../assets/icon/ppt/model6-2.png'),
                            title: {
                                x: 0, // 横坐标
                                y: "30%",
                                w: "35%",
                                h: "40%",
                                color: 'ffffff',
                                bold: true,
                                fontSize: 30, // 字号
                                fontFace: '黑体',
                                align: "right",
                                fill: { color: "4F73DA" },
                                margin: 10,
                            },
                            subTitle: {
                                x: "37.5%", // 横坐标
                                y: 1,
                                w: "53%",
                                color: "333333",
                                fontSize: 20, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            content: {
                                x: "37.5%", // 横坐标
                                y: 2,
                                w: "53%",
                                color: "333333",
                                fontSize: 18, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            square: {
                                x: "5%",
                                y: "10%",
                                w: "90%",
                                h: "80%",
                                fill: { color: "ffffff" },
                                line: {
                                    width: '2',
                                    color: "3B4564"
                                }
                            },
                        }, //内容页5
                        {
                            img: require('../../../assets/icon/ppt/model6-2.png'),
                            title: {
                                x: "17%", // 横坐标
                                y: "20%",
                                h: 0.75,
                                w: "66%",
                                color: 'ffffff',
                                fill: { color: "4F73DA" },
                                bold: true,
                                fontSize: 35, // 字号
                                fontFace: '黑体',
                                align: "center",
                            },
                            subTitle: {
                                x: "5%", // 横坐标
                                y: 3,
                                w: "90%",
                                color: "333333",
                                fontSize: 20, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            content: {
                                x: "5%", // 横坐标
                                y: 3.8,
                                w: "90%",
                                color: "333333",
                                fontSize: 18, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            image: {
                                x: 0,
                                y: 0,
                                w: "100%",
                                h: "45%",
                                sizing: "contain",
                                path: require('../../../assets/icon/ppt/model6-6.png')
                            },
                        }, //内容页6
                        {
                            img: require('../../../assets/icon/ppt/model6-7-1.png'),
                            title: {
                                x: "45%", // 横坐标
                                y: 1.3,
                                w: "50%",
                                color: '4F73DA',
                                bold: true,
                                fontSize: 35, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            subTitle: {
                                x: "45%", // 横坐标
                                y: 2,
                                w: "50%",
                                color: "333333",
                                fontSize: 20, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            content: {
                                x: "45%", // 横坐标
                                y: 3.2,
                                w: "50%",
                                color: "333333",
                                fontSize: 18, // 字号
                                fontFace: '黑体',
                                align: "left",
                            },
                            image: {
                                x: "20%",
                                y: 0,
                                w: "80%",
                                h: "100%",
                                sizing: "contain",
                                path: require('../../../assets/icon/ppt/model6-7-2.png')
                            },
                        }, //内容页7
                    ],
                    imgEnd: {
                        img: require('../../../assets/icon/ppt/model6-1-2.png'),
                        setting: {
                            x: "35%",
                            y: 2.3,
                            w: "60%",
                            color: 'EA7A93',
                            fontSize: 38,
                            fontFace: '黑体',
                            align: "center",
                        }
                    },
                },
                {
                    img: require('../../../assets/icon/ppt/model1-1.png'),
                    img1: {
                        img: require('../../../assets/icon/ppt/model1-1.png'),
                        setting: {
                            x: "5%",
                            y: 3,
                            w: "90%",
                            color: '17094F',
                            fontSize: 38,
                            fontFace: '黑体',
                            align: "center",
                        }
                    },
                    img2: [{
                        img: require('../../../assets/icon/ppt/model1-2.png'),
                        title: {
                            x: "5%", // 横坐标
                            y: 1.1,
                            w: "90%",
                            color: '17094F',
                            bold: true,
                            fontSize: 35, // 字号
                            fontFace: '黑体',
                            align: "center",
                        },
                        subTitle: {
                            x: "5%", // 横坐标
                            y: 1.8,
                            w: "90%",
                            color: "222222",
                            fontSize: 20, // 字号
                            fontFace: '黑体',
                            align: "center",
                        },
                        content: {
                            x: "20%", // 横坐标
                            y: 3.2,
                            w: "60%",
                            color: "444444",
                            fontSize: 18, // 字号
                            fontFace: '黑体',
                            align: "left",
                        }
                    }],
                    imgEnd: {
                        img: require('../../../assets/icon/ppt/model1-1.png'),
                        setting: {
                            x: "5%",
                            y: 3,
                            w: "90%",
                            color: '17094F',
                            fontSize: 38,
                            fontFace: '黑体',
                            align: "center",
                        }
                    }
                },
                {
                    img: require('../../../assets/icon/ppt/model2-1.png'),
                    img1: {
                        img: require('../../../assets/icon/ppt/model2-1.png'),
                        setting: {
                            x: "5%",
                            y: 3,
                            w: "90%",
                            color: '052B37',
                            fontSize: 38,
                            fontFace: '黑体',
                            align: "center",
                        }
                    },
                    img2: [{
                        img: require('../../../assets/icon/ppt/model2-2.png'),
                        title: {
                            x: "5%", // 横坐标
                            y: 1.1,
                            w: "90%",
                            color: '052B37',
                            bold: true,
                            fontSize: 35, // 字号
                            fontFace: '黑体',
                            align: "center",
                        },
                        subTitle: {
                            x: "5%", // 横坐标
                            y: 1.8,
                            w: "90%",
                            color: "222222",
                            fontSize: 20, // 字号
                            fontFace: '黑体',
                            align: "center",
                        },
                        content: {
                            x: "20%", // 横坐标
                            y: 3.2,
                            w: "60%",
                            color: "444444",
                            fontSize: 18, // 字号
                            fontFace: '黑体',
                            align: "left",
                        }
                    }],
                    imgEnd: {
                        img: require('../../../assets/icon/ppt/model2-1.png'),
                        setting: {
                            x: "5%",
                            y: 3,
                            w: "90%",
                            color: '052B37',
                            fontSize: 38,
                            fontFace: '黑体',
                            align: "center",
                        }
                    }
                },
                {
                    img: require('../../../assets/icon/ppt/model3-1.png'),
                    img1: {
                        img: require('../../../assets/icon/ppt/model3-1.png'),
                        setting: {
                            x: "5%",
                            y: 3,
                            w: "90%",
                            color: '1D5869',
                            fontSize: 38,
                            fontFace: '黑体',
                            align: "center",
                        }
                    },
                    img2: [{
                        img: require('../../../assets/icon/ppt/model3-2.png'),
                        title: {
                            x: "5%", // 横坐标
                            y: 1.1,
                            w: "90%",
                            color: '1D5869',
                            bold: true,
                            fontSize: 35, // 字号
                            fontFace: '黑体',
                            align: "center",
                        },
                        subTitle: {
                            x: "5%", // 横坐标
                            y: 1.8,
                            w: "90%",
                            color: "222222",
                            fontSize: 20, // 字号
                            fontFace: '黑体',
                            align: "center",
                        },
                        content: {
                            x: "20%", // 横坐标
                            y: 3.2,
                            w: "60%",
                            color: "444444",
                            fontSize: 18, // 字号
                            fontFace: '黑体',
                            align: "left",
                        }
                    }],
                    imgEnd: {
                        img: require('../../../assets/icon/ppt/model3-1.png'),
                        setting: {
                            x: "5%",
                            y: 3,
                            w: "90%",
                            color: '1D5869',
                            fontSize: 38,
                            fontFace: '黑体',
                            align: "center",
                        }
                    }
                },
                {
                    img: require('../../../assets/icon/ppt/model4-1.png'),
                    img1: {
                        img: require('../../../assets/icon/ppt/model4-1.png'),
                        setting: {
                            x: "5%",
                            y: 3,
                            w: "90%",
                            color: '372213',
                            fontSize: 38,
                            fontFace: '黑体',
                            align: "center",
                        }
                    },
                    img2: [{
                        img: require('../../../assets/icon/ppt/model4-2.png'),
                        title: {
                            x: "5%", // 横坐标
                            y: 1.1,
                            w: "90%",
                            color: '372213',
                            bold: true,
                            fontSize: 35, // 字号
                            fontFace: '黑体',
                            align: "center",
                        },
                        subTitle: {
                            x: "5%", // 横坐标
                            y: 1.8,
                            w: "90%",
                            color: "222222",
                            fontSize: 20, // 字号
                            fontFace: '黑体',
                            align: "center",
                        },
                        content: {
                            x: "20%", // 横坐标
                            y: 3.2,
                            w: "60%",
                            color: "444444",
                            fontSize: 18, // 字号
                            fontFace: '黑体',
                            align: "left",
                        }
                    }],
                    imgEnd: {
                        img: require('../../../assets/icon/ppt/model4-1.png'),
                        setting: {
                            x: "5%",
                            y: 3,
                            w: "90%",
                            color: '372213',
                            fontSize: 38,
                            fontFace: '黑体',
                            align: "center",
                        }
                    },
                    color: '372213'
                },
                {
                    img: require('../../../assets/icon/ppt/model5-1.png'),
                    img1: {
                        img: require('../../../assets/icon/ppt/model5-1.png'),
                        setting: {
                            x: "5%",
                            y: 3,
                            w: "90%",
                            color: '674D40',
                            fontSize: 38,
                            fontFace: '黑体',
                            align: "center",
                        }
                    },
                    img2: [{
                        img: require('../../../assets/icon/ppt/model5-2.png'),
                        title: {
                            x: "5%", // 横坐标
                            y: 1.1,
                            w: "90%",
                            color: '674D40',
                            bold: true,
                            fontSize: 35, // 字号
                            fontFace: '黑体',
                            align: "center",
                        },
                        subTitle: {
                            x: "5%", // 横坐标
                            y: 1.8,
                            w: "90%",
                            color: "222222",
                            fontSize: 20, // 字号
                            fontFace: '黑体',
                            align: "center",
                        },
                        content: {
                            x: "20%", // 横坐标
                            y: 3.2,
                            w: "60%",
                            color: "444444",
                            fontSize: 18, // 字号
                            fontFace: '黑体',
                            align: "left",
                        }
                    }],
                    imgEnd: {
                        img: require('../../../assets/icon/ppt/model5-1.png'),
                        setting: {
                            x: "5%",
                            y: 3,
                            w: "90%",
                            color: '674D40',
                            fontSize: 38,
                            fontFace: '黑体',
                            align: "center",
                        }
                    },
                },
            ],
            templateIndex: 0,
        };
    },
    watch: {
        dialogVisibleAiCreate(newValue, oldValue) {
            if (newValue) {
                this.dialogVisibleAiCreate2 = true
                this.tanDialog = false
                this.loading = false;
                this.aiGet();
                // this.templateIndex = 5
                // let array = [
                // {
                //     "page": 1,
                //     "title": "引入阶段",
                //     "task": "课程背景",
                //     "points": "同学们，让我们一起了解一下这门有趣的熊猫课程吧！今天，我们将探索熊猫的生活环境，并尝试去理解这些环境是如何影响熊猫的生存的。"
                // },
                // {
                //     "page": 2,
                //     "title": "引入阶段",
                //     "task": "整体目标和任务要求",
                //     "points": "这门课程的主要目标是让大家了解熊猫生活的环境以及生存所需的关键因素。我们将完成一个任务，具体要求是观察、记录、绘制和制作模型哦！"
                // },
                // {
                //     "page": 3,
                //     "title": "引入阶段",
                //     "task": "驱动性问题",
                //     "points": "大家思考一下这样一个问题：‘熊猫的生活环境对它们的生存有何重要影响?’ 我们接下去的活动将帮助大家找到答案。"
                // },
                // {
                //     "page": 4,
                //     "title": "引入阶段",
                //     "task": "观察与记录技巧",
                //     "points": "今天我们会运用图片和视频，来帮助大家观察熊猫栖息地和它们所吃的竹子等特征。细心观察，并将所见的特征记录下来是非常重要的技能哦！"
                // },
                // {
                //     "page": 5,
                //     "title": "探究阶段",
                //     "task": "绘图工具和材料",
                //     "points": "现在我们分发绘图工具和材料，来学习基本的绘图和建模技巧吧！熟练掌握这些工具会帮助我们更好地记录和展示我们的观察结果。"
                // },
                // {
                //     "page": 6,
                //     "title": "探究阶段",
                //     "task": "观察和记录特征",
                //     "points": "让我们好好观察一下身边的常见物体，把它们的特征记录下来。这个过程会训练你们的观察力和手眼协调能力。"
                // },
                // {
                //     "page": 7,
                //     "title": "探究阶段",
                //     "task": "转换二维图像",
                //     "points": "接下来，我们要把记录的三维物体转化为二维图像。这个步骤非常有趣，大家可以尽情发挥自己的绘画天赋哦！"
                // },
                // {
                //     "page": 8,
                //     "title": "探究阶段",
                //     "task": "三维模型制作",
                //     "points": "现在我们提供一些简单的材料，比如纸张和纸板，示范一下如何制作三维模型。记住，比例和结构是模型制作的关键！"
                // },
                // {
                //     "page": 9,
                //     "title": "评估与反馈阶段",
                //     "task": "评估和检查",
                //     "points": "大家完成了任务后，我们来检查和评估你们的二维图像和三维模型。确保它们的结构合理、比例协调。"
                // },
                // {
                //     "page": 10,
                //     "title": "评估与反馈阶段",
                //     "task": "提出改进建议",
                //     "points": "针对你们完成的作品，我们会提出一些改进建议。大家也可以相互评价，分享制作经验，这样可以互相学习哦！"
                // },
                // {
                //     "page": 11,
                //     "title": "评估与反馈阶段",
                //     "task": "任务总结",
                //     "points": "最后，我们要总结这次任务的执行情况，并表扬表现特别突出的同学。希望大家都能有所收获，并继续努力！"
                // },
                // {
                //     "page": 12,
                //     "title": "练习",
                //     "task": "练习1：二维图像绘制",
                //     "points": "选择一件日常物品（如书本、杯子），观察其特征，尝试通过手绘将其转换为二维图像。示例：通过绘制书本的正面、侧面和顶面图，展示其主要特征和比例关系。"
                // },
                // {
                //     "page": 13,
                //     "title": "练习",
                //     "task": "练习2：三维模型制作",
                //     "points": "使用纸张和纸板制作简单的模型，比如一个基本的房子或盒子。关注其结构和比例哦！ 示例：通过折叠和粘贴纸张，制作一个四面体，确保各个面的比例协调，结构稳定。"
                // }
                // ]
                // this.createPpt(array);

            }
        },
    },
    methods: {
        getLang() {
            let lang = ''
            if (this.languageSetting == 0) {
                lang = 'Chinese.'
            } else if (this.languageSetting == 1) {
                lang = 'Traditional Chinese.'
            } else if (this.languageSetting == 2) {
                lang = 'English.'
            }
            return lang
        },
        cancelAjax(type) {
            if(type != 2){
                this.$message.success("已经成功停止")
            }
            this.stopPpt && this.stopPpt.cancel('Request canceled by the user.');
            this.stopPpt = null;
            this.tcancelSource && this.tcancelSource.close();
            this.tcancelSource = null;
            this.loading = false
        },
        handleClose(done) {
            this.close();
            done();
        },
        close() {
            // this.$emit("update:dialogVisibleAiCreate", false);
            this.dialogVisibleAiCreate2 = false
        },
        closeAiPpt(){
            this.cancelAjax(2)
            this.dialogVisibleAiCreate2 = false
            this.$emit("closeAiPpt", this.lineCount);
        },
        closeT(){
            this.tanDialog = true
            this.close()
        },
        confirm() {
            if (this.url) {
                this.$emit("createAiPpt", this.uJson, this.lineCount);
            } else {
                this.$message.error("请点击“生成PPT”按钮");
            }
        },
        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;
            }
        },
        createFileid(url) {
            let _this = this;
            return new Promise((resolve, reject) => {
                try {
                    _this.ajax
                        .put("https://gpt4.cocorobo.cn/upload_file_knowledge", {
                            url: url,
                        })
                        .then((res) => {
                            let _data = res.data.FunctionResponse;
                            if (_data.result && _data.result.id) {
                                resolve(_data.result.id);
                            }
                        })
                        .catch(function(error) {
                            resolve("");
                        });
                } catch (e) {
                    resolve();
                }
            });
        },
        async aiGetPPt() {
            if (this.loading || this.tloading) {
                this.$message.error("正在生成中，请稍后");
                return;
            }
            let _this = this;

            let fileid = [];
            if (_this.infoData.length) {
                for (var i = 0; i < _this.infoData.length; i++) {
                    if (_this.infoData[i].fileid) {
                        fileid.push(_this.infoData[i].fileid);
                    } else {
                        let _fileid = await _this.createFileid(_this.infoData[i].url);
                        if (_fileid) {
                            _this.infoData[i].fileid = _fileid;
                            _this.$forceUpdate();
                            fileid.push(_fileid);
                        }
                    }
                }
            }
            console.log("fileid=========", fileid);

            let mclass = [];
            if (_this.courseTypeId.length) {
                for (var i = 0; i < _this.courseTypeId.length; i++) {
                    let _sid = _this.courseTypeId[i];
                    for (
                        var j = 0; j <
                        _this.CourseTypeJson["34628934-d02f-11ec-8c78-005056b86db5"].length; j++
                    ) {
                        if (
                            _sid ==
                            _this.CourseTypeJson["34628934-d02f-11ec-8c78-005056b86db5"][j].id
                        ) {
                            mclass.push(
                                _this.CourseTypeJson["34628934-d02f-11ec-8c78-005056b86db5"][j]
                                .name
                            );
                        }
                    }
                }
            }
            let message = "";
            if (!_this.outline) {
                _this.$message.error("请先生成大纲内容");
                return;
            }
            message = `NOTICE
Role: 你是ppt内容设计大师，能力是从用户提供的文件资料中提取最重要的学科概念作为ppt参考内容，最后根据Context要求的流程要求输出ppt内容。
Output: Provide your output in json format.
Language: ${this.getLang()}
ATTENTION: Use '##' to SPLIT SECTIONS, not '#'. Output format carefully referenced "Format example".
Instruction: Based on the context, follow "Format example", write content.

# Context 
## 任务
你会收到一节课的教学ppt大纲<大纲内容>，你需要细化大纲每个部分（除了测试题部分），生成详细每一页ppt的内容参考#每一页输出格式。 

# 目标
生成教师可用直接拿来上课的ppt，ppt中用亲切的口吻告诉学生，他们该做什么，以及介绍相关的知识点（知识点需要详细的说明）。必要时使用bullet point。最终生成12页左右的ppt。

# 每一页输出格式
- 页数：序列数字
- 标题：环节
- 子标题：步骤或者知识点或测试题序号
- 内容：用亲切的口吻告诉学生本步骤应做什么？或者是用亲切的口吻向学生介绍知识点，多条时可使用bullet point；或者是给学生测试题。

## 大纲内容
${_this.outline.replaceAll('#', '').replaceAll('*', '').replaceAll('-', '').replaceAll('\n', '')}

# Format example
[{"page": "页码（数字）","title": "学科概念（请从给你的大纲中摘取）（标题）","task": "知识点（请从给你的大纲中摘取）（子标题）","points": "内容：用亲切的口吻告诉学生本步骤应做什么？或者是用亲切的口吻向学生介绍知识点，多条时可使用bullet point；或者是给学生测试题。"}]`;
            this.url = "";
            this.uJson = {};

            _this.stopPpt = _this.ajax.setCancelSource();
            let parm = {
                assistant_id: "6063369f-289a-11ef-8bf4-12e77c4cb76b",
                message: [{ type: "text", text: this.languageSetting == 1 ? converter2(message.replaceAll('\n', " ")) : message.replaceAll('\n', " ") }],
                session_name: uuidv4(),
                userId: this.userid,
                file_ids: fileid.length ? [...fileid] : "",
                model: 'gpt-4o-2024-08-06',
            };
            _this.loading = true;
            this.ajax
                .post("https://gpt4.cocorobo.cn/ai_agent_park_chat", parm, _this.stopPpt)
                .then((response) => {
                    console.log(response);
                    let data = response.data.FunctionResponse;
                    if (data.message) {
                        console.log(data.message);
                        try {
                            let _data = JSON.parse(
                                data.message.replaceAll("```json", "").replaceAll("```", "")
                            );
                            _this.createPpt(_data);
                            _this.steps = 2;
                        } catch (e) {
                            console.log("error_________________" + e);
                            try {
                                let regex = new RegExp("(?<=```json)([\\s\\S]*?)(?=```)");
                                let match = data.message.match(regex);
                                let _data2 = JSON.parse(match[0]);
                                _this.createPpt(_data2);
                                _this.steps = 2;

                            } catch (error) {
                                _this.$message.error("生成失败，正在重新生成");
                                _this.loading = false;
                                _this.stopPpt = null
                                _this.aiGetPPt();
                            }
                        }
                    }
                })
                .catch((error) => {
                    _this.loading = false;
                    _this.stopPpt = null
                    console.log(error);
                });
        },
        async aiGet() {
            if (this.loading || this.tloading) {
                this.$message.error("正在生成中，请稍后");
                return;
            }
            let _this = this;

            let fileid = [];
            if (_this.infoData.length) {
                for (var i = 0; i < _this.infoData.length; i++) {
                    if (_this.infoData[i].fileid) {
                        fileid.push(_this.infoData[i].fileid);
                    } else {
                        let _fileid = await _this.createFileid(_this.infoData[i].url);
                        if (_fileid) {
                            _this.infoData[i].fileid = _fileid;
                            _this.$forceUpdate();
                            fileid.push(_fileid);
                        }
                    }
                }
            }
            console.log("fileid=========", fileid);

            let mclass = [];
            if (_this.courseTypeId.length) {
                for (var i = 0; i < _this.courseTypeId.length; i++) {
                    let _sid = _this.courseTypeId[i];
                    for (
                        var j = 0; j <
                        _this.CourseTypeJson["34628934-d02f-11ec-8c78-005056b86db5"].length; j++
                    ) {
                        if (
                            _sid ==
                            _this.CourseTypeJson["34628934-d02f-11ec-8c78-005056b86db5"][j].id
                        ) {
                            mclass.push(
                                _this.CourseTypeJson["34628934-d02f-11ec-8c78-005056b86db5"][j]
                                .name
                            );
                        }
                    }
                }
            }
            let message = "";
            if (this.courseState == 4) {
                message = `NOTICE Language: ${this.getLang()}

# 任务
请根据参考资料，生成关于${this.courseName}，为教师生成这节课的教学ppt的大纲，大纲的主要内容课程知识点的讲解与相关练习和测试。你的输出应该符合#输出格式

${mclass.length ? "#参考资料\n面向年级：" + mclass.join(",") : ""}

# 输出格式
- 标题：
--步骤
--知识点

# 限制
- 你不能输出错误的知识，如果你实在不清楚，输出“对不起，我不确定”
- 你不能输出违反伦理的内容`;
            } else if (this.courseState == 5) {
                message = `NOTICE Language: ${this.getLang()}

# 任务
请根据<任务教案>，为教师生成本的教学ppt的大纲，大纲包含各环节的步骤，学科知识点。

# 参考资料
任务教案：${_this.unitJson[0].chapterInfo[0].taskJson[_this.lineCount].taskDetail3.replaceAll('#', '').replaceAll('*', '').replaceAll('-', '').replaceAll('\n', '')}
${mclass.length ? "面向年级：" + mclass.join(",") : ""}

# 输出格式
- 标题：
--步骤
--知识点

# 限制
- 你不能输出错误的知识，如果你实在不清楚，输出“对不起，我不确定”
- 你不能输出违反伦理的内容
`

            }
            this.url = "";
            this.uJson = {};
            let _uid = uuidv4()
            _this.stopPpt = _this.ajax.setCancelSource();
            let parm = {
                assistant_id: "f8e1ebb2-2e0d-11ef-8bf4-12e77c4cb76b",
                message: [{ type: "text", text: this.languageSetting == 1 ? converter2(message.replaceAll('\n', " ")) : message.replaceAll('\n', " ") }],
                session_name: _uid,
                userId: _this.userid,
                uid: _uid,
                file_ids: fileid.length ? [...fileid] : "",
                model: 'gpt-4o-2024-08-06',
            };
            _this.loading = true;
            _this.tloading = true;
            _this.ajax
                .post("https://gpt4.cocorobo.cn/ai_agent_park_chat_new", parm, _this.stopPpt)
                .then((response) => {
                    let data = response.data.FunctionResponse;
                    console.log(response);
                    if (converter2(response.data.FunctionResponse.result) == converter2("发送成功")) {} else {
                        _this.$message.warning(response.data.FunctionResponse.result);
                    }
                    // if (data.message) {
                    //     console.log(data.message);

                    //     _this.outline = data.message;
                    //     _this.steps = 1;
                    //     _this.stopPpt = null
                    //     _this.loading = false;
                    // }
                })
                .catch((error) => {
                    _this.loading = false;
                    _this.tloading = false;
                    _this.stopPpt = null
                    console.log(error);
                });
            await _this.aiGetgetAiContent(_uid)
        },
        aiGetgetAiContent(_uid) {
            try {
                this.tcancelSource = new EventSource(`https://gpt4.cocorobo.cn/question/${_uid}`); //http://gpt4.cocorobo.cn:8011/stream/     https://gpt4.cocorobo.cn/stream/
            } catch (error) {
                console.log('EventSource error:', error);
                // this.tcancelSource && this.$message.error("哎呀，请求太多了，服务器忙不过来了，请稍等再重试")
                this.loading = false
                this.tLoading = false
                this.tcancelSource = null
                return;
            }
            let _allText = "";
            let _mdText = "";
            let _iindex = 0
            this.tcancelSource.onmessage = _e => {
                let _eData = JSON.parse(_e.data).content;
                if (_eData.replace("'", "").replace("'", "") == "[DONE]") {
                    //对话已经完成
                    _mdText = _mdText.replace("_", "").replace(/【[^】]*source[^】]*】/g, '').replaceAll("<br>", "");
                    this.tcancelSource && this.tcancelSource.close();
                    this.tcancelSource = null;
                    this.outline = _mdText;
                    this.loading = false
                    this.tloading = false
                    this.stopPpt = null
                    return;
                } else {
                    _iindex++
                    //对话还在继续
                    let _text = "";
                    _text = _eData.replaceAll("'", "");
                    if (_allText == "") {
                        _allText = _text.replace(/^\n+/, ""); //去掉回复消息中偶尔开头就存在的连续换行符
                    } else {
                        _allText += _text;
                    }
                    _mdText = _allText + "_";
                    _mdText = _mdText.replace(/\\n/g, "\n");
                    _mdText = _mdText.replace(/\\/g, "");
                    if (_allText.split("```").length % 2 == 0) _mdText += "\n```\n";
                    //转化返回的回复流数据
                    if (_iindex == 10) {
                        this.outline = _mdText;
                        _iindex = 0
                    }
                    if(this.loading){
                        this.loading = false
                        this.steps = 1;
                    }
                    // 处理流数据
                }
                // this.$forceUpdate();
            };
            let _this = this
            this.tcancelSource.onerror = function(event) {
                // 处理错误，可以尝试重新连接
                console.log('EventSource error:', event);
                // _this.tcancelSource && _this.$message.error("哎呀，请求太多了，服务器忙不过来了，请稍等再重试")
                _this.loading = false
                _this.tloading = false
                _this.stopPpt = null
                _this.tcancelSource && _this.tcancelSource.close();
                _this.tcancelSource = null;
            };
        },
        generateRandomNumber(min, max) {
            // min 是随机数范围的最小值，max 是随机数范围的最大值
            return Math.floor(Math.random() * (max - min + 1)) + min;
        },
        createPpt(arr) {
            let array = arr
            // 1. 创建PPT
            const pres = new Pptxgen();
            const _slideTou = pres.addSlide();
            _slideTou.background = { path: this.templateList[this.templateIndex].img1.img }
            let title = ''
            if (this.courseState == 4) {
                title = this.courseName
            } else if (this.courseState == 5) {
                title = this.unitJson[0].chapterInfo[0].taskJson[this.lineCount].task
            }
            _slideTou.addText(title, this.templateList[this.templateIndex].img1.setting);
            for (var i = 0; i < array.length; i++) {
                // 2. 创建一个PPT页面，每调用一次 pres.addSlide() 都可以生成一张新的页面
                // 建议把每个页面的构造抽成一个个函数，然后通过函数调用生成新页面，代码不会很乱
                const _slide = pres.addSlide();
                const randomNum = this.generateRandomNumber(0, (this.templateList[this.templateIndex].img2.length - 1))
                let pContent = this.templateList[this.templateIndex].img2[randomNum]
                _slide.background = { path: pContent.img }

                // 3. 调用addTetx()，在PPT页面中插入文字“Hello World from PptxGenJS...”
                // 括号里面是对文字的配置，文字横坐标x为1.5，纵坐标y为1.5，字体颜色 363636……
                // 关于坐标长度与px的转换 x 1 = 127~128px 左右
                const page = i + 1 > 10 ? i + 1 : "0" + (i + 1);

                if (pContent.square) {
                    _slide.addText("", pContent.square);
                    _slide.addText("", pContent.square2);
                }
                if (pContent.image) {
                    _slide.addImage(pContent.image);
                }
                const tempResult1 = page + " " + array[i].title;
                _slide.addText(tempResult1, pContent.title);
                const tempResult2 = array[i].task;
                _slide.addText(tempResult2, pContent.subTitle);
                let tempResult3 = '';
                if (typeof array[i].points == 'object') {
                    if (Array.isArray(array[i].points)) {
                        for (var k = 0; k < array[i].points.length; k++) {
                            array[i].points[k] = '· ' + array[i].points[k]
                        }
                        tempResult3 = array[i].points.join('\n')
                    } else {
                        tempResult3 = JSON.stringify(array[i].points)
                    }
                } else {
                    tempResult3 = array[i].points
                }
                _slide.addText(tempResult3, pContent.content);
            }
            const _slideWei = pres.addSlide();
            _slideWei.background = { path: this.templateList[this.templateIndex].imgEnd.img }
            _slideWei.addText("谢谢观看，下课!", this.templateList[this.templateIndex].imgEnd.setting);
            // 获取PPTX文件的ArrayBuffer

            // 保存为 Blob 并处理
            pres.write("blob").then((blob) => {
                // 现在你有了一个 Blob 对象
                console.log(blob);

                const file = new File([blob], title + ".pptx", {
                    type: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
                });
                console.log(pres);
                this.beforeUpload(file);
            });
        },
        beforeUpload(event) {
            var file = event;
            var credentials = {
                accessKeyId: "AKIATLPEDU37QV5CHLMH",
                secretAccessKey: "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",
            }; //秘钥形式的登录上传
            window.AWS.config.update(credentials);
            window.AWS.config.region = "cn-northwest-1"; //设置区域

            var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
            var _this = this;

            if (file) {
                var params = {
                    Key: file.name.split(".")[0] +
                        new Date().getTime() +
                        "." +
                        file.name.split(".")[file.name.split(".").length - 1],
                    ContentType: file.type,
                    Body: file,
                    "Access-Control-Allow-Credentials": "*",
                    ACL: "public-read",
                }; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
                var options = {
                    partSize: 2048 * 1024 * 1024,
                    queueSize: 2,
                    leavePartsOnError: true,
                };
                bucket
                    .upload(params, options)
                    .on("httpUploadProgress", function(evt) {
                        //这里可以写进度条
                        // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
                    })
                    .send(function(err, data) {
                        _this.loading = false;
                        if (err) {
                            _this.$message.error("上传失败");
                        } else {
                            _this.url = data.Location;
                            _this.uJson = {
                                name: file.name,
                                url: data.Location,
                                type: 3,
                            };
                            if(_this.tanDialog){
                                _this.confirm()
                            }
                            console.log(data.Location);
                        }
                    });
            }
        },
        changeTemplate(index) {
            this.templateIndex = index;
        }
    },
};
</script>

<style scoped>
.dialog_diy>>>.el-dialog {
    height: auto;
    margin: 15vh 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_textarea:focus-visible {
    border: 1.5px solid #3681fc !important;
}

.binfo_textarea::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 6px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 6px;
}

/*定义滚动条轨道 内阴影+圆角*/

.binfo_textarea::-webkit-scrollbar {
    border-radius: 10px;
    background-color: #eee;
}

/*定义滑块 内阴影+圆角*/

.binfo_textarea::-webkit-scrollbar-thumb {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
    background-color: rgba(0, 0, 0, 0.1);
}

.t_box {
    display: flex;
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
}

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

.template_box {
    width: 250px;
}

.template_box>.title {
    font-size: 18px;
    margin-bottom: 10px;
    display: block;
}

.template_list {
    overflow: auto;
    width: 100%;
    height: calc(100% - 31px);
}

.template_item {
    cursor: pointer;
    width: 100%;
    height: 165px;
    overflow: hidden;
    border-radius: 5px;
    box-sizing: border-box;
    border: 5px solid #e5e5e5ee;
}

.template_item+.template_item {
    margin-top: 10px;
}

.template_item.active {
    border: 5px solid #0061ff;
}

.template_item>img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.stopBtn {
    z-index: 999999;
    position: absolute;
    left: 50%;
    top: calc(50% + 70px);
    transform: translateX(-50%);
}

.tanDialog{
    cursor: pointer;
    display: flex;
    align-items: center;
}

.tanDialog > span{
    margin-right: 5px;
}

.tanDialog > .c_pub_button_confirm{
    padding: 0 10px;
    height: 26px;
    min-width: unset;
}
</style>