<template>
  <uni-popup
    ref="popup"
    type="bottom"
    border-radius="20rpx"
    style="z-index: 99999"
    :is-mask-click="false"
  >
    <view class="upload-app">
      <image
        src="/static/images/upload/bj.png"
        class="upload-app__bj"
        mode="aspectFit"
      ></image>
      <view class="upload-app__main">
        <view class="upload-app__main__title">发现新版本</view>
        <view class="upload-app__main__version">
          <text class="upload-app__main__version__text"
            >v{{ newVersion }}已发布，推荐更新</text
          >
        </view>
        <view
          class="upload-app__main__content__title"
          v-if="this.apkUpdateContent"
          >更新内容</view
        >
        <view class="upload-app__main__contents">
          <rich-text
            :nodes="this.apkUpdateContent"
            v-if="this.apkUpdateContent"
          ></rich-text>
          <!-- <view class="upload-app__main__contents__content"
            >1.修复多处稳定性问题，提升了应用的流程</view
          >
          <view class="upload-app__main__contents__content"
            >2.修复多处稳定性问题，提升了应用的流程</view
          > -->
        </view>
        <view
          class="upload-app__main__buttons"
          v-if="this.is_force == 0 && !this.startUpload"
        >
          <view class="upload-app__main__buttons__Later">
            <text
              class="upload-app__main__buttons__Later__text"
              @click="Updatelater"
              >稍后更新</text
            >
          </view>
          <view class="upload-app__main__buttons__immediately">
            <text
              class="upload-app__main__buttons__immediately__text"
              @click="UpdateNow"
              >立即更新</text
            >
          </view>
        </view>
        <view
          class="upload-app__main__buttons"
          v-else-if="this.is_force == 1 && !this.startUpload"
        >
          <view
            class="upload-app__main__buttons__immediately Mandatory"
            @click="UpdateNow"
          >
            <text class="upload-app__main__buttons__immediately__text"
              >立即更新</text
            >
          </view>
        </view>
        <view class="upload-app__main__Progress" v-if="this.startUpload">
          <view class="upload-app__main__Progress__bar">
            <view
              class="upload-app__main__Progress__bar__active"
              :style="{ width: 495 * (updateProgress / 100) + 'rpx' }"
            >
            </view>
            <view class="upload-app__main__Progress__bar__text">
              {{ updateProgress }}%
            </view>
          </view>
          <view class="upload-app__main__Progress__hint">
            新版本正在努力更新中，请耐心等待
          </view>
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<script>
import request from "@/utils/request";
import uniPopup from "@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue";
export default {
  name: "uploadAppVue",
  data() {
    return {
      version: null, //现在版本
      updateProgress: 0, //下载进度
      newVersion: null, //最新版本
      updateAPKPath: "", //更新地址
      is_force: 0, //是否强更，0为否1为是
      startUpload: false, //是否开启跟新
      down_type: null, //1是跳转，2是下载
      apkUpdateContent: "", //更新内容说明

      updateType: "", //1资源包更新2版本更新
      versionsFlag: 1, //1需要更新弹窗2已是最新版本弹窗3正在下载
      latestVersionInfo: "", //已是最新版本弹窗内容

      restartFlag: false, // 是否需要重启APP
      show: true,
    };
  },
  props: {
    isHome: {
      type: Boolean,
      default: true,
    },
  },
  created() {},
  mounted() {
    if (this.isHome) {
      this.uploadApp();
    }
	// this.$refs.popup.open("center");
  },
  methods: {
    Updatelater() {
      let timestamp = Date.now();
      uni.setStorageSync("updatelaterTime", timestamp);
      this.$refs.popup.close();
      // uni.showTabBar();
    },
    UpdateNow() {
      if (this.down_type == 1) {
        plus.runtime.openURL(this.updateAPKPath);
      } else if (this.down_type == 2) {
        this.startUpload = true;
        this.uploadAppDowlond();
      }
    },
    // app内跟新下载
    uploadAppDowlond() {
      const downloadTask = uni.downloadFile({
        url: this.updateAPKPath,
        success: (downloadResult) => {
          if (downloadResult.statusCode === 200) {
            plus.runtime.install(
              downloadResult.tempFilePath,
              {
                force: false,
              },
              function () {
                // 下载资源成功，重启应用
                plus.runtime.restart();
              },
              function (e) {
                // 下载资源失败
              }
            );
          }
        },
      });

      downloadTask.onProgressUpdate((res) => {
        this.updateProgress = res.progress;
        console.log("下载进度" + res.progress);
        console.log("已经下载的数据长度" + res.totalBytesWritten);
        console.log("预期需要下载的数据总长度" + res.totalBytesExpectedToWrite);

        // 满足测试条件，取消下载任务。
        // if (res.progress > 50) {
        // 	downloadTask.abort();
        // }
      });
    },
    async uploadApp(type) {
      // uploadAppDowlond()
      try {
        await this.getVersionNum();
        if (!this.version) return;
        // #ifdef APP-PLUS
        await this.getUpdateInfo();
        let timestamp = Date.now();
        let updatelaterTime = uni.getStorageSync("updatelaterTime") || 0;
        if (
          Math.abs(timestamp - updatelaterTime) < 86400000 &&
          this.is_force != 1 &&
          type != "setting"
        ) {
          return;
        }

        if (!this.newVersion) {
          if (type == "setting") {
            uni.showToast({
              title: "当前已是最新版本",
              icon: "none",
            });
          }
        } else {
          uni.hideTabBar();
          this.$refs.popup.open("center");
        }
        // if (this.compareVersion(this.version, this.newVersion)) {
        // 	uni.hideTabBar();
        // 	this.$refs.popup.open("center");
        // } else {
        // 	uni.showToast({
        // 		title: "当前已是最新版本",
        // 		icon: "none",
        // 	});
        // }
        // #endif
      } catch (error) {
        console.error("检查更新失败:", error);
      }
    },
    getVersionNum() {
      // 获取当前app的版本
      const systemInfo = uni.getSystemInfoSync();
      // 应用程序版本号
      // 条件编译，只在APP渲染
      // #ifdef APP
      this.version = systemInfo.appWgtVersion;
      // #endif
      // #ifdef H5
      this.version = systemInfo.appVersion;
      console.log(systemInfo.appVersion, "版本号");
      // #endif
      // #ifdef MP-WEIXIN
      const accountInfo = uni.getAccountInfoSync();
      this.version = accountInfo.miniProgram.version; // 小程序 版本号
      console.log(accountInfo.miniProgram.version, "小程序版本号");
      // #endif
      return this.version;
    },
    async getUpdateInfo() {
      const response = await request.post("/sj/getAppVersion");
      this.newVersion = response.data?.version;
      this.updateAPKPath = response.data?.url;
      this.is_force = response.data?.is_force;
      this.down_type = response.data?.down_type;
      this.apkUpdateContent = response.data?.explain;
    },
    compareVersion(current, latest) {
      const curParts = current.split(".").map(Number);
      const latParts = latest.split(".").map(Number);

      for (let i = 0; i < Math.max(curParts.length, latParts.length); i++) {
        const cur = curParts[i] || 0;
        const lat = latParts[i] || 0;
        if (cur < lat) return true;
        if (cur > lat) return false;
      }
      return false;
    },
  },
};
</script>

