<template>
    <lj-win-common title="版本" :show-back="true" ref="baseWin">
        <mu-button icon slot="header_right" @click="refresh">
            <i class="iconfont icon-ic_refresh"></i>
        </mu-button>
        <div slot="body">
            <div class="current-version">
                <div class="logo-box">
                    <van-image :src="wgtRootDir + '/assets/image/jlhapp-logo.png'" :alt="appName" class="logo" />
                    <!-- <van-image :src="'../../../../../assets/image/jlhapp-logo.png'" :alt="appName" class="logo" /> -->
                </div>
                <div class="content">
                    <div class="app-name">
                        {{ appName }}
                    </div>
                    <div class="app-version" v-if="currentVersion">
                        {{ `版本号 V${currentVersion}` }}
                    </div>
                </div>
            </div>
            <main class="version-content">
                <div class="has-new-version" v-if="versionStatus == 4 || versionStatus == 2">
                    <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-xing1"></use>
                    </svg>
                    发现新版本：{{ updateData.newmd5 }}
                </div>
                <div class="version-content-main">
                    <van-cell
                        class="updatetime"
                        title="发布时间"
                        :value="updateData | dateTimeFilter(versionStatus)"
                    >
                    </van-cell>
                    <div class="version-text">
                        <van-skeleton v-if="loading" title :row="5" />
                        <template v-else>
                            <div class="title">
                                新功能：
                            </div>
                            <div class="content" :class="isVersonMsgCls" v-html="versionContent"></div>
                        </template>
                    </div>
                    <div class="version-text qrcode" v-if="!loading && (versionStatus == 3)">
                        <qrcode :value="updateData.shareurl" type="img"></qrcode>
                        <div class="system-icon" v-if="isQrcodeAndroid">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-anzhuo"></use>
                            </svg>
                        </div>
                    </div>
                    <template v-if="ifIOS">
                        <div class="version-confirm">
                            <div class="confirm-btn btn">
                                <van-button class="check-btn" round block type="primary" size="normal" @click="handleConfirm">
                                    <i solt="icon" class="iconfont icon-Arrow-Right_light" style="font-size: 14px"></i>
                                    前往App Store下载
                                </van-button>
                            </div>
                        </div>
                    </template>
                    <template v-else>
                        <div class="version-confirm" :class="{'hasdownload': startDownload}" v-if="!loading && (versionStatus == 4 || versionStatus == 2)">
                            <div class="btn flex_shrink-0">
                                <transition name="slidecheck">
                                    <van-button v-show="isShowDlAgain" round size="normal" @click="handleDownloadAgain">
                                        <i solt="icon" class="iconfont icon-ic_loop" style="font-size: 14px"></i>
                                    </van-button>
                                </transition>
                            </div>
                            <div class="confirm-btn btn">
                                <transition name="slidecheck">
                                    <van-button v-show="!startDownload" :loading="confirmLoading" class="check-btn " round block :type="isBtnType" size="normal" @click="handleConfirm">
                                        <i solt="icon" class="iconfont" :class="isBtnIcon" style="font-size: 14px"></i>
                                        {{ isBtnTitle }}
                                    </van-button>
                                </transition>
                                <van-progress v-if="startDownload" class="progress-btn" :percentage="download.progress" stroke-width="8" :color="isProgressColor" />
                            </div>
                        </div>
                    </template>
                </div>
                <div class="is-new-version" v-if="versionStatus == 3">
                    <i class="iconfont icon-tongyi"></i>
                    已是最新版
                </div>
            </main>
        </div>
    </lj-win-common>
</template>

