<!--文件懒加载控件（集成了龙嘉协议获取图片的方式）-->
<template>
    <div class="lj-video-dl lj-picture_and_video">
        <video
            class="video-js vjs-big-play-centered vjs-fluid video-dl-item"
            playsinline 
            webkit-playsinline
            style="max-width: 100%;max-height: 100%;"
            @click="onPlayerPlay"
            @loadedmetadata="getDuration"
            :src="currentSrc"
            ref="video"
        >
            <!-- <source src="https://www.runoob.com/try/demo_source/mov_bbb.mp4" type="video/mp4"/> -->
            <!-- <source :src="currentSrc" type="video/mp4"/> -->
        </video>
        <slot name="bottom-nav" v-if="showfilename">
            <div class="bottom-nav">
                <div class="name text-ellipsis-one">
                    {{ fileName }}
                </div>
            </div>
        </slot>
        <div class="video-tag">
            <van-tag
                v-if="duration > 0"
                type="primary"
                class="tag-item"
            >
                {{ duration }}s
            </van-tag>
        </div>
        <div class="bottom-nav-status" v-if="downloadbtn && (downloading || dlSuccess != 0)" :class="{'show': downloadbtn && (downloading || dlSuccess != 0)}">
            <div class="download" :class="{'del-item': delbtn, 'dl-success': dlSuccess == 1, 'dl-fail': dlSuccess == 2}">
                <template v-if="downloading">
                    <van-loading class="video-loading" size="14" color="#fff">
                        <span class="bottom-nav-text">
                            保存中
                        </span>
                    </van-loading>
                </template>
                <template v-else-if="dlSuccess != 0">
                    <i v-if="dlSuccess == 1" class="iconfont icon-check"></i>
                    <i v-else class="iconfont icon-jinggao"></i>
                </template>
            </div>
        </div>
        <div v-if="downloadbtn || delbtn || error || loading" class="control-bar">
            <van-tag
                v-if="loading"
                class="tag-item"
                :class="{'loading': loading}"
                round
            >
                <van-loading color="#F2F2F7" size="14" />
            </van-tag>
            <van-tag
                v-else
                class="tag-item"
                :class="{'del-item': delbtn, 'download-item': downloadbtn, 'error-item': error && !delbtn, 'loading': downloading}"
                round
                @click.stop="handleBottomNav"
            >
                <template v-if="delbtn">
                    <i class="iconfont icon-close"></i>
                </template>
                <template v-else-if="error && !delbtn">
                    <i class="iconfont icon-ic_refresh"></i>
                </template>
                <template v-else-if="downloading">
                    <van-loading color="#8E8E93" size="14" />
                </template>
                <template v-else-if="downloadbtn">
                    <i class="iconfont icon-save1"></i>
                </template>
            </van-tag>
        </div>
    </div>
    
</template>

