<template>
    <div class="aliUpload-container">
        <div class="upload">
            <div>
                <el-upload
                        :before-upload="beforeUpload"
                        :http-request="fileChange"
                        :on-remove="filesRemove"
                        :show-file-list="true"
                        action="aaa"
                        class="upload-box"
                        ref="aliUpload"
                >
                    <el-button class="response-middle-btn" type="primary">选择视频文件</el-button>
                </el-upload>
                <el-tooltip content="注：音、视频课件上传大小限制1.5G以内，麻烦请留意上传音、视频文件大小！！！"  placement="top" popper-class="c-aliUpload-tooltip"><i class="aliUpload-note-word"></i></el-tooltip>
                <label class="status">上传状态: <span>{{statusText}}</span></label>
            </div>
            <div class="upload-type">
                <!--上传方式一, 使用 UploadAuth 上传:-->
                <el-progress :percentage="authProgress" class="aly-progressbar"></el-progress>
                <button :disabled="uploadDisabled" @click.prevent="authUpload" class="start-btn"></button>
                <button :disabled="resumeDisabled" @click.prevent="resumeUpload" class="upload-btn"></button>
                <button :disabled="pauseDisabled" @click.prevent="pauseUpload" class="pause-btn"></button>
             <!--   <span class="progress">上传进度: <i id="auth-progress">{{authProgress}}</i> %</span>-->

            </div>
        </div>
    </div>