<script>
import {productInfo} from "components/project-set"
import ljWinCommon from "components/lj-win-common";
import {Qrcode} from 'vux'

    export default {
        components: {
            ljWinCommon,
            Qrcode
        },
        data() {
            return {
                loading: true,
                wgtRootDir: "",
                currentVersion: "",
                appName: "",
                updateData: {},
                versionStatus: 0, // 0: 未知， 1：当前版本高于升级计划，2：当前版本低于升级计划；3：已是最新版；4：可更新
                versionContent: "", // 新功能描述
                startDownload: false,
                confirmLoading: false,
                confirmLoading: false,
                installStatus: false, //  是否完成下载
                download: {
                    version: "",
                    url: "",
                    apkdata: "",
                    fileName: "",
                    progress: 0,
                    savePath: "",
                    changeLog: ""
                },
                ifIOS: false
            }
        },
        computed: {
            isBtnTitle() {
                return this.installStatus ? "安装" : "下载"
            },
            isBtnIcon() {
                return this.installStatus ? "icon-financial_install" : "icon-download"
            },
            isBtnType() {
                return this.installStatus ? "primary" : "info"
            },
            isProgressColor() {
                return this.download.progress >= 100 ? "#07c160" : "##1989fa"
            },
            isVersonMsgCls() {
                let cls = "";
                switch (this.versionStatus) {
                    case 1:
                    case 2:
                        cls = "dscrp";
                        break;
                    case 3:
                        if (!this.updateData.updatetime) {
                            cls = "dscrp";
                        }
                        break;
                    default:
                        break;
                }
                return cls;
            },
            isQrcodeAndroid() {
                return this.updateData.platform == '安卓'
            },
            isShowDlAgain() {
                if (this.ifIOS) return false;
                if (!this.download.url) return false;
                return !this.startDownload && this.installStatus;
            }
        },
        created() {
            if (api.systemType === "ios") {
                this.ifIOS = true;
            } 
            this.currentVersion = $lj.getVersion();
            this.appName = api.appName;
            this.refresh();
            this.wgtRootDir = api.wgtRootDir;
        },
        methods: {
            handleDownloadAgain() {
                $lj.confirm("提示", "是否清除并重新下载", () => {
                    let self = this;
                    var fs = api.require('fs');
                    fs.remove({
                        path: this.download.savePath
                    }, function(ret, err) {
                        if (ret.status) {
                            self.installStatus = false;
                            self.download.percent = 0
                            self.handleConfirm();
                        } else {
                            alert("删除失败：获取文件路径失败" + err.msg);
                        }
                    });                
                })
            },
            handleConfirm() {
                if (this.confirmLoading) return false;
                
                // 是否ios端
                if (api.systemType == "ios") {
                    api.openApp({
                        iosUrl: this.download.url
                    });
                    return;
                }
                // Android
                let _url = this.download.url;
                if (this.download.local_url) {
			        let requestWay = $lj.getPrefs('serverCurrentRequestWay');
                    if (requestWay == 'DIRECT') {
                        // IP连接中
                        _url = this.download.local_url;
                    }
                }
                api.openApp({
                    uri: _url
                }, function(ret, err) {
                });

                // let self = this;
                // if (!this.installStatus) {
                //     this.startDownload = true;
                //     console.log('handleConfirm this.download :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.download));
                //     // 下载APP
                //     $lj.download(this.download.url, this.download.savePath, function(ret) {
                //         // 下载成功
                //         console.log('$lj.download 下载完成 ret :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(ret));
                //         self.installStatus = true;
                //         self.startDownload = false;
                //         // self.$refs.CheckApp.clearState();
                //     }, function(ret) {
                //         // 下载中。。。
                //         self.download.progress = parseInt(ret.percent);
                //     }, function(err) {
                //         // 下载失败
                //         // self.$refs.CheckApp.clearState();
                //         self.download.progress = 0;
                //         self.startDownload = false;
                //     });
                // } else {
                //     // 安装App
                //     // self.$refs.CheckApp.clearState();
                //     $lj.updateApp(this.download.apkdata, this.download.fileName, function(ret) {
                //         // self._fnSetNewTime();
                //         self.confirmLoading = false;
                //         api.installApp({
                //             appUri: ret.appUri
                //         });
                //     })
                // }
            },
            refresh() {
                this.loading = true;
                let self = this;
                let appname = productInfo.productCode;
                if (this.ifIOS) {
                    appname = appname + "_ios"
                } 
                $lj.postLJRequest("GetTVUpdate", {
                    appname: appname,
                    oldmd5: this.currentVersion,
                    type: 1 // 使用中转方式
                }, function (ret) {
                    if (ret) {
                        self.loading = false;
                        self.updateData = ret;
                        self.fnCompareVersion();
                        self.fnCheckAppRequest(ret);
                    }
                })
            },
            fnCheckAppRequest(ret) {
                this.checkingApp = false;
                this.download.fileName = productInfo.productCode + "_" + ret.newmd5.replace(/\./g, "_") + ".apk";
                this.download.version = ret.newmd5 || "";
                this.download.changeLog = ret.changelog_new || "";

                // 主动获取版本检测，跳过此约束
                if (ret.apkdata) {
                    // 更新
                    // this.hasNewApp = true
                    this.installStatus = true;
                    this.download.apkdata = ret.apkdata;
                }else if (ret.url) {
                    // 可下载更新
                    // this.hasNewApp = true
                    this.installStatus = false;
                    $lj.getCacheDir((cacheDir) => {
                        let newpath = cacheDir + "/" + this.download.fileName;
                        this.download.url = ret.url;
                        this.download.local_url = ret.hasOwnProperty("local_url") ? ret.local_url : "";
                        this.download.apkdata = this.download.fileName;
                        this.download.savePath = newpath;

                        let fs = $lj.getFileHelperModule();
                        let existRet = fs.existSync({
                            path: newpath
                        });

                        if (existRet.exist) {
                            this.installStatus = true;
                            this.startDownload = false;
                        }

                    });
                    // if (api.systemType != "ios") {
                    // }
                }
            },
            /**比较 */
            fnCompareVersion() {
                if ($lj.transVersionToInt(this.currentVersion) > $lj.transVersionToInt(this.updateData.newmd5)) {
                    // 当前版本高于升级计划
                    this.versionStatus = 1;
                } else if ($lj.transVersionToInt(this.currentVersion) == $lj.transVersionToInt(this.updateData.newmd5)) {
                    // 当前是最新版
                    this.versionStatus = 3
                } else if (!this.updateData.updatetime) {
                    // 升级计划没记录
                    this.versionStatus = 2
                } else {
                    this.versionStatus = 4
                }
                this.versionContent = this.fnToVersionMsg(this.updateData.changelog_new);
            },
            fnToVersionMsg(data) {
                if (!data) return '';
                let changeLog = '', i = 0;
                changeLog = data.replace(/[0-9]*[0-9][.|、]/g, function(captured) { 
                    if (i++) { 
                        return "<br/>" + captured; 
                    } 
                    return captured; 
                })
                return changeLog;
            },
            handleMenus() {
                let self = this;
                api.actionSheet({
                    // title: '底部弹出框测试',
                    cancelTitle: '取消',
                    buttons: ['重新生成二维码',]
                }, function (ret, err) {
                    var index = ret.buttonIndex;
                    if (index === 1) {
                        self.reloadQrcode();
                    }
                });
            },
            reloadQrcode(){
                let self = this;
                $lj.postLJRequest("GetL1APPQrcode", {
                    token: $lj.getStorage("token"),
                    type: 1,
                }, function (ret) {
                    if (ret) {
                        self.qrcodeObj = ret.Qrcode;
                        self.qrcode = self.qrcodeObj.qrcode;
                    }
                })
            }
        },
        filters: {
            dateTimeFilter(data, type) {
                if (type == 2 || type == 1 || (type == 3 && !data.updatetime)) {
                    return '未知'
                }
                if (!data.updatetime) return '-'; 
                return $lj.parseTime(data.updatetime, '{y}-{m}-{d} {h}:{i}')
            },
        }
    }