<style scoped lang="less">
.popupShow {
  overflow: hidden;
  position: fixed;
}

.upload-app {
  width: 568rpx;
  background-color: #ffff;
  position: relative;
  border-radius: 20rpx;

  &__bj {
    width: 568rpx;
    height: 317rpx;
    position: absolute;
    left: 0;
    top: -23rpx;
    z-index: 0;
  }

  &__main {
    z-index: 1;
    position: relative;

    &__title {
      font-weight: 600;
      font-size: 46rpx;
      color: #333333;
      line-height: 65rpx;
      text-align: left;
      font-style: normal;
      padding: 40rpx 38rpx 14rpx 38rpx;
    }

    &__version {
      margin-left: 38rpx;
      width: auto;
      display: inline;
      // height: 33rpx;
      padding: 4rpx 10rpx;
      background: linear-gradient(136deg, #fed7f5 0%, #fbdce5 100%);
      border-radius: 0rpx 10rpx 0rpx 10rpx;

      &__text {
        font-weight: 400;
        font-size: 18rpx;
        color: #E8101E;
        line-height: 25rpx;
        text-align: left;
        font-style: normal;
      }
    }

    &__content__title {
      padding-left: 39rpx;
      padding-top: 38rpx;
      font-weight: 500;
      font-size: 30rpx;
      color: #333333;
      line-height: 42rpx;
      text-align: left;
      font-style: normal;
    }

    &__contents {
      padding: 20rpx 40rpx 40rpx 40rpx;
      display: flex;
      flex-wrap: wrap;
      row-gap: 14rpx;

      ::v-deep p {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 26rpx;
        color: #5e5e60;
        line-height: 37rpx;
        text-align: left;
        font-style: normal;
      }
    }

    &__buttons {
      padding: 0rpx 40rpx 50rpx 40rpx;
      display: flex;
      flex-wrap: nowrap;
      justify-content: space-between;
      align-items: center;

      &__Later {
        width: 236rpx;
        height: 78rpx;
        background: #f6f6f6;
        border-radius: 39rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        &__text {
          font-weight: 500;
          font-size: 30rpx;
          color: #333333;
          line-height: 42rpx;
          text-align: left;
          font-style: normal;
        }
      }

      &__immediately {
        width: 236rpx;
        height: 78rpx;
        background: #E8101E;
        border-radius: 39rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        &__text {
          font-weight: 500;
          font-size: 30rpx;
          color: #ffffff;
          line-height: 42rpx;
          text-align: left;
          font-style: normal;
        }
      }

      &__immediately.Mandatory {
        width: 100%;
      }
    }

    &__Progress {
      padding: 10rpx 40rpx 40rpx 40rpx;

      &__bar {
        margin-bottom: 20rpx;
        width: 495rpx;
        height: 28rpx;
        background: #f0f1f3;
        border-radius: 39rpx;
        position: relative;

        &__active {
          height: 28rpx;
          background: linear-gradient(270deg, #fe78b3 0%, #E8101E 100%);
          border-radius: 39rpx;
        }

        &__text {
          font-weight: 400;
          font-size: 24rpx;
          color: #333333;
          text-align: left;
          font-style: normal;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate3d(-50%, -50%, 0);
        }
      }

      &__hint {
        font-weight: 400;
        font-size: 20rpx;
        color: #a5a6ad;
        line-height: 28rpx;
        text-align: left;
        font-style: normal;
        text-align: center;
      }
    }
  }
}
</style>
