import BaseStore from '@src/stores/base';
import * as querystring from 'querystring';
import { getMap } from '@src/services/Tools';
// import * as querystring from 'querystring';

import { ServiceParamMap, OrderInfoMap, ServiceKey } from '../../Constant';

const ServiceParamRelation = getMap(
  Object.keys(ServiceParamMap).map(key => {
    return {
      map: getMap(
        ServiceParamMap[key].map((row, index) => {
          row.index = index;
          return row;
        }),
        'value',
        'index',
      ),
      key,
    };
  }),
  'key',
  'map',
);
function formatTitle(record) {
  if (record.productType === 'course_package') {
    return (record.coursePackage || {}).title;
  }
  if (record.productType === 'course') {
    record.minNumber = record.course.minNumber;
    record.maxNumber = record.course.maxNumber;
    return (record.course || {}).title;
  }
  if (record.productType === 'data') {
    return (record.data || {}).title;
  }
  if (record.productType === 'service') {
    return record.info.label || (record.serviceInfo || {}).title;
  }
  return '';
}
function formatGift(record) {
  let gift = null;
  if (record.productType === 'course_package') {
    ({ gift } = record.coursePackage || {});
  }
  if (!gift) return null;
  return ServiceKey.map(row => {
    if (!gift[row.value]) return null;
    const list = ServiceParamMap[row.value];
    if (list) {
      const map = getMap(list, 'value');
      return Object.assign({ param: map[gift[row.value]] }, map[gift[row.value]], row);
    }
    return Object.assign({ number: gift[row.value] }, row);
  }).filter(row => row);
}
function formatCheckout(checkouts) {
  checkouts.forEach(checkout => {
    checkout.key = checkout.id;
    checkout.info = OrderInfoMap[checkout.productType];
    if (checkout.productType === 'service') {
      const index =
        (ServiceParamRelation[checkout.service] && ServiceParamRelation[checkout.service][checkout.param]) || 0;
      checkout.info = Object.assign({}, checkout.info[checkout.service], checkout.serviceInfo.package[index]);
    }
    checkout.title = formatTitle(checkout);
    checkout.gift = formatGift(checkout);
    if (checkout.children) formatCheckout(checkout.children);
  });
}
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, needPay: false, needLogin: false };
  }

  fixState() {
    return { needPay: false, needLogin: false };
  }

  initAfter() {
    if (this.adminLogin || this.state.login) {
      this.refreshToken().then(() => {
        // if (this.adminLogin) {
        //   window.location.href = window.location.href.replace(`token=${this.adminLogin}`, '').replace('&&', '&');
        // }
      }).catch((e) => {
        console.log(e);
      });
    }
  }

  needPay(order) {
    return new Promise((resolve, reject) => {
      this.successCB = resolve;
      this.failCB = reject;
      formatCheckout(order.checkouts);
      this.setState({ needPay: true, order });
    });
  }

  formatCheckout(record) {
    formatCheckout(record);
  }

  formatOrder(order) {
    formatCheckout(order.checkouts);
  }

  closePay(err) {
    this.setState({ needPay: false });
    if (err) {
      if (this.failCB) this.failCB();
    } else if (this.successCB) this.successCB();
    this.successCB = null;
    this.failCB = null;
  }

  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: false });
    if (err) {
      if (this.failCB) this.failCB();
    } else if (this.successCB) this.successCB();
    this.successCB = null;
    this.failCB = null;
  }

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

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

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

  addSearch(keyword) {
    const { searchHistoryList = [] } = this.state;
    searchHistoryList.unshift(keyword);
    searchHistoryList.splice(5);
    this.setState({ searchHistoryList });
  }

  removeSearchIndex(index) {
    const { searchHistoryList = [] } = this.state;
    searchHistoryList.splice(index, 1);
    this.setState({ searchHistoryList });
  }

  clearSearch() {
    this.setState({ searchHistoryList: [] });
  }

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

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

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

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

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

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

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

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

  /**
   * 查询邮箱对应账号
   */
  validEmail(email) {
    return this.apiGet('/auth/valid/email', { email });
  }

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

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