import React, { Component } from 'react';
import { Formik, Form, Field } from 'formik';
import { Toast } from 'antd-mobile';
import { isEmpty } from 'lodash';
import Captcha from '@/common/Captcha';
import { http, getParam } from '@/utils';
import './index.scss';

class BindPhone extends Component {
  captchaInstance = null;

  constructor(props) {
    super(props),
    this.state = {
      validate: '',
      seconds: 60,
      isFirst: true,
      timer: null,
      isTimer: false, // 是否开始倒计时
      accountInfo: {},
      bindInfo: {},
      country: {
        num: '86'
      }
    }
  }

  componentDidMount() {
    this.initCountryInfo();
  }

  initCountryInfo = () => {
    const { country } = this.props;
    this.setState({
      country
    });
  }

  toFetchCountryNum = () => {
    const { history, hideBindPhone } = this.props;
    hideBindPhone();
    history.push('/country?from=bind');
  }

  getCaptchaInstance = instance => {
    this.captchaInstance = instance;
  }

  onVerify = (err, data) => {
    if (err) {
      console.log(err);
    } else {
      this.setState({
        validate: data.validate
      });
    }
  }

  // 获取手机号验证码
  handleToSend = ({tel, code}) => {
    let { validate, seconds, isFirst, isTimer, country: {num = '86'} } = this.state;
    if(validate) {
      if (!isFirst) {
        Toast.info('请重新进行滑块验证', 2, null, false);
        this.captchaInstance.refresh();
        this.setState({
            isFirst: true
        });
        return
      }
      if(!isTimer) {
        if (!tel) {
          Toast.info('手机号码不能为空', 2, null, false);
        }else if(!/^\d+$/.test(tel)) {
          Toast.info('请输入正确格式的手机号码', 2, null, false);
        }else {

          // 获取验证码
          http.post(
            `${API['passport-api']}/m/personal/bindPhoneSendCode`,
            {
              area_code: `00${num}`,
              phone_num: tel
            }
          ).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);

              // 滑块
              this.setState({
                isFirst: false
              })
            }else {
              Toast.info(msg, 2, null, false);
            }
          })
        }
      }
    }
    return false;
  }

  // 绑定手机
  toBindPhone = () => {
    const { accountInfo: { tel, code }, country: {num = '86'}  } = this.state;
    const { handleToConfirmPhone, successBindPhone } = this.props;
    const params = {
      area_code: `00${num}`,
      mobile: tel,
      code: code,
      act_type: 'treasure', // 宝箱
    };
    http.post(
      `${API.home}/sys/v2/user/bindMobile`,
      {  
        ...params,
        type: 1, // 1:绑定,2:修改绑定
        is_valid: 1, // is_valid	是否验证 1:验证(默认),0不验证
      }
    ).then(res => {
      const { code, data, msg } = res.data;
      if(code === 200 ) {
        if(data.tip_info) {
          handleToConfirmPhone(params, data.tip_info);
        }else {
          successBindPhone();
        }
      }else {
        Toast.info(msg, 2, null, false);
      }
    });
  }

  render() {
    const { desc, skip = 'year' } = this.props;
    const { country, validate, isTimer, seconds } = this.state;
    return (
        <Formik
          initialValues={{
            tel: '',
            code: ''
          }}
          validate={({tel, code}) => {
            const errors = {};

            // if (!validateTel(tel)) {
            if(!/^\d+$/.test(tel)) {
              errors.tel = '请填写正确格式的手机号';
            }
            if (!/[0-9]{6}/.test(code)) {
              errors.code = '请输入验证码';
            }

            return errors;
          }}
          onSubmit={(values, { setStatus, setSubmitting }) => {
            this.setState({
              accountInfo: {
                ...values
              }
            });
            this.toBindPhone();
          }}
          render={({values: {tel, code}, errors}) => (
            <Form className="popup-form" data-skip={skip}>
              <h2 className="popup-form__title">绑定手机号</h2>
              {
                desc &&
                <div className="poup-form__desc">{desc}</div>
              }
              <div className="popup-form__item">
                <a className="popup-form__button--num" onClick={this.toFetchCountryNum}>
                  +{country.num}
                  <i className="iconfont iconiconfront-69"/>
                </a>
                <Field
                  name="tel"
                  render={({field}) => {
                    return (
                      <input
                        {...field}
                        className="popup-form__ipt"
                        data-type="tel"
                        type="text"
                        placeholder="请填写手机号"
                      />
                    );
                  }}
                />
              </div>
              <Captcha
                getInstance={this.getCaptchaInstance}
                onVerify={this.onVerify}
              />
              <div className="popup-form__item">
                <Field
                  name="code"
                  render={({field}) => {
                    return (
                      <input
                        {...field}
                        className="popup-form__ipt popup-form__ipt--left"
                        type="text"
                        placeholder="输入验证码"
                      />
                    );
                  }}
                />
                <button
                  className="popup-form__button--code"
                  data-status={(validate && !isTimer)? 'do': ''}
                  type="button"
                  onClick={() => this.handleToSend({tel, code})}
                >
                  {
                    isTimer? `重新发送${seconds}s` : '发送验证码'
                  }
                </button>
              </div>
              <button
                className="popup-form__button--bundle"
                data-status={(tel && code && isEmpty(errors))? 'do': 'done'}
                type="submit"
              >
                完成绑定
              </button>
            </Form>
          )}
        />
    )
  }
}

export default BindPhone;