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

export interface IUserState {
  token: string;
  imToken: string;
  username: string;
  readCoursewareOpenAgreement: boolean;
  avatar: string;
  info: any;
  imUserInfo: any;
  noReadCount: number;
}

export const useUserStore = defineStore('user-store', {
  state: (): IUserState => ({
    token: storage.get(ACCESS_TOKEN, ''),
    imToken: storage.get(IM_TOKEN, ''),
    username: '',
    avatar: '',
    readCoursewareOpenAgreement: true, // 是否阅读协议 备课
    noReadCount: 0, // 未读数量
    info: storage.get(CURRENT_USER, {}),
    imUserInfo: {} // IM
  }),
  getters: {
    getNoReadCount(): number {
      return this.noReadCount;
    },
    getToken(): string {
      // 为了处理课堂乐器后台预览课件的功能
      let Authorization = this.token;
      // 为了处理课堂乐器后台预览课件的功能
      const userAuth = getAuthForAdmin();
      if (userAuth.authSource === 'admin') {
        Authorization = userAuth.Authorization;
      } else {
        Authorization = this.token || '';
      }
      return Authorization;
    },
    getImToken(): string {
      return this.imToken;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getNickname(): string {
      return this.username;
    },
    getUserInfo(): any {
      return this.info;
    },
    getImUserInfo(): any {
      return this.imUserInfo;
    },
    getReadCoursewareOpenAgreement(): boolean {
      return this.readCoursewareOpenAgreement;
    }
  },
  actions: {
    setNoReadCount(count: number) {
      this.noReadCount = count;
    },
    setToken(token: string) {
      this.token = token;
    },
    setImToken(token: string) {
      this.imToken = token;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setUsername(username: string) {
      this.username = username;
    },
    setUserInfo(info: any) {
      this.info = info;
    },
    setImUserInfo(info: any) {
      this.imUserInfo = info;
    },
    setReadCoursewareOpenAgreement(info: any) {
      this.readCoursewareOpenAgreement = info;
    },
    // 登录
    async login(userInfo: any) {
      try {
        const { data } = await userLogin(userInfo);
        const userToken = data.token_type + ' ' + data.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() {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then((res: any) => {
            const result = res.data;
            this.setUserInfo(result);
            this.setAvatar(result.account.avatar);
            this.setUsername(result.nickname);
            this.setReadCoursewareOpenAgreement(
              result.readCoursewareOpenAgreement
            );
            resolve(true);
          })
          .catch((error: any) => {
            reject(error);
          });
      });
    },

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

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