import { defineStore } from "pinia";
import { USER_INFO, TOKEN, OPEN_ID, REDIRECT_KEY, USER_PHONE } from "@/settings/enums.js";

export const useUserStore = defineStore({
  id: "app-user",
  state: () => ({
    userInfo: null,
    token: undefined,
    siteId: undefined,
    openId: undefined,
  }),
  getters: {
    getUserInfo() {
      return this.userInfo || uni.getStorageSync(USER_INFO) || {};
    },
    getToken() {
      return this.token || uni.getStorageSync(TOKEN) || "";
    },
    getOpenId() {
      return this.openId || uni.getStorageSync(USER_INFO)?.openId || "";
    },
    getPhone() {
      const info = this.userInfo || uni.getStorageSync(USER_INFO) || {};
      return info.phone ?? info.mobile ?? info.contactPhone ?? uni.getStorageSync(USER_PHONE) ?? "";
    },
  },
  actions: {
    // 修改用户信息
    setUserInfo(e) {
      this.userInfo = e;
      uni.setStorageSync(USER_INFO, e);
    },
    // 登录（含微信授权手机号时一并缓存）
    login(e) {
      this.userInfo = e;
      this.token = e.token;
      this.siteId = e.siteId;
      uni.setStorageSync(TOKEN, e.token);
      uni.setStorageSync(USER_INFO, e);
      const phone = e.phone ?? e.mobile ?? e.contactPhone ?? "";
      if (phone) uni.setStorageSync(USER_PHONE, phone);
      setTimeout(() => {
        uni.showToast({
          title: "登录成功",
          duration: 1000,
        });
      });
    },

    // 退出之前的操作
    beforeLogout() {
      uni.showModal({
        title: "提示",
        content: "确定退出登录吗？",
        confirmText: "确定",
        success: (res) => {
          if (res.confirm) {
            this.logout();
          } else if (res.cancel) {
          }
        },
      });
    },

    // 退出登录
    async logout(option = {}) {
      const options = {
        redirct: true,
        ...option,
      };
      try {
        const keys = [USER_INFO, TOKEN, USER_PHONE];
        await Promise.all(keys.map((key) => uni.removeStorageSync(key))).then(
          () => {
            this.userInfo = null;
            this.token = "";
            options.redirct &&
              uni.reLaunch({
                url: "/pages/index/index",
              });
          }
        );

        return Promise.resolve();
      } catch (e) {
        console.log("eeee login", e);
        //TODO handle the exception
      }
    },
  },
});
