import React, { Component } from 'react'
import './binding-tel.scss'
import { withFormik, Field, Form } from "formik"
import { http, getParam } from "@/utils"
import { compose } from "redux"
import { connect } from "react-redux"
import { setCurrentUser } from "@/store/userAction"
import Captcha from '@/common/Captcha'
import { HeaderBar } from '@/common'


// import ClearableInput from '@common/ClearableInput'
import ClearableInput from '../common/clearableInputWithCountryCodes'
import Button from '../common/Button'
import VeriCodeInput from '../common/veriCodeInput'
import { Toast } from "antd-mobile"
import { isEmpty } from "lodash"

class BindingTel extends Component {


  state = {
    validate: null,
    captchaInstance: null
  }

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


  render() {
    const {
      values,
      errors,
      country
    } = this.props
    return (
      <>
        <HeaderBar title={'绑定手机号'} arrow={true}/>
        <div className={'binding-tel'}>
          <p className={'title'}>为提高您的账号安全,请绑定手机号</p>
          <Form>
            <Field
              name='tel'
              render={({field, form}) => {
                return (
                  <ClearableInput
                    {...field}
                    setFieldValue={form.setFieldValue}
                    placeholder={'请输入需要绑定的手机号'}
                    wrapperClass={'tel'}
                    country={country}
                  />

                )
              }}
            />
            <Field
              name='veriCode'
              render={({field}) => {
                return (
                  <VeriCodeInput
                    {...field}
                    className={'verification'}
                    icon={<i className={'iconfont iconduanxin'}
                             style={{fontSize: '20px', left: '12px'}}
                    />}
                    placeholder={'验证码'}
                    account={values.tel}
                    tel={values.tel}
                    challenge={this.state.validate}
                    instance={this.state.captchaInstance}
                    action={'auth'}
                    country={country}
                  />

                )
              }}
            />
            <Captcha onVerify={this.onVerify} getInstance={this.getCaptchaInstance}/>
            <Button className={'complete-btn'}
                    active={values.tel && values.veriCode && isEmpty(errors)}>完成</Button>
          </Form>
        </div>
      </>
    )
  }
}


const formikConfig = {
  mapPropsToValues() {
    return {
      tel: '',
      veriCode: ''
    }
  },
  validateOnChange: true,
  validate(values) {
    let errors = {}
    if (!/\d/.test(values.tel)) {
      errors.tel = '请输入正确的手机号'
    }
    if (!values.veriCode) {
      errors.veriCode = '请填写验证码'
    }
    return errors
  },
  handleSubmit(values, {props}) {
    http.post(`${API['passport-api']}/bind_mobile`, {
      phone_num: values.tel,
      phone_code: values.veriCode,
      mkey: getParam('mkey'),
      area_code: '00' + props.country.num,
      plat: 5
    }).then(res => {
      const data = res.data
      if (data.errno == 200) {
        if (data.data['is_set_pwd']) {
          const {history} = props
          history.replace(`/passport/set-password`, {
            user: {
              hasError: false,
              data: {
                uid: data.data.uid
              },
              msg: data.data.msg,
              stage: 'binding'
            }
          })
        } else {
          location.assign(data.data['jump_url'])
        }


      } else {
        Toast.info(data.msg, 2, null, false)
      }
    })
  }
}
export default compose(
  connect(
    state => ({country: state.country}),
    {setCurrentUser}
  ),
  withFormik(formikConfig),
)(BindingTel)