import type { providerType, UserState } from './types';
import type { LoginReq } from '@/api/user/types';
import { defineStore } from 'pinia';
import { UserApi } from '@/api';
import { refreshToken, type UserInfo } from '@/api/auth';

import { clearToken, setToken } from '@/utils/auth';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    user_id: '',
    user_name: '江阳小道',
    avatar: '',
    token: '',
  }),
  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },
  actions: {
    // 设置用户的信息
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },
    // 重置用户信息
    resetInfo() {
      this.$reset();
    },
    // 获取用户信息
    async info() {
      const result = await UserApi.profile();
      this.setInfo(result);
    },
    // 异步登录并存储token
    login(loginForm: LoginReq) {
      return new Promise((resolve, reject) => {
        UserApi.login(loginForm).then((res) => {
          const token = res.token;
          if (token) {
            setToken(token);
          }
          resolve(res);
        }).catch((error) => {
          reject(error);
        });
      });
    },
    // Logout
    async logout() {
      await UserApi.logout();
      this.resetInfo();
      clearToken();
    },
    // 小程序授权登录
    authLogin(provider: providerType = 'weixin') {
      return new Promise((resolve, reject) => {
        uni.login({
          provider,
          success: async (result: UniApp.LoginRes) => {
            if (result.code) {
              const res = await UserApi.loginByCode({ code: result.code });
              resolve(res);
            }
            else {
              reject(new Error(result.errMsg));
            }
          },
          fail: (err: any) => {
            console.error(`login error: ${err}`);
            reject(err);
          },
        });
      });
    },
    // 刷新 Token
    async refreshToken() {
      const refresh_token = uni.getStorageSync('refresh_token');
      if (!refresh_token) {
        throw new Error('No refresh token available');
      }

      try {
        const res = await refreshToken(refresh_token);
        const rawUserInfo = uni.getStorageSync('user_info');
        const cachedUserInfo = rawUserInfo && typeof rawUserInfo === 'object'
          ? rawUserInfo as Partial<UserInfo>
          : {};
        const cachedButtons = Array.isArray(cachedUserInfo.buttons) ? cachedUserInfo.buttons : [];
        const sessionUser = {
          ...cachedUserInfo,
          ...res.user,
          buttons: Array.isArray(res.buttons) ? res.buttons : cachedButtons,
        };
        // 更新 access_token
        setToken(res.access_token);
        // 更新 refresh_token
        uni.setStorageSync('refresh_token', res.refresh_token);
        // 更新用户信息
        uni.setStorageSync('user_info', sessionUser);
        return res;
      }
      catch (error) {
        // 刷新失败，清除登录状态
        clearToken();
        uni.removeStorageSync('refresh_token');
        uni.removeStorageSync('user_info');
        throw error;
      }
    },
  },
  persist: true,
});

export default useUserStore;
