<template>
    <div style="position: relative;">
        <el-dialog title="交互视频设置" :visible.sync="dialogVisibleVideo" :append-to-body="true" width="95%"
            :before-close="handleClose" class="dialog_diy">
            <div v-if="dialogVisibleVideo">
                <div class="btnBox">
                    <el-button type="primary" size="default" @click="addImg($event)" v-if="!this.json.video">
                        添加视频
                        <input type="file" accept="video/mp4, video/quicktime, video/x-msvideo" style="display: none"
                            @change="addVideo($event)" />
                    </el-button>
                    <el-button type="primary" size="default" @click="reset" v-else>重置</el-button>

                </div>
                <div class="videoBox">
                    <video-player class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true"
                        :options="playerO" v-if="this.json.video"></video-player>
                    <div class="content" v-else>请上传视频</div>
                </div>
                <div class="settingBox" v-if="this.json.video">
                    <div class="settingBtn">
                        <span class="title">交互设置</span>
                        <el-button type="primary" size="small" @click="addSetting">添加</el-button>
                    </div>
                    <div class="settingContent">
                        <div class="setting_b" v-for="(item, index) in json.setting" :key="index">
                            <div class="time_box">
                                <span>触发时间：</span>
                                <el-input-number v-model="item.time" :controls="false" :min="1" placeholder="视频第几秒"
                                    @change="changeTime(item.time, index)" style="width: 100px;"></el-input-number><span style="margin-left: 5px;">秒</span>
                            </div>
                            <div class="setting_fool">
                                <span>工具设置：</span>
                                <el-button type="primary" size="mini" @click="setting(index)">{{ item.tool.tool ? "已设置" :
                                    "插入工具" }}</el-button><el-button type="text" size="mini" @click="deleteSetting(index)" style="color:#818181">删除</el-button>
                            </div>
                            <!-- <div>
                                <el-button type="primary" size="mini" @click="deleteSetting(index)">删除</el-button>
                            </div> -->
                        </div>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="close">取 消</el-button>
                <el-button type="primary" @click="addV">确定</el-button>
            </span>
        </el-dialog>
        <choiceDialog :dialogVisibleChoice.sync="dialogVisibleChoice" :json="settingJson" @add="addSettingJson"
            v-if="dialogVisibleVideo"></choiceDialog>
        <div v-if="proVisible" class="mask">
            <div class="progressBox">
                <div class="lbox">
                    <img src="../../../assets/loading.gif" />上传中，请稍后
                </div>
                <div style="margin-bottom: 10px">
                    <span>{{ isFinishSize }}M</span> / <span>{{ isAllSize }}M</span>
                </div>
                <el-progress :text-inside="true" :stroke-width="20" :percentage="progress" style="width: 80%"></el-progress>
            </div>
        </div>
    </div>
</template>