</template>
<script>
    // import axios from 'axios'
    import * as videoPolicy from '@/api/peixun/videoPolicy';
    import { mapGetters }   from 'vuex';

    export default {
        name:     'AliUploadVideo',
        data() {
            return {
                timeout:        null,
                partSize:       null,
                parallel:       null,
                retryCount:     null,
                retryDuration:  null,
                region:         'cn-shanghai',
                userId:         '1815477461878711',
                file:           null,
                authProgress:   0,
                uploadDisabled: true,
                resumeDisabled: true,
                pauseDisabled:  true,
                uploader:       null,
                statusText:     '',
                policy:         {
                    fileName: '',
                    title:    '',
                },
            };
        },
        computed: {
            ...mapGetters([
                              'getTenantCode',
                          ]),
        },
        methods:  {
            /*initAliUpload(truck, userData) {

            },*/
            clear() {
                if (this.$refs.aliUpload.uploadFiles.length > 0) {
                    this.$refs.aliUpload.uploadFiles.splice(0, 1);
                }
                this.authProgress = 0;
                this.statusText = '';
                this.pauseDisabled = true;
                this.resumeDisabled = true;
            },
            fileChange(truck) {
                if (!truck.file) {
                    this.$message.warning('请先选择需要上传的文件!');
                    return;
                }

                var userData = '{"Vod":{}}';

                if (this.$refs.aliUpload.uploadFiles.length > 1) {
                    this.$refs.aliUpload.uploadFiles.splice(0, 1);
                    // this.initAliUpload(truck, userData);
                }

                // console.log(truck);
                var time = new Date().getTime();
                this.policy.fileName = this.getTenantCode + time + '.' + truck.file.name.split('.').pop();
                this.$emit('fileSuffix', truck.file.name.split('.').pop());
                this.policy.title = this.getTenantCode + time;

                if (this.uploader) {
                    this.uploader.stopUpload();
                    this.authProgress = 0;
                    this.statusText = '';
                }
                this.uploader = this.createUploader();
                console.log(userData);
                this.uploader.addFile(truck.file, null, null, null, userData);
                this.authUpload();
            },
            authUpload() {
                // 然后调用 startUpload 方法, 开始上传
                if (this.uploader !== null) {
                    this.uploader.startUpload();
                }
            },
            // 暂停上传
            pauseUpload() {
                if (this.uploader !== null) {
                    this.uploader.stopUpload();
                }
            },
            // 恢复上传
            resumeUpload() {
                if (this.uploader !== null) {
                    this.uploader.startUpload();
                }
            },
            createUploader(type) {
                let self = this;
                let uploader = new AliyunUpload.Vod({
                                                        timeout:              self.timeout || 60000,
                                                        partSize:             self.partSize || 1048576,
                                                        parallel:             self.parallel || 5,
                                                        retryCount:           self.retryCount || 3,
                                                        retryDuration:        self.retryDuration || 2,
                                                        region:               self.region,
                                                        userId:               self.userId,
                                                        // 添加文件成功
                                                        addFileSuccess:       (uploadInfo) => {
                                                            /*this.uploadDisabled = false;
                                                            this.pauseDisabled = true;
                                                            this.resumeDisabled = false;*/
                                                            self.statusText = '添加文件成功, 等待上传...';
                                                            console.log('addFileSuccess: ' + uploadInfo.file.name);
                                                        },
                                                        // 开始上传
                                                        onUploadstarted:      (uploadInfo) => {
                                                            // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
                                                            // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress
                                                            // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
                                                            // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
                                                            // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
                                                            // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
                                                            if (!uploadInfo.videoId) {
                                                                // let createUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateUploadVideo?Title=testvod1&FileName=aa.mp4&BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&VideoId=5bfcc7864fc14b96972842172207c9e6'
                                                                let createUrl = '';
                                                                videoPolicy.videoPolicy({
                                                                                            'fileName': this.policy.fileName,
                                                                                            'title':    this.policy.title,
                                                                                        }).then(res => {
                                                                    if (res.code == 0) {
                                                                        let uploadAddress = res.data.uploadAddress;
                                                                        let uploadAuth = res.data.uploadAuth;
                                                                        let videoId = res.data.videoId;
                                                                        uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId);
                                                                        self.statusText = '文件开始上传...';
                                                                        console.log('onUploadStarted1:' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object);

                                                                        this.uploadDisabled = true;
                                                                        this.pauseDisabled = false;
                                                                        this.resumeDisabled = true;

                                                                    } else {
                                                                        console.error('videoPolicy code error!');
                                                                    }
                                                                });

                                                            } else {
                                                                // 如果videoId有值，根据videoId刷新上传凭证
                                                                // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
                                                                // let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
                                                                videoPolicy.videoRefresh({
                                                                                             'videoId': uploadInfo.videoId,
                                                                                         }).then(res => {
                                                                    if (res.code == 0) {
                                                                        let uploadAuth = res.data.uploadAuth;
                                                                        let uploadAddress = res.data.uploadAddress;
                                                                        let videoId = res.data.videoId;
                                                                        console.log(uploadInfo, uploadAuth, uploadAddress, videoId);
                                                                        uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId);
                                                                        self.statusText = '刷新凭证 文件开始上传...';
                                                                        console.log('onUploadStarted2:' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object);

                                                                        this.uploadDisabled = true;
                                                                        this.pauseDisabled = false;
                                                                        this.resumeDisabled = true;

                                                                    } else {
                                                                        console.error('videoRefresh code error!');
                                                                    }
                                                                });
                                                            }
                                                        },
                                                        // 文件上传成功
                                                        onUploadSucceed:      (uploadInfo) => {
                                                            console.log(uploadInfo);
                                                            console.log('onUploadSucceed: ' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object);
                                                            self.statusText = '文件上传成功!';
                                                            this.$emit('fileState', {
                                                                state:     9,
                                                                videoId:   uploadInfo.videoId,
                                                                videoInfo: uploadInfo,
                                                            });

                                                            this.uploadDisabled = true;
                                                            this.pauseDisabled = true;
                                                            this.resumeDisabled = true;
                                                        },
                                                        // 文件上传失败
                                                        onUploadFailed:       (uploadInfo, code, message) => {
                                                            console.log('onUploadFailed: file:' + uploadInfo.file.name + ',code:' + code + ', message:' + message);
                                                            self.statusText = '文件上传失败!';
                                                            this.$emit('fileState', {
                                                                state:   3,
                                                                videoId: uploadInfo.videoId,
                                                            });

                                                            this.uploadDisabled = true;
                                                            this.pauseDisabled = true;
                                                            this.resumeDisabled = false;
                                                        },
                                                        // 取消文件上传
                                                        onUploadCanceled:     (uploadInfo, code, message) => {
                                                            console.log('Canceled file: ' + uploadInfo.file.name + ', code: ' + code + ', message:' + message);
                                                            self.statusText = '文件已暂停上传';
                                                            this.$emit('fileState', {
                                                                state:   2,
                                                                videoId: uploadInfo.videoId,
                                                            });

                                                            this.uploadDisabled = true;
                                                            this.pauseDisabled = true;
                                                            this.resumeDisabled = false;

                                                        },
                                                        // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
                                                        onUploadProgress:     (uploadInfo, totalSize, progress) => {
                                                            console.log('onUploadProgress:file:' + uploadInfo.file.name + ', fileSize:' + totalSize + ', percent:' + Math.ceil(progress * 100) + '%');
                                                            let progressPercent = Math.ceil(progress * 100);
                                                            self.authProgress = progressPercent;
                                                            self.statusText = '文件上传中...';
                                                            this.$emit('fileState', {
                                                                state:   1,
                                                                videoId: uploadInfo.videoId,
                                                            });
                                                            this.uploadDisabled = true;
                                                            this.pauseDisabled = false;
                                                            this.resumeDisabled = true;
                                                        },
                                                        // 上传凭证超时
                                                        onUploadTokenExpired: (uploadInfo) => {
                                                            // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
                                                            // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
                                                            // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
                                                            // let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId

                                                            self.statusText = '文件超时...';
                                                            this.$emit('fileState', {
                                                                state:   5,
                                                                videoId: uploadInfo.videoId,
                                                            });
                                                            videoPolicy.videoRefresh({
                                                                                         'videoId': uploadInfo.videoId,
                                                                                     }).then(res => {
                                                                if (res.code == 0) {
                                                                    let uploadAuth = res.data.UploadAuth;
                                                                    let uploadAddress = res.data.UploadAddress;
                                                                    let videoId = res.data.VideoId;
                                                                    uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId);
                                                                    self.statusText = '刷新凭证 文件开始上传...';
                                                                    console.log('onUploadStarted3:' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object);
                                                                    this.uploadDisabled = true;
                                                                    this.pauseDisabled = true;
                                                                    this.resumeDisabled = false;
                                                                } else {
                                                                    console.error('videoRefresh code error!');
                                                                }
                                                            });
                                                        },
                                                        // 全部文件上传结束
                                                        onUploadEnd:          () => {
                                                            // console.log('onUploadEnd: uploaded all the files');
                                                            /*self.statusText = '全部文件上传完毕';
                                                            this.$emit('fileState', {
                                                                state:   10,
                                                            });
                                                            this.uploadDisabled = false;
                                                            this.pauseDisabled = false;
                                                            this.resumeDisabled = false;*/

                                                        },
                                                    });
                return uploader;
            },
            beforeUpload(file) {
                if (file.size > 1.5 * 1024 * 1024 * 1024) {
                    this.$message.warning('文件超过1.5G');
                    return false;
                }
                let url = URL.createObjectURL(file);
                var audioElement = new Audio(url);
                audioElement.addEventListener('loadedmetadata', () => {
                    let playTime = audioElement.duration; //playTime就是当前视频长度
                    console.log(playTime);
                    this.$emit('syncBaseInfo', audioElement);
                });
            },
            filesRemove() {
                console.log('filesRemove');
            }
        },
    };
</script>
