<template>
  <view class="upgrade-popup" v-if="isModalShow">
    <image class="header-bg" src="http://192.168.123.165:9300/statics/images/common/oa-upgrade.png" mode="widthFix"></image>
    <view
      class="iconfont oaIcon-upgrade header-bg"
      style="font-size: 110px; margin-top: -110px"
      :style="{
        color: themesColor,
        fill: themesColor,
      }"
    ></view>

    <view class="main">
      <view
        class="version"
        :style="{
          color: themesColor,
        }"
      >
        发现新版本v{{ versionName }}
      </view>
      <view class="content">
        <text class="desc">{{ versionDesc }}</text>
      </view>
      <!--下载状态-进度条显示 -->
      <view class="footer" v-if="isStartDownload">
        <view class="progress-view" :class="{ active: !hasProgress }" @click="handleInstallApp">
          <!-- 进度条 -->
          <view v-if="hasProgress" style="height: 100%">
            <view class="txt">{{ percentText }}</view>
            <view class="progress" :style="setProStyle"></view>
          </view>
          <view v-else>
            <view class="btn upgrade force">{{ isDownloadFinish ? "立即安装" : "下载中..." }}</view>
          </view>
        </view>
      </view>
      <!-- 强制更新 -->
      <view class="footer" v-else-if="isForceUpdate">
        <view class="btn upgrade force" @click="handleUpgrade">立即更新</view>
      </view>
      <!-- 可选择更新 -->
      <view class="footer" v-else>
        <view class="btn close" @click="handleCancel">以后再说</view>
        <view
          class="btn upgrade"
          :style="{
            backgroundColor: themesColor,
          }"
          @click="handleUpgrade"
        >
          立即更新
        </view>
      </view>
    </view>
  </view>
  <view class="upgrade-show" v-if="isModalShow"></view>
</template>
<script setup>
import { onReady, onLoad, onShow, onNavigationBarButtonTap, onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
import { ref, onMounted, inject, shallowRef, reactive, getCurrentInstance, watchEffect, toRefs, computed } from "vue";

import { downloadApp, installApp } from "@/utils/upgrade.js";

const { proxy } = getCurrentInstance();
const props = defineProps({
  //主题颜色
  themesColor: {
    type: String,
    default: "#3f99ff",
  },
});
const emits = defineEmits([]);
const { themesColor } = toRefs(props);

const checkInfo = reactive({
  isModalShow: false, //是否打开弹窗
  isForceUpdate: false, //是否强制更新
  versionName: undefined, //版本名称
  versionDesc: undefined, //更新说明
  downloadUrl: undefined, //APP下载链接
  isDownloadFinish: false, //是否下载完成
  hasProgress: false, //是否能显示进度条
  currentPercent: 0, //当前下载百分比
  isStartDownload: false, //是否开始下载
  newFileName: "", //下载后app本地路径名称
});

const { isModalShow, isForceUpdate, versionName, versionDesc, downloadUrl, isDownloadFinish, hasProgress, currentPercent, isStartDownload, newFileName } = toRefs(checkInfo);

//设置进度条样式，实时更新进度位置
const setProStyle = computed(() => {
  return {
    width: (510 * currentPercent.value) / 100 + "rpx", //510：按钮进度条宽度
  };
});

//百分比文字
const percentText = computed(() => {
  let percent = currentPercent.value;
  if (typeof percent !== "number" || isNaN(percent)) return "下载中...";
  if (percent < 100) return `下载中${percent}%`;
  return "立即安装";
});

//更新
function handleUpgrade() {
  if (downloadUrl.value) {
    isStartDownload.value = true;
    //开始下载App
    downloadApp(downloadUrl.value, (current) => {
      //下载进度监听
      hasProgress.value = true;
      currentPercent.value = current;
    })
      .then((fileName) => {
        //下载完成
        isDownloadFinish.value = true;
        newFileName.value = fileName;
        if (fileName) {
          //自动安装App
          handleInstallApp();
        }
      })
      .catch((e) => {
        console.log(e, "e");
      });
  } else {
    uni.showToast({
      title: "下载链接不存在",
      icon: "none",
    });
  }
}

//安装app
function handleInstallApp() {
  //下载完成才能安装，防止下载过程中点击
  if (isDownloadFinish.value && newFileName.value) {
    installApp(newFileName.value, () => {
      //安装成功,关闭升级弹窗
      isModalShow.value = false;
    });
  }
}

/** 打开弹窗 */
function openUpgrade(e) {
  isModalShow.value = true;

  versionName.value = e.modalArray.buildVersion;
  versionDesc.value = e.modalArray.buildUpdateDescription.replace(/\\n/, "\n");
  downloadUrl.value = e.modalArray.downloadURL;
}

/** 取消按钮 */
function handleCancel() {
  isModalShow.value = false;
}

onLoad((option) => {});

defineExpose({
  openUpgrade,
});
</script>

<style lang="scss" scoped>
.upgrade-popup {
  width: 580rpx;
  height: auto;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #fff;
  border-radius: 20rpx;
  box-sizing: border-box;
  border: 1px solid #eee;
  z-index: 1200;
}

.header-bg {
  display: flex;
  width: 230rpx;
  margin: -112rpx auto 0 auto;
}

.main {
  padding: 10rpx 30rpx 30rpx;
  box-sizing: border-box;
  .version {
    font-size: 36rpx;
    font-weight: 700;
    width: 100%;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    letter-spacing: 1px;
  }

  .content {
    margin-top: 60rpx;
    .desc {
      display: block;
      box-sizing: border-box;
      margin-top: 20rpx;
      font-size: 28rpx;
      color: #6a6a6a;
      max-height: 80vh;
      overflow-y: auto;
    }
  }

  .footer {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    flex-shrink: 0;
    margin-top: 100rpx;

    .btn {
      width: 246rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      z-index: 999;
      height: 90rpx;
      box-sizing: border-box;
      font-size: 30rpx;
      border-radius: 10rpx;
      letter-spacing: 2rpx;

      &.force {
        width: 500rpx;
      }

      &.close {
        border: 1px solid #e0e0e0;
        margin-right: 25rpx;
        color: #000;
      }

      &.upgrade {
        color: white;
      }
    }

    .progress-view {
      width: 510rpx;
      height: 90rpx;
      display: flex;
      position: relative;
      align-items: center;
      border-radius: 6rpx;
      background-color: #dcdcdc;
      display: flex;
      justify-content: flex-start;
      padding: 0px;
      box-sizing: border-box;
      border: none;
      overflow: hidden;

      &.active {
        background-color: #026df7;
      }

      .progress {
        height: 100%;
        background-color: #026df7;
        padding: 0px;
        box-sizing: border-box;
        border: none;
        border-top-left-radius: 10rpx;
        border-bottom-left-radius: 10rpx;
      }

      .txt {
        font-size: 28rpx;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #fff;
      }
    }
  }
}

.upgrade-show {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1110;
  background: rgba(0, 0, 0, 0.6);
}
</style>
