import { defineStore } from 'pinia';
import { login, getInfo } from '../../base/api/login';
import { kuky_Authorization } from '../storage';

/**
 * 当前登录的用户信息
 */
export const useCurrentUserStore = defineStore('current_user', {
  state: () => {
    return {
      name: 'Jack',
      token_type: '',
      token: kuky_Authorization.get(),
      username: '',
      nickname: '',
      dept: [],
      roles: [],
      permissions: [],
      user: {}
    };
  },
  actions: {
    updateName(name) {
      this.name = name;
    },
    toLogin(data) {
      const { username, password } = data;
      return new Promise((resolve, reject) => {
        login({ username, password })
          .then((res) => {
            if (res.code == 200 && res.data.access_token.length) {
              this.token = res.data.access_token;
              this.token_type = res.data.token_type;
              this.username = res.data.username;
              this.nickname = res.data.nickname;
              kuky_Authorization.set(res.data.access_token);
              resolve(res.msg);
              /**
               * 获取用户信息
               * 暂时先在这里去调用，后续可以考虑放在路由拦截中去调用
               */
              this.getInfo();
            } else {
              reject(res.msg);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            if (res.code == 200) {
              this.dept = res.data.dept;
              if (res.roles && res.roles.length > 0) {
                // 验证返回的roles是否是一个非空数组
                this.roles = res.roles;
                this.permissions = res.permissions;
              } else {
                this.roles = ['ROLE_DEFAULT'];
              }
              resolve(res.msg);
            } else {
              reject(res.msg);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    }
  }
});
