<template>
    <div id="app">
        <div class="main-header">
            <div style="float: left;">
                <span>当前编辑视频：</span>
                <el-button type="text" @click="handleClickSelectSyllabus">在库中选择视频</el-button>
            </div>
            <div style="float: right;">
                <el-button type="primary" @click="handleClickSave">保存</el-button>
            </div>
        </div>
        <div class="main-body">
            <div ref="refDubbingScrollList" class="dubbing-items">
                <el-card v-for="item, index in dubbingData.dubbingItems" :key="index" class="box-card">
                    <div style="position: relative;">
                        <span style="position: absolute;" class="item-index">{{ index + 1 }} <span style="font-size: medium; line-height: normal;">{{ currentSelectDubbingIndex==index ? '正在编辑' : '' }}</span></span>
                        <div style="text-align: right;">
                            <el-button size="mini" type="danger" @click="handleClickDelete(index)">删除</el-button>
                            <el-button size="mini" type="primary" @click="handleClickSetCurrent(index)">编辑</el-button>
                        </div>
                    </div>
                    <el-divider></el-divider>
                    <el-form label-width="50px">
                        <el-form-item label="原文">
                            <el-input type="text" v-model="item.orgText" />
                        </el-form-item>
                        <!-- <el-form-item label="译文">
                                <el-input type="text" v-model="item.transText"/>
                            </el-form-item> -->
                        <el-form-item label="开始">
                            <el-input type="text" v-model="item.timelineIn">
                                <template slot="append">（秒）</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="结束">
                            <el-input type="text" v-model="item.timelineOut">
                                <template slot="append">（秒）</template>
                            </el-input>
                        </el-form-item>
                    </el-form>
                </el-card>
                <el-card class="box-card">
                    <el-button type="primary" @click="handelClickAdd" style="width: 100%;">新建</el-button>
                </el-card>
            </div>
            <div class="video-panel">
                <div class="center-container">
                    <video v-if="!updateVideoSource" ref="refVideo" controls width="768px">
                        <source :src="videoUrl" type="video/mp4">
                        Your browser does not support the video tag.
                    </video>
                    <TimeRangeSelector v-model="timeRange" @change="handleRangeChange"></TimeRangeSelector>
                </div>
            </div>
            <el-collapse-transition>
                <div v-show="currentSelectDubbingIndex >= 0" class="button-group">
                    <el-button type="" size="medium" icon="el-icon-refresh" @click="handleClickPlayRange">播放区间</el-button>
                    <el-button v-show="!isPlaying" type="" size="medium" icon="el-icon-video-play" @click="handleClickPlay">播放</el-button>
                    <el-button v-show="isPlaying" type="" size="medium" icon="el-icon-video-pause" @click="handleClickPause">暂停</el-button>
                    <el-button type="" size="medium" @click="handelClickRre10s">向前1秒</el-button>
                    <el-button type="" size="medium" @click="handleClickSetStart">设置为起点</el-button>
                    <el-button type="" size="medium" @click="handleClickSetEnd">设置为结束点</el-button>
                </div>
            </el-collapse-transition>
        </div>

        <el-dialog title="选择内容" :visible.sync="dialogSelectShow" width="500px">
            <div class="el-main" style="height: 300px;">
                <el-tree :data="treeListData" :props="treeProps" @node-click="handleClickTreeNode" :lazy="true"
                    :load="handleLazyLoadTreeData"></el-tree>
            </div>
            <div slot="footer" class="dialog-footer">
                <span class="current-selected-text">当前选择：{{ currentSelectTreeNode ? currentSelectTreeNode.name : "" }} -
                    {{ currentSelectTreeNode ? currentSelectTreeNode.id : "" }}</span>
                <el-button @click="handleClickCancelSelect">取 消</el-button>
                <el-button type="primary" @click="handleClickConfirmSelect">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import TimeRangeSelector from './components/TimeRangeSelector.vue'
import { getSyllabusListById, getFirstCoursewareBySyllId, getPidPathName } from '@/api/syllabus'

