<template>
  <div class="text-center q-py-xl q-px-md">
    <img src="icons/favicon-128x128.png" width="64" class="q-mt-xl q-mb-lg rounded-borders"/>
    <div v-if="appInfo" class="">
      <div class="text-h6 q-mb-md">发现新版本v{{ appInfo.version }}</div>
      <div class="q-mb-md">{{ appInfo.description||'您好，您当前使用的版本太低，不更新将无法使用APP，为了您正常使用，请更新最新版本。' }}</div>
      <p class="text-caption">
        <a :href="appInfo.url" target="_blank" class="text-primary">点击下载最新版本</a>
      </p>
    </div>
    <div v-else id="app" class="">正在努力加载...</div>
  </div>
</template>

<script setup>
import {shallowRef } from 'vue'
import axios from "axios";
import {compareVersions} from 'compare-versions'

import { useQuasar,openURL } from 'quasar';
const $q = useQuasar()
const service = axios.create({
  headers: {
    "Content-Type": "application/json"
  },
  timeout: 30000,
  baseURL: process.env.BASE_URL+"/api/",
  transformRequest: [function (data, headers) {
    return JSON.stringify(data);
  }],
});
service.interceptors.response.use(
  function (response) {
    if (response.data && response.data.code == 200) {
      return response.data.data;
    }
    return Promise.reject({
      message: response.data?.message,
      code: response.data?.code
    });
  },
  (error) => {
    let retErr = {
      message: error.message
    }
    if (axios.isCancel(error)) {
      retErr.message = "请求已取消"
      return Promise.reject(retErr);
    } else {
      let data = error.response?.data;
      retErr.code = data?.code ?? (error.code||-1);
      if (data && data.message) {
        retErr.message = data.message;
      } else {
        retErr.message = "网络连接失败，请稍后重试";
      }
      return Promise.reject(retErr);
    }
  }
);
const appInfo = shallowRef(null)
// 检查更新
function checkUpdate() {
  const version = window.AppVersion?.version??'0.0.1'
  return service.get('seller/app/version_info').then(res => {
    if (res && compareVersions(res.version, version) > 0) {
      return res
    } else {
      return Promise.reject(new Error('未发现新版本'))
    }
  })
  .then(({ version, version_code, url, description }) => {
    setTimeout(() => {
      $q.dialog({
        title: "发现新版本v" + version,
        message: description,
        html: true,
        ok: "前往更新",
        persistent: true
      })
        .onOk(() => {
          openURL(url);
        })
        .onDismiss(() => {
          appInfo.value = {
            version,url,description
          }
        });
    }, 0);
    return version;
  })
}

checkUpdate().catch((e) => {
  window.open(process.env.BASE_URL+'/app.html',"_blank")
})
document.addEventListener("deviceready", () => {
  navigator.splashscreen.hide()
});
</script>
