<template>
    <div>
        <el-dialog
            :visible.sync="appDialogVisible"
            :append-to-body="true"
            width="100%"
            fullscreen
            :before-close="handleClose"
            :show-close="false"
            class="dialog_diyCopy "
            >
            <div style="width: 100%;height: 90%;overflow: auto;">
                <iframe
                    allow= "camera *; microphone *;display-capture;midi;encrypted-media;"
                    allowfullscreen
                    frameborder
                    border= "0"
                    scrolling = "no"
                    :src="urlData"
                    ref="appStore"
                    style="width: 100%;height: 99%;"
                ></iframe>
                    <!-- :class="[urlData.indexOf('story-telling') ? 'minH':'']" -->

            </div>
            
            
            <div style="display: flex;justify-content: flex-end;padding: 0 30px;box-sizing: border-box;">
                <el-button type="primary" style="margin-right: 20px;" size="medium" @click="handleClose">{{ lang.ssClose }}</el-button>
                <el-button type="primary" @click="uploadWork" size="medium">{{ lang.ssSubmitWork }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { myMixin } from "@/mixins/mixin.js"
    export default {
        mixins: [ myMixin ],
        props: ["sStudent","courseType","taskCount","toolindex"],
        data() {
            return {
                urlData:"",
                userId: '',
                appDialogVisible: false,
                id: this.$route.query.courseId,
                homeWorkLoading:false
            }
        },
        methods: {
            getData(val,uid){
                this.urlData = val
                this.userId = uid
                this.appDialogVisible = true
            },
            handleClose() {
                this.urlData = ''
                this.userId = ''
                if (document.fullscreenElement) {
                    this.exitFullScreen();
                } 
                this.appDialogVisible = false
            },
            exitFullScreen() {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.mozCancelFullScreen) { /* Firefox */
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) { /* Chrome, Safari and Opera */
                    document.webkitExitFullscreen();
                } else if (document.msExitFullscreen) { /* IE/Edge */
                    document.msExitFullscreen();
                }
            },
            async uploadWork(){
                // console.log('window.exposed_outputs',window.exposed_outputs);
                let _iframe = this.$refs.appStore;
                console.log('sStudent',this.userId);

                if (this.homeWorkLoading) return this.$message.info(this.lang.ssClickTooFast)
                this.homeWorkLoading = true
                // window.exposed_outputs
                // let Cow = _iframe.contentWindow.exposed_outputs

                const pptJsonStr = JSON.stringify(_iframe.contentWindow.exposed_outputs);
                const pptJsonFile = new File([pptJsonStr], "pptData.json", { type: "application/json" });
                // 你可以根据需要将pptJsonFile上传或保存

                let Cow = await this.uploadFile(pptJsonFile);
                // console.log(_url)
                // return
                
                let params = [
                    {
                        uid: this.userId,
                        cid: this.id,
                        stage: this.courseType,
                        task: this.taskCount,
                        tool: this.toolindex,
                        content: Cow,
                        type: 20,
                        atool:72
                    }
                ];
                this.ajax
                    .post(this.$store.state.api + "addCourseWorks3-2", params)
                    .then(res => {
                    this.$message({
                        message: this.lang.ssSubmitSuccess,
                        type: "success"
                    });
                        this.dialogVisibleSelectTeacher = false;
                        setTimeout(() => {
                            this.homeWorkLoading = false
                        }, 500);

                        this.addOp3('1', "", { courseid: this.id,tool:'AI应用',data:Cow,type: "course_tool_sub" }, "success")
                        // this.selectAnswer = {};
                        this.$emit('selectSWorks');
                        this.$emit('selectStudent');
                    })
                    .catch(err => {
                        this.addOp3('1', "", { courseid: this.id,tool:'AI应用',data:Cow,type: "course_tool_sub" }, err)
                        setTimeout(() => {
                            this.homeWorkLoading = false
                        }, 500);

                        this.$message.error(this.lang.ssSubmitFailed);
                        console.error(err);
                    });
            },
            //上传文件
            uploadFile(file) {
                return new Promise((resolve)=>{
                    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) {
                        if (err) {
                        // var a = _this.$refs.upload1.uploadFiles;
                        // a.splice(a.length - 1, a.length);
                        _this.$message.error(_this.lang.ssUploadPptDataFailed);
                        } else {
                        //上传成功处理
                        // _this.unitJson[_this.unitIndex].chapterInfo[0].fileList1.push({
                        //   name: file.name,
                        //   url: data.Location,
                        //   uid: file.uid
                        // });
                        // _this.imgChange();
                        // console.log(data.Location);
                        resolve(data.Location)
                        }
                    });
                }
                })
            },
        },  
    }
</script>

<style scoped>
.dialog_diyCopy >>> .el-dialog__header {
  display: none !important;
  /* position: relative; */
}
.dialog_diyCopy >>> .el-dialog__body {
  padding: 0 !important;
  height: 100% !important;
}
.minH{
    min-height: 800px;
}
</style>