import { useFiltersStore } from "@/store/filter.js";
import axios from "axios";

export default defineNuxtRouteMiddleware((to, from) => {
  const filtersStore = useFiltersStore();
  const getLoginFlag = () => {
    let param = new FormData();
    param.append("grant_type", "refresh_token");
    param.append("refresh_token", filtersStore.getRefreshToken);
    post("v3/frontLogin/oauth/token", param).then(
      (res) => {
        if (res.state == 200) {
          filtersStore.setToken(res.data.access_token);
          filtersStore.setTime(new Date().getTime().toString()); //存储refresh_token更新时间
        }
      },
      (err) => {
        console.log("更新access_token出错：", err);
      }
    );
  };
  if (filtersStore.getRefreshToken  && new Date().getTime() - filtersStore.getTime * 1 > 58 * 60 * 1000) {
    getLoginFlag();
  }
  if (!filtersStore.getLoginFlag) {
    return navigateTo("/login");
  }
});