</script>

<style lang="less">
.background-color {
    background-color: @light-barkground-primary!important;
}
.current-version {
    display: flex;
    flex-direction: column;
    // justify-content: center;
    align-items: center;
    padding-top: 40px;

    .logo-box {
        width: 74px;
        height: 74px;
        border-radius: 16px;
        background: @light-barkground-elevated-primary;
        overflow: hidden;
        padding: 14px;

        .logo {
            width: 100%;
            height: 100%;
        }
    }
    .content {
        padding: 16px 0;
        display: flex;
        flex-direction: column;
        align-items: center;

        .app-name {
            font-size: 17px;
            font-weight: 600;
            color: @light-label-primary;
        }
        .app-version {
            font-size: 14px;
            color: @light-label-primary;
        }
    }
}
.version-content {
    margin: 0 20px;
    // border-radius: 8px;
    // overflow: hidden;

    .version-content-main {
        border-radius: 8px;
        overflow: hidden;
        background: @light-barkground-elevated-primary;
    }
    .has-new-version {
        color: @light-label-primary;
        padding: 8px 16px;
    }
    .is-new-version {
        color: @light-label-tertiary;
        padding: 8px 16px;
        text-align: center;

        .iconfont {
            color: @light-system-green3;
            font-size: 14px;
        }
    }
    .version-text {
        padding: 12px 16px;

        .title {
            // font-size: 17px;
            color: @light-label-secondary;
            margin-bottom: 6px;
        }
        .content.dscrp {
            color: @light-label-tertiary;
            text-align: center;
        }
    }
    .qrcode {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 16px;

        .system-icon {
            position: absolute;
            bottom: 0;
            right: 0;
            display: inline-block;

            .icon {
                width: 44px;
                height: 44px;
                vertical-align: middle;
            }
        }
    }
}

.version-confirm {
  margin: 8px 48px;
}
</style>