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

export default class UserStore extends BaseStore {
  initState() {
    // const { code } = querystring.parse(window.location.search.replace('?', ''));
    // if (code) {
    //   this.loginWechat(code);
    // }
    return { login: false };
  }

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

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

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

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

  /**
   * 登出
   */
  logout() {
    return this.apiPost('/auth/logout');
  }

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

  /**
   * 查询邀请码对应账号
   * @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 });