export default {
    name: 'App',
    components: {
        TimeRangeSelector
    },
    data() {
        return {
            // 是否正在播放
            isPlaying: false,

            // 视频地址
            videoUrl: '',

            // 时间区间
            timeRange: {
                start: 0,
                end: 1
            },

            // 配音数据
            dubbingData: {
                backgroundAudio: {
                    url: "",
                    duration: 0,
                    size: 0
                },
                dubbingItems: []
            },


            // 选择内容对话框显示隐藏控制
            dialogSelectShow: false,

            // 树形列表数据
            treeListData: [],

            // 当前选择的节点信息
            currentSelectTreeNode: null,

            // 树形列表配置
            treeProps: {
                children: 'children',
                label: 'name',
                isLeaf: function (data, node) {
                    return data.has_courseware == "1";
                }
            },

            // 是否更新视频资源
            updateVideoSource: false,

            // 当前选择的配音秀索引
            currentSelectDubbingIndex: -1
        };
    },
    async mounted() {
        this.getData();
        // this.$setData([
        //     {
        //         "orgText": "Apple.",
        //         "transText": "",
        //         "timelineIn": "0.352728",
        //         "timelineOut": "2.349307"
        //     },
        //     {
        //         "orgText": "Green apple.",
        //         "transText": "",
        //         "timelineIn": "4.938305",
        //         "timelineOut": "7.2651"
        //     },
        //     {
        //         "orgText": "Red apple.",
        //         "transText": "",
        //         "timelineIn": "10.687003",
        //         "timelineOut": "13.054597"
        //     },
        //     {
        //         "orgText": "Juicy apple.",
        //         "transText": "",
        //         "timelineIn": "16.128933",
        //         "timelineOut": "20.358868"
        //     },
        //     {
        //         "orgText": "Gulp,gulp,hic!",
        //         "transText": "",
        //         "timelineIn": "20.674126",
        //         "timelineOut": "23.316044"
        //     },
        //     {
        //         "orgText": "BOTH:apples!",
        //         "transText": "",
        //         "timelineIn": "26.360674",
        //         "timelineOut": "29.569075"
        //     },
        //     {
        //         "orgText": "Shiny apple.",
        //         "transText": "",
        //         "timelineIn": "34.97507",
        //         "timelineOut": "37.929512"
        //     },
        //     {
        //         "orgText": "Crunchy apple.",
        //         "transText": "",
        //         "timelineIn": "41.66807",
        //         "timelineOut": "44.267387"
        //     },
        //     {
        //         "orgText": "Bobbing apple.",
        //         "transText": "",
        //         "timelineIn": "48.00274",
        //         "timelineOut": "50.683136"
        //     },
        //     {
        //         "orgText": "Way-hay!Apples!",
        //         "transText": "",
        //         "timelineIn": "53.787037",
        //         "timelineOut": "57.842"
        //     }
        // ])
    },
    methods: {
        async getData() {
            const dpeData = await this.$getDPEData();
            console.log("====dpeData====", dpeData)
            
            const res = await this.$getData();
            console.log("====getData====", res)
            if(!res) {
                // 默认数据
                this.dubbingData = {
                    backgroundAudio: {
                        url: "",
                        duration: 0,
                        size: 0
                    },
                    dubbingItems: []
                }
            } else {
                this.dubbingData = res
            }
        },

        handleRangeChange(event) {
            this.$refs.refVideo.currentTime = event.start * this.$refs.refVideo.duration;
            const sTime = this.timeRange.start * this.$refs.refVideo.duration;
            const eTime = this.timeRange.end * this.$refs.refVideo.duration;

            this.dubbingData.dubbingItems[this.currentSelectDubbingIndex].timelineIn = sTime;
            this.dubbingData.dubbingItems[this.currentSelectDubbingIndex].timelineOut = eTime;
        },

        // 点击区间播放
        handleClickPlayRange() {
            const sTime = this.timeRange.start * this.$refs.refVideo.duration;
            const eTime = this.timeRange.end * this.$refs.refVideo.duration;

            this.$refs.refVideo.currentTime = sTime;
            this.$refs.refVideo.play().then(() => {
                this.isPlaying = true;
                const checkTime = () => {
                    if (this.$refs.refVideo.currentTime >= eTime) {
                        this.$refs.refVideo.pause();
                        this.isPlaying = false;
                        this.$refs.refVideo.removeEventListener('timeupdate', checkTime);
                    }
                }
                this.$refs.refVideo.addEventListener('timeupdate', checkTime, false);
            })
                .catch(error => {
                    console.log(error);
                });

        },

        handleClickPlay() {
            this.$refs.refVideo.play();
            this.isPlaying = true;
        },

        handleClickPause() {
            this.$refs.refVideo.pause();
            this.isPlaying = false;
        },

        handelClickRre10s() {
            this.$refs.refVideo.currentTime -= 1;
        },

        handleClickSetStart() {
            this.timeRange.start = this.$refs.refVideo.currentTime / this.$refs.refVideo.duration;
            this.dubbingData.dubbingItems[this.currentSelectDubbingIndex].timelineIn = this.$refs.refVideo.currentTime;
            
        },

        handleClickSetEnd() {
            this.timeRange.end = this.$refs.refVideo.currentTime / this.$refs.refVideo.duration;
            this.dubbingData.dubbingItems[this.currentSelectDubbingIndex].timelineOut = this.$refs.refVideo.currentTime;
        },

        handleClickSetCurrent(index, play = false) {
            const timelineIn = this.dubbingData.dubbingItems[index].timelineIn / this.$refs.refVideo.duration;
            const timelineOut = this.dubbingData.dubbingItems[index].timelineOut / this.$refs.refVideo.duration;

            this.currentSelectDubbingIndex = index;

            this.timeRange = {
                start: timelineIn,
                end: timelineOut
            }

            play && this.handleClickPlayRange()
        },

        // 删除配音秀
        handleClickDelete(index) {
            this.$confirm("确定要删除吗？").then(res=>{
                this.dubbingData.dubbingItems.splice(index, 1)
            }).catch(_=>"")
        },

        // 添加配音
        handelClickAdd() {
            this.dubbingData.dubbingItems.push({
                orgText: '',
                transText: '',
                timelineIn: 0,
                timelineOut: 1
            })
            this.$nextTick(() => {
                this.$refs.refDubbingScrollList.scrollTop = this.$refs.refDubbingScrollList.scrollHeight;
            })
        },

        // 点击切换配音资源
        async handleClickSelectSyllabus() {
            this.dialogSelectShow = true;
            const resData = await getSyllabusListById();
            this.treeListData = resData.rows;
        },

        // 点击树形列表节点
        handleClickTreeNode(node) {
            if (node.has_courseware == "1") {
                this.currentSelectTreeNode = node;
            }
        },

        // 懒加载树形列表数据
        handleLazyLoadTreeData(node, resolve) {
            getSyllabusListById(node.data.id).then(data => {
                resolve(data.rows)
            })
        },

         // 取消选择
         handleClickCancelSelect() {
            this.dialogSelectShow = false;
            this.currentSelectTreeNode = null;
            this.treeListData = [];
        },

        // 确定选择节点
        async handleClickConfirmSelect() {
            // 获取视频课件信息
            const resData = await getFirstCoursewareBySyllId(this.currentSelectTreeNode.id);

            let jsonData = null;
            try {
                jsonData = JSON.parse(resData.data);
            } catch (error) {
                
            }

            // 获取视频地址
            this.videoUrl = jsonData ? jsonData.url : '';

            // 重新加载视频组件
            this.updateVideoSource = true;
            this.$nextTick(() => {
                this.updateVideoSource = false;
            })

            // 关闭对话框
            this.handleClickCancelSelect();
        },

        // 保存数据
        async handleClickSave() {
            this.$setData(this.dubbingData)
        }
    }
}
</script>

