import React, { Component } from 'react';
import classnames from 'classnames';
import { Link } from 'react-router-dom';
import { Formik, Form, Field } from 'formik';
import { Toast } from 'antd-mobile';
import { http, getParam } from '@/utils';
import './index.scss';

class BargainBindPhone extends Component {

  constructor(props) {
    super(props);
    this.state = {
      mobile: '',
      code: '',
      num: '86',
      seconds: 60,
      isTimer: false, // 是否开始倒计时
    };
  }

  // 获取短信验证码
  handleToSendCode = ({ mobile }) => {
    const { country: { num = 86 } } = this.props;
    let { isTimer, seconds } = this.state;
    if(!isTimer) {
      if(!/^\d+$/.test(mobile)){
        Toast.info('请输入正确的手机号');
        return;
      }

      // 获取验证码
      http.post(
        `${API['passport-api']}/m/personal/bindPhoneSendCode`,
        {
          area_code: `00${num}`,
          phone_num: mobile
        }
      ).then(res => {
        const { errno, msg } = res.data;
        if(errno === 200) {
          Toast.info('验证码发送成功', 2, null, false);
              
          // 倒计时
          this.timer = window.setInterval(() => {
            if (seconds <= 0) {
              window.clearInterval(this.timer);
              this.setState({
                isTimer: false,
                seconds: 60
              });
            }else {
              this.setState({
                isTimer: true,
                seconds: --seconds
              });
            }
          }, 1000);
        }else {
          Toast.info(msg);
        }
      });
    }
  }

  // 绑定手机号
  handleToBindPhone = ({code, mobile}) => {
    const { country: { num = 86}, handleToBargain, confirmBindPhone } = this.props;
    if (!mobile) {
      Toast.info('请填手机号码');
      return;
    }
    if (!code) {
      Toast.info('请填写验证码');
      return;
    }

    const params = {
      area_code: `00${num}`,
      phone_num: mobile,
      code: code,
    };

    // is_valid	是否验证 1:验证(默认),0不验证
    http.post(
      `${API['passport-api']}/m/personal/bindPhone`,
      {
        ...params,
        type: 1,
        is_valid: 1
      }
    ).then(res => {
      const { errno, data, msg } = res.data;
      if(errno === 200) {
        if(data.tip_info) {
          confirmBindPhone(params, data.tip_info);
        }else {
          handleToBargain();
        }
      }else {
        Toast.info(msg);
      }
    });
  }

  render() {
    const { country: { num = '86' } } = this.props;
    const { isTimer, seconds } = this.state;
    return (
      <Formik
        initialValues={{
          mobile: '',
          code: ''
        }}
        validate={({mobile, code}) => {
          const errors = {};
          if(!/^\d+$/.test(mobile)) {
            errors.mobile = '请填写正确格式的手机号';
          }
          if (!/[0-9]{6}/.test(code)) {
            errors.code = '请输入验证码';
          }
          return errors;
        }}
        onSubmit={(values, { setStatus, setSubmitting }) => {
          this.handleToBindPhone(values);
        }}
        render={({values: {mobile, code}, errors}) => (
          <Form className="bargain-bind-phone">
            <h2 className="bargain-bind-phone__title">绑定手机,先砍一刀</h2>
            <div className="bargain-bind-phone__item">
              <Link
                className="bargain-bind-phone__button--num"
                to={`/country?id=${getParam('id')}&from=bargain`}
              >
                +{num}
                <i className="iconfont iconiconfront-69"></i>
              </Link>
              <Field
                name="mobile"
                render={({field}) => (
                  <input 
                    {...field}
                    className="bargain-bind-phone__ipt"
                    type="tel"
                    placeholder='手机号' 
                    maxLength={11}
                  />
                )}
              />
            </div>
            <div className="bargain-bind-phone__item">
              <Field 
                name="code"
                render={({field}) =>  (
                  <input 
                    {...field}
                    type="tel"
                    placeholder='验证码'
                    maxLength={6}
                  />
                )}
              />
              {errors.mobile}
              <button 
                type="button"
                className={classnames(
                  'bargain-bind-phone__button--send',
                  {
                    'active': mobile && errors.mobile === undefined
                  }
                )}
                disabled={!(mobile && errors.mobile === undefined)}
                onClick={() => this.handleToSendCode({mobile})}
              >
                {isTimer? `重新发送${seconds}s` : '发送验证码'}
              </button>
            </div>
            <button 
              type="submit"
              className="bargain-bind-phone__button--bargain"
              disabled={!(mobile && code && JSON.stringify(errors) === '{}')}
            >先砍一刀</button>
          </Form>
        )}
      />
    )
  }
}

export default BargainBindPhone;