import React, { Component } from 'react';
import { Col, Row, Icon } from 'antd';

class OpenVip extends Component { // eslint-disable-line react/prefer-stateless-function
  state = {
    phone: '',
    type: '',
    current_status: this.props.current_status,
  };

  constructor(props, context) {
    super(props, context);
  }

  checkIsVip() {
    return this.state.current_status;
  }

  handleOpenVip() {
    let title = '升级VIP版';
    let button = '立即升级VIP版';
    let message = '请留下您的联系方式，我们会尽快帮您开通VIP版本！';
    let type = 'vip';

    if (type === 'trial') {
      title = '申请试用VIP版';
      button = '立即申请VIP试用';
      message = '验证手机后即可立刻试用VIP版！';
      type =  'trial';
    } else if type === 'renew' {
      title = '续费VIP版';
      button = '立即续费';
      message = '请留下您的联系方式，我们会尽快帮您开通续费VIP版本！';
      type = 'renew';
    }

    this.setState( { type: type });

    const $cover = $('<div id="guide-cover"></div>');
    const $container = $('<div id="guide-container"></div>');
    const body = `<div class="body">
                    <h2>${title}</h2>
                    <p class="ik-margin-top-5 ik-margin-bottom-5">${message}</p>
                    <div class="ik-margin-bottom-5">
                      <input class="training-input-2 vip-phone" placeholder="请输入正确的手机号">
                    </div>
                    <div class="ik-margin-bottom-5">
                      <button class="training-btn training-btn-w50" id="get_verify_code">获取短信验证码</button>
                    </div>
                    <div class="ik-margin-bottom-15">
                      <input class="training-input-2 validation-code" placeholder="请输入验证码">
                    </div>
                    <div>
                      <button class="training-btn training-btn-2 open-vip-btn">${button}</button>
                      </div>
                    </div>`;

    $container.append($("<div class='close''></div>"));
    $container.append($(body));

    const offset = {
      top: ($(window).height() - $container.height()) / 2,
      left: ($(window).width() - $container.width()) / 2
    };
    $container.css(offset);

    const $topMargin = ($(window).height() - $container.height()) / 2;

    $('body').on('focus', 'input.training-input-2', () => {
      $container.css(top: 10)
    });

    $('body').on('blur', 'input.training-input-2', () => {
      $container.css(top: $topMargin);
    });

    $container.find('.close').click(() => {
      removeHelpGuide();
    })

  }

  goToHelpIndex() {
    window.location.href = '/mobile/help';
  }

  showOpenDialog() {
    const $cover = $("<div id='guide-cover'></div>")
    const $container = $("<div id='vip-container'></div>")
    const body = `<div class='vip-body'>
                    <h2 class='ik-text-center'>提示</h2>
                    <p class='ik-margin-top-5 ik-margin-bottom-5 ik-margin-top-40 ik-font-size-16'>#{message}</p>
                    <div class='vip-content'>
                      <button class='training-btn training-btn-2 close-btn'>确定</button>
                    <div>
                  </div>`;

    $container.append($(body));
    $('body').append($cover);
    $('body').append($container);

    const offset = {
      top: ($(window).height() - $container.height()) / 2,
      left: ($(window).width() - $container.width()) / 2,
    };

    $container.css(offset);
    $container.find('.vip-content').width($container.width() - 28);
    $container.find('.close-btn').click((event) => {
      this.goToHelpIndex();
    })
  }

  openVip(e, phone, code) {
    if(!/^1[3|4|5|7|8][0-9]\d{8}$/.test(phone)) {
      errorNotice('请输入正确的手机号码', 2)
      return false
    }

    if(!/^\d{6}$/.test(code)) {
      errorNotice('请输入正确的验证码', 2)
      return false
    }

    $('.open-vip-btn').addClass('ik-disabled');

    const promise = $.ajax({
      type: 'POST',
      url: '/api/vips/open_vip',
      dataType: 'json',
      data: {
        phone: phone,
        code: code,
        status: this.state.type,
      }
    });

    promise.done((res) => {
      if (res.code == 200) {
        removeHelpGuide()
        message = '';
        if (this.state.type === 'trial') {
          if (res.response_code === '400000') {
            message = '所在的团队已经试用过一次VIP版本了，如希望再次试用，请联系爱客客服：400-867-1101';
          }

          if (res.response_code === '000000') {
            message = "恭喜您，所在团队获得爱客进销存的VIP版试用机会，试用期15天（#{response.date}），立即使用吧！";
          }
        }

        if (this.state.type === 'vip') {
          message = '升级VIP版申请提交成功，我们会尽快和您联系！如有其它问题，请联系爱客客服：400-867-1101';
        }

        if (this.state.type === 'renew') {
          message = '续费申请提交成功！如有其他问题，请联系爱客客服：400-867-1101';
        }

        this.showOpenDialog(message);
      } else {
        errorNotice(res.message);
        $('.open-vip-btn').removeClass('ik-disabled');
      }
    }).fail((err) => {
      errorNotice('提交失败');
      $('.open-vip-btn').removeClass('ik-disabled');
    });
  }

  timeCounter(e, text) {
    const $this = $(e);
    let count = 60;
    $this.text(text + '('+ count.toString() + ')').addClass('ik-disabled');

    const interval = setInterval(() => {
      if (count--) {
        $this.text(text + '('+ count.toString() + ')');
      } else {
        $this.text(text).removeClass('ik-disabled');
        clearInterval(interval);
      }
    } , 1000);
  }

  getVerifyCode(e, phone) {
    if (!/^1[3|4|5|7|8][0-9]\d{8}$/.test(phone)) {
      errorNotice('请输入正确的手机号码', 2);
      return false;
    }

    this.timeCounter($("#get_verify_code"), '获取短信验证码');

    const promise = $.ajax({
      type: 'POST',
      url: '/api/vips/get_verify_code',
      dataType: 'json',
      data: {
        phone: phone,
      }
    });

    promise.done((res) => {
      if (res.code === 200) {
        successNotice(res.message);
      } else {
        errorNotice(res.message);
      }
    }).fail((err) => {
      errorNotice('提交失败');
    });
  }

  componentDidMount() {
    const that = this;

    $('body').on('click', '.open-vip-btn', () => {
      const $phone = $('.vip-phone').val();
      const $code = $('.validation-code').val();
      that.openVip($(this), $phone, $code);
    });

    $('body').on('click', '#get_verify_code', () => {
      that.getVerifyCode($(this), $('.vip-phone').val());
    });
  }

  render() {
    if (this.checkIsVip()) {
      return (
        <Row>
          <IKButtonGroup position="bottom">
            <IKButton IKButton, type="primary" onClick={ this.handleOpenVip.bind(this, 'renew')}>
              续费
            </IKButton>
          </IKButtonGroup>
        </Row>
      );
    } else {
      return (
        <Row>
          <IKButtonGroup position="bottom">
            <IKButton IKButton, type="primary" onClick={ this.handleOpenVip.bind(this, 'trial')}>
              申请试用VIP版
            </IKButton>
            <IKButton IKButton, type="primary" onClick={ this.handleOpenVip.bind(this, 'vip')}>
              升级VIP版
            </IKButton>
          </IKButtonGroup>
        </Row>
      );
    }
  }
}

export default OpenVip;
