<!--图片展示器，集下载、删除等辅助功能（集成了龙嘉协议获取图片的方式）-->
<template>
    <div class="lj-img-pro lj-picture_and_video" :class="{'round': round}">
        <van-image
            class="img-pro-box"
            :src="currentSrc" 
            :fit="fit"
            :round="round"
            :radius="RadiusValue"
            @click="imageClick"
        >
            <template v-slot:error>
                <i v-if="!error" class="loading-icon iconfont icon-a-Image2"></i>
                <i v-else class="error-icon iconfont icon-ImageError"></i>
            </template>
        </van-image>
        <slot name="bottom-nav" v-if="showfilename">
            <div class="bottom-nav">
                <div class="name text-ellipsis-one">
                    {{ fileName }}
                </div>
            </div>
        </slot>
        <div class="bottom-nav-status" v-if="downloadbtn && (downloading || dlSuccess != 0)" :class="{'show': downloadbtn && (downloading || dlSuccess != 0)}">
            <!-- <div class="error-refresh" v-if="error && !delbtn"></div> -->
            <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="#8E8E93" 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 {
        name: "lj-img-pro",
        props: {
            // 龙嘉协议的图片md5值
            md5: {
                Type: String,
                default: ""
            },
            // 普通http路径
            src: {
                Type: String,
                default: ""
            },
            fit:{
                Type:String,
                default:"contain"
                // contain	保持宽高缩放图片，使图片的长边能完全显示出来
                // cover	保持宽高缩放图片，使图片的短边能完全显示出来，裁剪长边
                // fill	拉伸图片，使图片填满元素
                // none	保持图片原有尺寸
                // scale-down	取none或contain中较小的一个
            },
            round:{
                Type:Boolean,
                default:false
            },
            Radius:{
                Type:String,
                default:'0'
            },
            fileType: String,
            fileName: String,
            delbtn: { // 是否显示删除按钮
                type: Boolean,
                default: false
            },
            downloadbtn: {// 是否显示下载按钮
                type: Boolean,
                default: false
            },
            showfilename: {// 是否显示文件名
                type: Boolean,
                default: false
            },
            loadPostion: { // loading位置。默认右上，
                type: String,
                default: ''
            }
        },
        data() {
            return {
                currentSrc: "",
                RadiusValue: "",
                downloading: false,
                dlSuccess: 0, // 是否下载成功: 0，未操作，1：成功，2：失败
                loading: false,
                error: false,
            }
        },
        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,"");;
            },
        },
        mounted() {
            if(this.Round){
              this.RadiusValue = '50%';
            }
            else{
                this.RadiusValue = this.Radius;
            }

            this.refreshImg();
        },
        methods: {
            refreshImg() {
                this.error = false;
                this.loading = true;
                let self = this;

                if (this.src) {
                    //this.currentSrc = this.src;
                    api.imageCache({
                        url: this.src,
                        policy: "cache_only",
                        thumbnail: false
                    }, function (ret, err) {
                        self.loading = false;
                        if (!err) {
                            self.getBase64(ret.url)
                        }else{
                            self.error = true;
                            alert(JSON.stringify(err));
                        }
                        console.log(ret.status + "\r\n" + ret.url);
                    })
                } else if (this.md5) {
                    $lj.getCacheDir(function (cacheDir) {
                        let path = cacheDir + "/" + self.md5;
                        var fs = $lj.getFileHelperModule();
                        console.warn("refreshImg getCacheDir:" + path);
                        fs.exist({
                            path: path
                        }, function (ret, err) {
                            if (ret.exist) {
                                self.loading = false;
                                self.getBase64(path);
                            } else {
                                $lj.postLJRequest("GetCacheFile", {filemd5: self.md5}, function (ret) {
                                    var cacheDir = $lj.constant.cacheDir;
                                    let newPath = cacheDir + "/" + self.md5;
                                    if (ret.filedata !== self.md5) {
                                        let oldPath = cacheDir + "/" + ret.filedata;
                                        console.error(`!!!!!!!!  lj-img:renaming ${ret.filedata} to ${self.md5}  !!!`);
                                        fs.rename({
                                            oldPath: oldPath,
                                            newPath: newPath
                                        }, function (ret, err) {
                                            if (ret.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);
                            }
                        });
                    });
                }
            },
            imageClick(item) {
                if (this.error) {
                    // 加载失败
                    this.refreshImg();
                    return;
                }
                this.$emit('image-click', item);
            },
            getBase64(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));
                    }
                });
            },
            handleBottomNav () {
                if (this.error && !this.delbtn) {
                    // 加载失败
                    this.refreshImg();
                    return;
                }
                if (this.downloadbtn) {
                    this.download();
                } else {
                    this.$emit('bottom-nav') 
                }
            },
            checkFile(oldPath, callback) {
                let self = this;
                var fs = $lj.getFileHelperModule();

                $lj.getCacheDir(function (cacheDir) {
                    let newPath = cacheDir + "/topic/" + self.md5 + "." + self.realFileType;
                    // console.warn("refreshImg getCacheDir:" + cacheDir);
                    fs.exist({
                        path: newPath
                    }, function (ret, err) {
                        // console.log('newPath ret :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(ret));
                        if (ret.exist) {
                            callback(newPath);
                            return;
                        } else {
                            fs.copyTo({
                                oldPath: oldPath,
                                newPath: cacheDir + "/topic"
                            }, function(ret, err) {
                                // console.log('copyTo ret :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(ret));
                                if (ret.status) {
                                    fs.rename({
                                        oldPath: cacheDir + "/topic/" + self.md5,
                                        newPath: newPath
                                    }, function (ret, err) {
                                        if (ret.status) {
                                            callback(newPath);
                                        } else {
                                            console.error("图片重命名: " + JSON.stringify(err));
                                        }
                                    });
                                } else {
                                    alert('copyTo操作失败，保存中断');
                                }
                            });
                        }
                    });
                });
            },
            _fnDownLoad(path, callback) {
                api.saveMediaToAlbum({
                    path: path
                }, (ret, err) => {
                    if (ret && ret.status) {
                        this.$toast.success('保存成功');
                        this.dlSuccess = 1;
                    } else {
                        alert('保存失败');
                        this.dlSuccess = 2;
                    }
                    callback();
                    setTimeout(() => {
                        this.dlSuccess = 0;
                    }, 1500);
                });
            },
            download(){
                if (this.downloading || this.dlSuccess != 0) {
                    return;
                }
                this.downloading = true;
                if (this.src) {
                    this._fnDownLoad(this.currentSrc, () => {
                        this.downloading = false;
                    })
                } else if (this.md5) {
                    this.checkFile(this.currentSrc, (newPath) => {
                        this._fnDownLoad(newPath, () => {
                            this.downloading = false;
                        })
                    });
                }
            },
        },
        watch:{
            md5(newVal,oldVal){
                if (newVal !== oldVal){
                    this.refreshImg();
                }
            },
            src(newVal,oldVal){
                if (newVal !== oldVal){
                    this.refreshImg();
                }
            }
        }
    }
</script>

<style lang="less">
    .lj-img-pro {
        &.round {
            border-radius: 50%;
            overflow: hidden;
        }
        .img-pro-box {
            display: block;
            width: 100%;
            height: 100%;

            .loading-icon {
                font-size: 32px;
                color: @light-system-gray4;
                opacity: 0.3;
            }
            .error-icon {
                font-size: 32px;
                color: @light-system-red;
                opacity: 0.6;
            }
        }
    }
</style>