<template>
  <uv-popup
    ref="popupRef"
    mode="center"
    bgColor="none"
    round="20rpx"
    :close-on-click-overlay="false"
    @change="popupChange"
  >
    <view class="version-update">
      <view class="version-update-content">
        <view class="content-form">
          <view class="title">发现最新版本</view>
          <view class="value">V{{ appInfo.version }}</view>
        </view>
        <view class="content-form">
          <view class="title">更新描述：</view>
          <view class="value">
            <view
              class="value-text"
              v-for="(item, index) in description"
              :key="index"
              >{{ item }}</view
            >
          </view>
        </view>

        <view v-if="startProgress" class="smallTitle">
          <view>下载进度:{{ downloadProgress }}%</view>
          <uv-line-progress
            active-color="#eb5153"
            :percentage="downloadProgress"
          >
          </uv-line-progress>
        </view>
        <button class="u-btn-two" @click.stop="handleUpdate">立即更新</button>
      </view>

      <view class="version-update-close" v-if="!appInfo.status">
        <uv-icon
          name="close-circle"
          color="#c4c4c4"
          size="28"
          @click="closePopup"
        ></uv-icon>
      </view>
    </view>
  </uv-popup>
</template>

<script setup name="VersionUpdate">
import { ref, onMounted, nextTick } from "vue";
import { appVersionNewest_Api } from "@/api/index.js";
const $props = defineProps({
  open: { type: Boolean, default: true },
});
const $emit = defineEmits(["setAppInfo"]);
const popupRef = ref(null);

const appInfo = ref({});
const startProgress = ref(false);
const downloadProgress = ref(0);
const packgePath = ref("");
const type = ref(0); // 0: android, 1: ios
const description = ref([]); // 更新描述
const downloadTask = ref(null);
const installed = ref(false);
// 获取更新信息
const getAppInfo = () => {
  appVersionNewest_Api({ type: type.value }).then((res) => {
    // console.log(res);
    if (res && res.code == 200) {
      appInfo.value = res.data || {};
      const systemInfo = uni.getSystemInfoSync();
      //   console.log(systemInfo);
      if (appInfo.value.description) {
        // 将描述按\n分割成数组
        description.value = appInfo.value.description.split("\n");
      }
      let appUpdate = false;
      if (
        (systemInfo.appVersionCode || 0) * 1 <
        (appInfo.value.level || 0) * 1
      ) {
        appUpdate = true;
        if ($props.open) {
          nextTick(() => {
            popupRef.value.open();
          });
          try {
            uni.hideTabBar();
          } catch (error) {}
        }
      }
      nextTick(() => {
        $emit("setAppInfo", {
          version: systemInfo.appVersion, // app版本号
          appUpdate: appUpdate, // 是否有新版本
        });
      });
    }
  });
};

// 开始下载任务
const createTask = (downloadLink) => {
  console.log("下载链接" + downloadLink);
  downloadProgress.value = 0;
  startProgress.value = true;
  // 创建下载任务对象
  downloadTask.value = uni.downloadFile({
    url: downloadLink,
    success: (res) => {
      //   console.log("下载成功", res);
      if (res.statusCode === 200) {
        // 保存下载的安装包
        uni.saveFile({
          tempFilePath: res.tempFilePath,
          success: (res) => {
            packgePath.value = res.savedFilePath;
            // 进行安装
            installPackge();
            // 任务完成，关闭下载任务
            closeTask();
          },
        });
      }
    },
  });

  downloadTask.value.onProgressUpdate((res) => {
    downloadProgress.value = res.progress;
    // uni.$forceUpdate();
    // console.log(res.progress);
  });
};

// 关闭下载任务
const closeTask = () => {
  downloadTask.value.abort();
  downloadTask.value = null;
  startProgress.value = false;
};

const installPackge = () => {
  // 安装更新
  plus.runtime.install(packgePath.value, {
    force: true,
  });
  installed.value = true;
  // 保存更新记录到stroage，方便下次启动app时删除安装包
  uni.setStorage({
    key: "updated",
    data: {
      completed: true,
      packgePath: packgePath.value,
    },
    success: (res) => {
      console.log("成功保存更新记录");
      // console.log(res.data)
    },
  });
  // 判断是否为热更新（判断文件名中是否含有.wgt）
  //   console.log(8888888888888888888888 + packgePath.value);
  if (packgePath.value.match(RegExp(/.wgt/))) {
    // console.log("9999999999999");
    installed.value = false;
    uni.showModal({
      title: "提示",
      content: "应用将重启以完成更新",
      showCancel: false,
      complete: () => {
        plus.runtime.restart();
      },
    });
  }
};

const handleUpdate = () => {
  //   console.log("startProgress.value", startProgress.value);
  if (startProgress.value) {
    uni.$uv.toast("请稍等，正在下载更新");
    return;
  }
  // 判断系统类型
  if (plus.os.name.toLowerCase() === "android") {
    if (appInfo.value.downloadLink && appInfo.value.downloadLink !== "#") {
      createTask(appInfo.value.downloadLink);
    } else {
      uni.$uv.toast("未找到下载地址");
    }
  } else {
    if (appInfo.value.ios_link && appInfo.value.ios_link !== "#") {
      // 我这里默认#也是没有地址，请根据业务自行修改
      // 苹果(A)：进行热更新（如果iosUrl是wgt更新包的下载地址）判断文件名中是否含有.wgt
      if (appInfo.value.ios_link.match(RegExp(/.wgt/))) {
        createTask(appInfo.value.ios_link);
      } else {
        // 苹果(B)：打开商店链接（如果iosUrl是苹果商店的地址）
        plus.runtime.openURL(appInfo.value.ios_link);
      }
    } else {
      uni.$uv.toast("未找到ios商店地址");
    }
  }
};

const popupChange = (e) => {
  if (!e.show) {
    uni.showTabBar();
  }
};

const closePopup = () => {
  popupRef.value.close();
};

const open = () => {
  popupRef.value.open();
};

onMounted(() => {
  console.log("onLoad");
  // #ifdef APP-PLUS
  type.value = plus.os.name.toLowerCase() === "android" ? 0 : 1;
  // #endif

  getAppInfo();
});

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

<style scoped lang="scss">
.version-update {
  .version-update-content {
    width: 487rpx;
    min-height: 451rpx;
    border-radius: 20px;
    background: url("@/static/version_bg.png") no-repeat;
    background-size: 100% 100%;
    box-sizing: border-box;
    padding: 124rpx 30rpx 67rpx 30rpx;
    .content-form {
      margin-bottom: 40rpx;

      .title {
        font-size: 34rpx;
        font-family: PingFang SC, PingFang SC-Bold;
        font-weight: 700;
        text-align: left;
        color: #1a1a1a;
        margin-bottom: 5rpx;
      }
      .value {
        font-size: 28rpx;
        color: #808080;
        .value-text {
          position: relative;
          padding-left: 20rpx;
          &::after {
            content: "";
            width: 8rpx;
            height: 8rpx;
            background: #808080;
            border-radius: 50%;
            position: absolute;
            left: 0;
            top: 16rpx;
          }
        }
      }
    }
    .smallTitle {
      padding-bottom: 30rpx;
      text-align: center;
    }
    .u-btn-two {
    }
  }
  .version-update-close {
    display: flex;
    justify-content: center;

    margin-top: 30rpx;
  }
}
</style>
