import BaseStore from '@src/stores/base';
import * as querystring from 'querystring';

export default class UserStore extends BaseStore {
  constructor(props) {
    super(props);
    this.adminLogin = null;
    const { token } = querystring.parse(window.location.search.replace('?', ''));
    if (token) {
      this.adminLogin = token;
    }
  }

  initState() {
    if (this.adminLogin) this.setToken(this.adminLogin);
    return { login: !!this.adminLogin };
  }

  initAfter() {
    if (this.state.login || this.adminLogin) {
      this.refreshToken().then(() => {
        if (this.adminLogin) {
          this.linkTo(window.location.href.substr(0, window.location.href.indexOf('?') + 1));
        }
      });
    }
  }

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

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

  originInviteCode(inviteCode) {
    this.setState({
      inviteCode,
    });
  }

  /**
   * 设置长难句试用
   */
  sentenceTrail() {
    this.setState({ sentenceTrail: true });
  }

  /**
   * 清除长难句试用
   */
  clearSentenceTrail() {
    this.setState({ sentenceTrail: null });
  }

  /**
   * 验证token
   */
  token() {
    return this.apiPost('/auth/token');
  }

  /**
   * 登陆
   * @param {*} mobile 手机号
   * @param {*} mobileVerifyCode 手机验证码
   * @param {*} inviteCode 邀请人手机/邀请码
   */
  login(mobile, mobileVerifyCode, inviteCode) {
    if (!inviteCode) {
      ({ inviteCode } = this.state);
    }
    return this.apiPost('/auth/login', { mobile, mobileVerifyCode, inviteCode });
  }

  loginWechat(code) {
    return this.apiGet('/auth/wechat_pc', { code }).then(() => {
      this.setState({ login: true });
    });
  }

  /**
   * 登出
   */

  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);
      });
  }

  /**
   * 绑定手机
   * @param {*} mobile 手机号
   * @param {*} mobileVerifyCode 手机验证码
   * @param {*} inviteCode 邀请人手机/邀请码
   */
  bind(mobile, mobileVerifyCode, inviteCode) {
    return this.apiPost('/auth/bind', { mobile, mobileVerifyCode, inviteCode });
  }

  /**
   * 查询邀请码对应账号
   * @param {*} code 邀请码
   */
  validInviteCode(code) {
    return this.apiGet('/auth/valid/invite_code', { code });
  }

  /**
   * 查询手机对应账号
   */
  validMobile(mobile) {
    return this.apiGet('/auth/valid/mobile', { mobile });
  }

  /**
   * 查询手机是否绑定微信
   */
  validWechat(area, mobile) {
    return this.apiGet('/auth/valid/wechat', { area, mobile });
  }
}

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