<style>
body,
html {
    margin: 0;
    padding: 0;
    height: 100%;
    overflow: hidden;
    background-color: #FFFFFF;
}

#app {}

.cascader-item {
    width: 150px;
}

.button-item {
    margin-left: 10px;
}

.current-selected-text {
    float: left;
    font-size: small;
}

.video-panel {
    margin-left: 320px;
}

.center-container {
    width: 768px;
    margin-left: 320px;
    padding: 20px 10px;
    margin: 0 auto;
}

.button-group {
    margin-left: 320px;
    text-align: center;
}

.dubbing-items {
    width: 300px;
    height: calc(100% - 90px);
    background-color: #f0f0f0;
    position: absolute;
    left: 0;
    overflow: auto;
    padding: 10px;
}

.box-card {
    margin-bottom: 10px;
}

::v-deep .el-card__body {
    padding: 0 !important;
}

.item-index {
    font-size: 20px;
    font-weight: bold;
    margin-right: 10px;
}

.main-header {
    height: 70px;
    line-height: 70px;
    position: fixed;
    z-index: 99;
    top: 0;
    background-color: #FFFFFF;
    width: calc(100% - 40px);
    border-bottom: 1px solid #dcdfe6;
    padding: 0 20px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
}

.main-body {
    margin-top: 70px;
    height: calc(100% - 70px);
    overflow: auto;
}
</style>
