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) {
          window.location.href = window.location.href.replace(`token=${this.adminLogin}`, '').replace('&&', '&');
        }
      });
    }
  }

  needLogin() {
    if (this.state.login) {
      return Promise.resolve();
    }
    return new Promise((resolve, reject) => {
      this.successCB = resolve;
      this.failCB = reject;
      this.setState({ needLogin: true });
    });
  }

  closeLogin(err) {
    this.setState({ needLogin: !!err });
    if (err) {
      if (this.failCB) this.failCB();
    } else if (this.loginCB) this.loginCB();
    this.loginCB = null;
    this.failCB = null;
  }

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

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

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

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

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

  /**
   * 登陆
   * @param {*} mobile 手机号
   * @param {*} mobileVerifyCode 手机验证码
   * @param {*} inviteCode 邀请人手机/邀请码
   * @param {*} email 绑定邮箱
   */
  login(area, mobile, mobileVerifyCode, inviteCode, email) {
    if (!inviteCode) {
      ({ inviteCode } = this.state);
    }
    return this.apiPost('/auth/login', { area, mobile, mobileVerifyCode, inviteCode, email }).then(result => {
      this.infoHandle(result);
      return result;
    });
  }

  loginWechat(code) {
    return this.apiGet('/auth/wechat_pc', { code }).then(result => {
      this.infoHandle(result);
      return result;
    });
  }

  /**
   * 登出
   */
  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 邀请人手机/邀请码
   * @param {*} email 绑定邮箱
   */
  bind(area, mobile, mobileVerifyCode, inviteCode, email) {
    return this.apiPost('/auth/bind', { area, mobile, mobileVerifyCode, inviteCode, email });
  }

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

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

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

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