<script>
import choiceDialog from '../choice/index.vue'
export default {
    props: {
        dialogVisibleVideo: {
            type: Boolean,
            default: false
        },
        videoJson: {
            type: Object
        }
    },
    components: {
        choiceDialog,
    },
    data() {
        return {
            json: {},
            playerOptions: {
                playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
                autoplay: false, //如果true,浏览器准备好时开始回放。
                muted: false, // 默认情况下将会消除任何音频。
                loop: false, // 导致视频一结束就重新开始。
                preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
                language: "zh-CN",
                aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
                fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
                sources: [
                    {
                        type: "video/mp4", //这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目   || "video/ogg"|| "video/webm"
                        src: "", //url地址require("../../assets/media/aaa.mp4")
                    },
                ],
                // poster: require("../../assets/tu31.png"), //你的封面地址
                // poster: dataRes.imgUrl, //你的封面地址
                notSupportedMessage: "此视频暂无法播放，请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
                controlBar: {
                    timeDivider: true, //当前时间和持续时间的分隔符
                    durationDisplay: true, //显示持续时间
                    remainingTimeDisplay: false, //是否显示剩余时间功能
                    fullscreenToggle: true, //全屏按钮
                },
            },
            playerO: {},
            videoTime: 0,
            settingIndex: 0,
            settingJson: {},
            dialogVisibleChoice: false,
            proVisible: false,
            isFinishSize: 0,
            isAllSize: 0,
            progress: 0,
        }
    },
    watch: {
        dialogVisibleVideo(newValue, oldValue) {
            this.json = JSON.parse(JSON.stringify(this.videoJson));
            if (this.json.video) {
                this.playerO = JSON.parse(JSON.stringify(this.playerOptions));
                this.playerO.sources[0].src = this.json.video
                this.$nextTick(() => {
                    setTimeout(() => {
                        this.videoTime = parseInt(this.$refs['videoPlayer'].player.cache_.duration)
                    }, 500)
                })
            }
        }
    },
    methods: {
        handleClose(done) {
            this.close()
            done()
        },
        close() {
            this.$emit("update:dialogVisibleVideo", false)
        },
        addV() {
            if (!this.json.video) {
                this.$message.error("请上传视频")
                return;
            }
            if (!this.json.setting.length) {
                this.$message.error("请添加至少一个交互")
                return;
            }
            let settingType = 1
            let settingToolType = 1
            let settingTypeArray = []
            for (var i = 0; i < this.json.setting.length; i++) {
                if (settingTypeArray.indexOf(this.json.setting[i].time) == -1) {
                    settingTypeArray.push(this.json.setting[i].time)
                } else {
                    settingType = 2
                    break
                }
                if (!this.json.setting[i].tool.tool) {
                    settingToolType = 2
                }
            }
            if (settingType == 2) {
                this.$message.error("不能设置一样的触发时间")
                return;
            }
            if (settingToolType == 2) {
                this.$message.error("请对交互设置工具")
                return;
            }
            this.$emit('add', this.json)
        },
        addSettingJson(tool, json) {
            this.json.setting[this.settingIndex].tool.tool = tool
            this.json.setting[this.settingIndex].tool.toolJson = json
            this.dialogVisibleChoice = false
        },
        setting(index) {
            this.settingIndex = index
            let testJson = {}
            if (this.json.setting[index].tool.tool) {
                testJson = JSON.parse(JSON.stringify(this.json.setting[index].tool.toolJson))
            } else {
                testJson = {
                    testCount: 1,
                    testTitle: "",
                    testJson: [
                        {
                            teststitle: "",
                            testItem: 1,
                            checkList: [],
                            timuList: [],
                            answer: "",
                            type: "1",
                        },
                    ],
                };
            }

            this.settingJson = testJson
            this.dialogVisibleChoice = true
        },
        changeTime(time, index) {
            if (time > this.videoTime) {
                this.$message.error("设置时间不能大于视频播放时长")
                this.$nextTick(() => {
                    this.json.setting[index].time = 1
                    this.$forceUpdate();
                })
            }
        },
        addSetting() {
            this.json.setting.push({
                time: "",
                tool: {
                    tool: "",
                    toolJson: {}
                }
            })
        },
        deleteSetting(index) {
            this
                .$confirm("确定删除么?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                .then(() => {
                    this.json.setting.splice(index, 1)
                })
                .catch(() => {
                    return;
                });
        },
        reset() {
            this
                .$confirm("确定重置么?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                .then(() => {
                    this.json = {
                        video: "",
                        setting: []
                    }
                })
                .catch(() => {
                    return;
                });
        },
        addImg(e) {
            var el = e.currentTarget;
            el.getElementsByTagName("input")[0].click();
            e.target.value = "";
        },
        addVideo(event) {

            var file = event.target.files[0];
            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;
            _this.progress = 0;
            _this.proVisible = true;
            _this.isFinishSize = 0;
            _this.isAllSize = (file.size / 1024 / 1024).toFixed(2);
            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) + '%');
                        _this.progress = parseInt((evt.loaded / evt.total) * 100);
                        _this.isFinishSize = (evt.loaded / 1024 / 1024).toFixed(2);
                        _this.$forceUpdate();
                    })
                    .send(function (err, data) {
                        _this.progress = 100;
                        _this.isFinishSize = _this.isAllSize;
                        _this.$forceUpdate();
                        setTimeout(() => {
                            _this.proVisible = false;
                            _this.$forceUpdate();
                        }, 500);
                        if (err) {
                            _this.$message.error("上传失败");
                        } else {
                            _this.json.video = data.Location;
                            _this.playerO = JSON.parse(JSON.stringify(_this.playerOptions));
                            _this.playerO.sources[0].src = data.Location
                            _this.$nextTick(() => {
                                setTimeout(() => {
                                    console.log(_this.$refs['videoPlayer']);
                                    _this.videoTime = parseInt(_this.$refs['videoPlayer'].player.cache_.duration)
                                }, 500)
                            })
                            _this.$forceUpdate();
                        }
                    });
            }
        }
    },
    mounted() {
        this.json = JSON.parse(JSON.stringify(this.videoJson));
        if (this.json.video) {
            this.playerO = JSON.parse(JSON.stringify(this.playerOptions));
            this.playerO.sources[0].src = this.json.video
            this.$nextTick(() => {
                setTimeout(() => {
                    this.videoTime = parseInt(this.$refs['videoPlayer'].player.cache_.duration)
                }, 500)
            })
        }
    },
}
</script>

<style scoped>
.dialog_diy>>>.el-dialog__header {
    background: #3c3c3c !important;
    padding: 15px 20px;
}

.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;
}

.videoBox {
    width: 100%;
    height: 600px;
    background: #fff;
    margin-top: 20px;
    position: relative;
}
.btnBox{
    display:flex;
    justify-content: flex-end;
}
.videoBox>.content {
    /* position: absolute; */
    line-height: 600px;
    text-align: center;
    font-size: 18px;
    user-select: none;
}

.videoBox .video-player {
    height: 100%;
    width: auto;
}

.videoBox>>>.vjs-fluid {
    padding: 0 !important;
    height: 100%;
}

.settingBox {
    margin-top: 20px;
}

.settingBtn {
    display: flex;
    align-items: center;
}

.settingBtn>.title {
    font-size: 22px;
    margin-right: 10px;
    color: #222;
}

.settingContent {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    margin-top: 20px;
}

.setting_b {
    margin: 0 60px 20px 0;
}

.setting_b div+div {
    margin: 10px 0 0 0;
}

.time_box {}

.setting_fool {}

.settingBox>>>.el-input-number.is-without-controls .el-input__inner {
    text-align: left;
}

.mask {
    background-color: rgb(0 0 0 / 30%);
    position: fixed;
    /* position: absolute; */
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 99999;
    display: flex;
    align-items: center;
    justify-content: center;
}

.progressBox {
    width: 300px;
    height: 150px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 0 6px 1px #bfbfbf;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: relative;
    color: #6c6c6c;
}

.progressBox>>>.el-progress-bar__outer {
    background-color: #d1dfff !important;
}

.progressBox .lbox {
    height: 50px;
    font-size: 19px;
    display: flex;
    align-items: center;
    color: #747474;
}

.progressBox .lbox img {
    width: 40px;
    margin-right: 20px;
}
</style>