<script>
    export default {
        props: {
            // 龙嘉协议的文件md5值
            md5: {
                Type: String,
                default: ""
            },
            // 普通http路径
            src: {
                Type: String,
                default: ""
            },
            fileType: String,
            fileName: String,
            delbtn: { // 是否显示删除按钮
                type: Boolean,
                default: false
            },
            downloadbtn: {// 是否显示下载按钮
                type: Boolean,
                default: false
            },
            showfilename: {// 是否显示文件名
                type: Boolean,
                default: false
            },
        },
        data() {
            return {
                currentSrc: "",
                player: null,
                playTime:'',
                seekTime:'',
                current:'',
                videoPlayer: null,
                downloading: false,
                dlSuccess: 0, // 是否下载成功: 0，未操作，1：成功，2：失败
                duration: 0, // 视频时长
                loading: false,
                error: false,
            }
        },
        mounted() {
            this.initVideo();
            this.refreshVideo();
        },
        methods: {
            initVideo() {
                //原生初始化视频方法
                // let myVideo = this.$refs.video;
                // //ontimeupdate
                //   myVideo.ontimeupdate = function() {myFunction()};
                //   let _this = this;

                //   function myFunction(){
                //       let playTime = myVideo.currentTime
                //       console.log('myFunction playTime  :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(playTime));
                //       setTimeout(function () {
                //           localStorage.setItem("cacheTime",playTime)
                //       },500)
                //       let time = localStorage.getItem("cacheTime")
                //       // 当前播放位置发生变化时触发。
                //       if(playTime - Number(time) > 2){
                //           myVideo.currentTime = Number(time)
                //       }else{
                //       }
                //   };
                // 创建api
                this.videoPlayer = api.require('videoPlayer');
            },
            refreshVideo() {
                this.error = false;
                let self = this;
                if (this.src) {
                    this.currentSrc = this.src
                } else if (this.md5) {
                    $lj.getCacheDir(function (cacheDir) {
                        let path = cacheDir + "/" + self.md5 + "." + self.realFileType;
                        var fs = $lj.getFileHelperModule();
                        console.warn(path);
                        fs.exist({
                            path: path
                        }, function (ret, err) {
                            if (ret.exist) {
                                self.getBase64(path);
                            } else {
                                self.loading = true;
                                $lj.postLJRequest("GetCacheFile", {filemd5: self.md5}, function (ret) {
                                    var cacheDir = $lj.constant.cacheDir + "/";
                                    let newPath = cacheDir + "/" + self.md5 + "." + self.realFileType;
                                    if (ret.filedata !== self.md5) {
                                        let oldPath = cacheDir + "/" + ret.filedata;
                                        console.error(`!!!!!!!!  lj-video:renaming ${ret.filedata} to ${self.md5}  !!!`);
                                        let renameRet = fs.renameSync({
                                            oldPath: oldPath,
                                            newPath: newPath
                                        });
                                        console.log(JSON.stringify(renameRet));
                                        if (renameRet.status) {
                                            self.getBase64(newPath);
                                        }else{
                                            self.error = true;
                                            console.error("视频重命名: " + JSON.stringify(err));
                                        }
                                    } else {
                                        self.getBase64(newPath);
                                    }
                                    self.loading = false;
                                },  function(ret) {
                                    self.error = true;
                                    self.loading = false;
                                }, true);
                            }
                        });
                    });
                }
            },
            // 播放回调
            onPlayerPlay(player) {
                if (this.error) {
                    // 加载失败
                    this.refreshImg();
                    return;
                }
                let self = this;
                this.videoPlayer.play({
                    texts: {
                        head: {
                            title: self.fileName
                        }
                    },
                    styles: {
                        head: {
                            bg: 'rgba(0.5,0.5,0.5,0.7)',
                            height: 44,
                            titleSize: 16,
                            titleColor: '#fff',
                            backSize: 28,
                            backImg: 'widget://assets/image/left.png',
                            setSize: 24,
                            setImg: 'widget://assets/image/settings.png'
                        },
                        foot: {
                            bg: 'rgba(0.5,0.5,0.5,0.7)',
                            height: 44,
                            playSize: 24,
                            playImg: 'widget://assets/image/play.png',
                            pauseImg: 'widget://assets/image/pause.png',
                            nextSize: 24,
                            nextImg: 'widget://assets/image/next.png',
                            timeSize: 14,
                            timeColor: '#fff',
                            sliderImg: 'fs://img/slder.png',
                            progressColor: '#696969',
                            progressSelected: '#76EE00',
                            lockImg:'widget://assets/image/lock.png', 
                            unlockImg:'widget://assets/image/unlock.png', 
                            fullscreenImgSize: 24,
                        }
                    },
                    path: self.currentSrc, //（可选项）字符串类型；文档的路径，支持网络和本地（fs://）路径；默认：未传值时不播放
                    //在 android 平台上不支持 widget://
                    autoPlay: true, //（可选项）布尔类型；打开时是否自动播放；默认：true（自动播放）
                    isFull: false // 是否全屏
                }, function(ret, err) {
                    if (ret) {
                        // alert(JSON.stringify(ret));
                    } else {
                        // alert(JSON.stringify(err));
                    }
                });
                // console.log("player play!", player);
            },
            getBase64(path) {
                // console.log("path>>>>>>",path)
                this.currentSrc = path;
                return;
                //热加载时使用
                console.log(path);
                var trans = $lj.getBase64TranModule();
                let self = this;
                trans.decodeImgToBase64({
                    imgPath: path
                }, function (ret, err) {
                    if (ret.status) {
                        console.log(JSON.stringify(ret));
                        var str = ret.base64Str;
                        self.currentSrc = "data:image/png;base64," + str;
                    } else {
                        alert(JSON.stringify(err));
                    }
                });
            },
            getDuration() {
                console.log('getDuration this.$refs.video.duration :>>>>>>>>>>>>>>>>>>>>>'+ JSON.stringify(this.$refs.video.duration));
                if (this.$refs.video.duration) {
                    this.duration = Number(this.$refs.video.duration).toFixed(1);
                } else {
                    this.duration = 0;
                }
            },
            handleBottomNav () {
                if (this.error && !this.delbtn) {
                    // 加载失败
                    this.refreshImg();
                    return;
                }
                if (this.downloadbtn) {
                    this.download();
                } else {
                    this.$emit('bottom-nav') 
                }
            },
            download(){
                if (this.downloading || this.dlSuccess != 0) {
                    return;
                }
                this.downloading = true;
                api.saveMediaToAlbum({
                    path: this.currentSrc
                }, (ret, err) => {
                    if (ret && ret.status) {
                        this.$toast.success('保存成功');
                        this.dlSuccess = 1;
                    } else {
                        alert('保存失败');
                        this.dlSuccess = 2;
                    }
                    this.downloading = false;
                    setTimeout(() => {
                        this.dlSuccess = 0;
                    }, 1500);
                });
            }
        },
        computed: {
            realFileType() {
                let type = this.fileType || (this.fileFj ? this.fileFj.fileType : "");
                if (type) {
                    let dotIndex = type.indexOf('.');
                    if (dotIndex >= 0) {
                        type = type.substring(type.indexOf('.') + 1);
                    }
                }
                return type.replace(/^\s+|\s+$/g,"");;
            },
        },
        watch:{
            md5(newVal,oldVal){
                if (newVal !== oldVal){
                    this.refreshVideo();
                }
            },
            src(newVal,oldVal){
                if (newVal !== oldVal){
                    this.refreshVideo();
                }
            }
        }
    }
</script>

<style lang="less">
    .lj-video-dl {
        .video-dl-item {
            width: 100%;
            height: 100%;
            background: url("../../assets/image/video.png") no-repeat center center;
        }
        .video-tag {
            position: absolute;
            right: 2px;
            bottom: 2px;
            display: flex;
            .tag-item {
                border-radius: 4px;
                margin-left: 2px;
                display: flex;
                align-items: center;
                justify-content: center;
            }
        }
    }
</style>