import { defineStore } from 'pinia';
import { store } from '@/store';
import { ACCESS_TOKEN, CURRENT_USER, IM_TOKEN } from '@/store/mutation-types';
import { storage } from '@/utils/storage';
import { userLogin, getUserInfo } from '@/api/user';

export interface IUserState {
  token: string;
  imToken: string;
  username: string;
  avatar: string;
  info: any;
}

export const useUserStore = defineStore('user-store', {
  state: (): IUserState => ({
    token: storage.get(ACCESS_TOKEN, ''),
    imToken: storage.get(IM_TOKEN, ''),
    username: '',
    avatar: '',
    info: storage.get(CURRENT_USER, {})
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getImToken(): string {
      return this.imToken;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getNickname(): string {
      return this.username;
    },
    getUserInfo(): object {
      return this.info;
    }
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setImToken(token: string) {
      this.imToken = token;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setUserInfo(info: any) {
      this.info = info;
    },
    // 登录
    async login(userInfo: any) {
      try {
        const { data } = await userLogin(userInfo);
        const userToken =
          data.authentication.token_type +
          ' ' +
          data.authentication.access_token;
        const ex = 7 * 24 * 60 * 60 * 1000;
        storage.set(ACCESS_TOKEN, userToken, ex);
        // storage.get(IM_TOKEN, data.imToken);

        this.setToken(userToken);
        // this.setImToken(data.imToken);
        return Promise.resolve();
      } catch (e) {
        return Promise.reject(e);
      }
    },

    // 获取用户信息
    async getInfo() {
      // const that = this;
      return new Promise((resolve, reject) => {
        //   .then(res => {
        //     const result = res.data;
        //     this..setUserInfo(result);
        //     that.setAvatar(result.account.avatar);
        //     resolve(res);
        //   })
        //   .catch(error => {
        //     reject(error);
        //   });
        try {
          // getUserInfo().then((res: any) => {
          //   console.log(res, 'res');
          // });
          resolve(true);
        } catch {
          reject();
        }
      });
    },

    // 登出
    async logout() {
      this.setUserInfo('');
      storage.remove(ACCESS_TOKEN);
      storage.remove(CURRENT_USER);
      return Promise.resolve('');
    }
  }
});

// Need to be used outside the setup
export function useUserStoreWidthOut() {
  return useUserStore(store);
}
