import BaseStore from './base';

export default class UserStore extends BaseStore {
  initState() {
    return {
      name: '管理后台',
      logo: '',
      login: false,
      username: '',
      info: {},
      collapsed: false,
      openMenu: {},
    };
  }

  initAfter() {
    if (this.state.login) this.refreshToken();
  }

  refreshToken() {
    return this.apiPost('/auth/token', { token: this.getToken() })
      .then(result => {
        this.infoHandle(result);
      })
      .catch(() => {
        this.logout(false);
      });
  }

  login({ username, password }) {
    return this.apiPost('/auth/login', { username, password }).then(result => {
      this.infoHandle(result);
    });
  }

  register({ username, password }) {
    return this.apiPost('/auth/register', { username, password }).then(result => {
      this.infoHandle(result);
    });
  }

  infoHandle(result) {
    this.setToken(result.token);
    this.setState({ login: true, info: result, username: result.username });
  }

  editPassword(params) {
    return this.apiPost('/auth/editPassword', params);
  }

  logout(login = true) {
    return Promise.resolve()
      .then(() => {
        if (login) {
          return this.apiPost('/auth/logout', {});
        }
        return true;
      })
      .then(() => {
        this.setState({ login: false, info: {}, username: '' });
      })
      .then(() => {
        linkTo(this.project.loginPath);
      });
  }

  switchCollapse() {
    this.setState({ collapsed: !this.state.collapsed });
  }

  openMenu(mKey, keys) {
    const { openMenu } = this.state;
    openMenu[mKey] = keys;
    this.setState({ openMenu });
  }
}

export const User = new UserStore({ key: 'user', local: true });
