import { store } from "@/store";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { useDictStoreHook } from "@/store/modules/dict";

import AuthAPI, { type loginRequest } from "@/api/account/login";
import ShopApi from "@/api/account/shop";
import UserAPI, { type UserInfo } from "@/api/system/user";

import { setToken, setRefreshToken, getRefreshToken, clearToken } from "@/utils/auth";

export const useUserStore = defineStore("user", () => {
  // const isShopAdmin = ref(false) // 0商户 1员工
  const isShopAdmin = useStorage("isShopAdmin", false) // 0商户 1员工
  const isAdmin = useStorage("isAdmin", false) // 是否是管理员
  const userInfo = useStorage<UserInfo>("userInfo", {} as UserInfo);
  const promissionList = useStorage<string[]>("promissionList", [] as string[]);
  //美团抖音核销店铺信息
  const meituan_douyin_info = useStorage<any>("meituan_douyin_info", {});


  localStorage.setItem("shopId", "" + userInfo.value.shopId);
  if (userInfo.value.shopId) {
    getUserInfo()
  }
  /**
   * 登录
   *
   * @param {loginRequest}
   * @returns
   */
  function login(loginRequest: loginRequest) {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.login(loginRequest)
        .then((data) => {
          isShopAdmin.value = data.loginType == 0 ? true : false;
          isAdmin.value = data.shopInfo.id == 1 ? true : false
          Object.assign(userInfo.value, { ...data.shopInfo, shopId: data.shopInfo.id });
          promissionList.value = data.promissionList;
          const token = data.tokenInfo.tokenValue;
          setToken(token);
          setRefreshToken(token);
          localStorage.setItem("shopId", "" + data.shopInfo.id);
          localStorage.setItem("branch_shopId", data.shopInfo.id)
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 获取用户信息
   *
   * @returns {UserInfo} 用户信息
   */
  function getUserInfo(shopId?: string | number) {
    return new Promise<UserInfo>((resolve, reject) => {
      ShopApi.get({ id: shopId || userInfo.value.shopId })
        .then((data) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }
          console.log(userInfo)
          console.log(data)
          localStorage.setItem("shopId", "" + data.id);
          Object.assign(userInfo.value, { ...data, roles: [], promissionList: [], shopId: data.id });
          resolve(userInfo.value);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 登出
   */
  function logout() {
    return new Promise<void>((resolve, reject) => {
      clearUserData();
      resolve();
      // AuthAPI.logout()
      //   .then(() => {
      //     clearUserData();
      //     resolve();
      //   })
      //   .catch((error) => {
      //     reject(error);
      //   });
    });
  }

  /**
   * 刷新 token
   */
  function refreshToken() {
    const refreshToken = getRefreshToken();
    return new Promise<void>((resolve, reject) => {
      // AuthAPI.refreshToken(refreshToken)
      //   .then((data) => {
      //     const { token } = data;
      //     setToken(token);
      //     setRefreshToken(refreshToken);
      //     resolve();
      //   })
      //   .catch((error) => {
      //     console.log(" refreshToken  刷新失败", error);
      //     reject(error);
      //   });
    });
  }

  /**
   * 清理用户数据
   *
   * @returns
   */
  function clearUserData() {
    return new Promise<void>((resolve) => {
      userInfo.value = {} as UserInfo
      meituan_douyin_info.value = {}
      isShopAdmin.value = false
      isAdmin.value = false
      clearToken();
      usePermissionStoreHook().resetRouter();
      useDictStoreHook().clearDictionaryCache();

      let loginType = localStorage.getItem('loginType')

      localStorage.clear()

      localStorage.setItem('loginType', loginType)

      window.location.reload()

      resolve();
    });
  }

  return {
    isShopAdmin, isAdmin,
    meituan_douyin_info,
    userInfo,
    promissionList,
    getUserInfo,
    login,
    logout,
    clearUserData,
    refreshToken,
  };
});

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
  return useUserStore(store);
}
