import { createApp } from "vue";
import {
  ActionBar,
  ActionBarIcon,
  ActionBarButton,
  Divider,
  Popup,
  Overlay,
  Loading,
  Dialog,
  ContactCard,
  Form,
  AddressEdit,
  AddressList,
  Field,
  CellGroup,
  Cell,
  SwipeCell,
  Icon,
  Stepper,
  Card,
  Checkbox,
  CheckboxGroup,
  Button,
  Swipe,
  SwipeItem,
  PullRefresh,
  List,
  Tab,
  Tabs,
  SubmitBar,
  Toast,
  Skeleton,
  RadioGroup,
  Radio,
  NoticeBar,
  ActionSheet,
  Cascader,
  Col,
  Row,
  Slider,
  DatePicker,
  Switch,
  Calendar,
  Picker,
  Uploader,
  Tag,
  DropdownMenu,
  DropdownItem,
  Notify,
  ConfigProvider,
  NavBar,
  Area,
  Popover,
  Collapse,
  CollapseItem,
  PickerGroup,
  TimePicker,
  BackTop,
  Progress,
  Tabbar,
  TabbarItem,
  Search,
  FloatingBubble,
  TextEllipsis,
  Step,
  Steps,
  Sticky,
  showConfirmDialog,
} from "vant";
import { Image as VanImage } from "vant";
import App from "./App.vue";
import store from "./store";
import router from "./router";
import "lib-flexible/flexible";
import "vant/lib/index.css"; // 全局引入样式
import "@vant/touch-emulator";
// 导入语言
import i18n from "./utils/i18n";

async function checkVersion() {
  // 开发环境跳过检测
  // if (process.env.NODE_ENV !== "production") return;
  try {
    // 添加时间戳避免 version.json 缓存
    const response = await fetch("/shenze/version.json?t=" + Date.now());
    const serverVersion = await response.json();
    const localVersion = localStorage.getItem("appVersion") || "";

    if (serverVersion.version !== localVersion) {
      showUpdateDialog(serverVersion.version); // 触发更新提示
    } else if (!localVersion) {
      localStorage.setItem("appVersion", serverVersion.version);
    }
  } catch (error) {
    console.error("版本检测失败:", error);
  }
}

// 启动定时检测（每 30 秒）
function startVersionPolling() {
  checkVersion(); // 初始检测
  setInterval(checkVersion, 30000); // 30 秒轮询一次
}

// 在应用初始化时启动轮询
startVersionPolling();

function showUpdateDialog(newVersion) {
  const { t } = i18n.global;
  showConfirmDialog({
    title: t("public.updateTips"),
    message: t("public.checkUpdate") + 'v' + newVersion,
    confirmButtonText: t("public.resetNow"),
    showCancelButton: false,
  })
    .then(() => {
      localStorage.setItem("appVersion", newVersion);
      window.location.reload();
    })
    .catch(() => {
      console.log("用户推迟了更新");
    });
}

// 注册Service Worker
if ("serviceWorker" in navigator && process.env.NODE_ENV === "production") {
  window.addEventListener("load", () => {
    navigator.serviceWorker
      .register("/shenze/sw.js")
      .then((registration) => {
        console.log("ServiceWorker 注册成功:", registration.scope);

        navigator.serviceWorker.addEventListener("controllerchange", () => {
          window.location.reload();
        });
      })
      .catch((error) => {
        console.log("ServiceWorker 注册失败:", error);
      });
  });
}

// 在应用初始化前执行检测
checkVersion();

const app = createApp(App); // 创建实例
// 全局过滤器
app.config.globalProperties.$filters = {
  prefix(url) {
    if (url && url.startsWith("http")) {
      return url;
    } else {
      url = `http://backend-api-01.newbee.ltd${url}`;
      return url;
    }
  },
};
// Vant组件注册
app
  .use(ActionBarButton)
  .use(ActionBarIcon)
  .use(ActionBar)
  .use(Divider)
  .use(Popup)
  .use(Overlay)
  .use(Loading)
  .use(Dialog)
  .use(Toast)
  .use(ContactCard)
  .use(Form)
  .use(AddressEdit)
  .use(AddressList)
  .use(Field)
  .use(CellGroup)
  .use(Cell)
  .use(SwipeCell)
  .use(Icon)
  .use(Stepper)
  .use(Card)
  .use(Button)
  .use(Swipe)
  .use(SwipeItem)
  .use(PullRefresh)
  .use(List)
  .use(Tab)
  .use(Tabs)
  .use(SubmitBar)
  .use(Checkbox)
  .use(CheckboxGroup)
  .use(Skeleton)
  .use(VanImage)
  .use(RadioGroup)
  .use(Radio)
  .use(NoticeBar)
  .use(ActionSheet)
  .use(Cascader)
  .use(Col)
  .use(Row)
  .use(Slider)
  .use(DatePicker)
  .use(Switch)
  .use(Calendar)
  .use(Picker)
  .use(Uploader)
  .use(Tag)
  .use(DropdownMenu)
  .use(DropdownItem)
  .use(Notify)
  .use(ConfigProvider)
  .use(NavBar)
  .use(Area)
  .use(Popover)
  .use(Collapse)
  .use(CollapseItem)
  .use(PickerGroup)
  .use(TimePicker)
  .use(BackTop)
  .use(Progress)
  .use(Tabbar)
  .use(TabbarItem)
  .use(Search)
  .use(FloatingBubble)
  .use(TextEllipsis)
  .use(Step)
  .use(Steps)
  .use(Sticky);

app.use(router);
app.use(store);

app.use(i18n);

app.mount("#app");
