import React, { Component } from 'react';
import './binding-tel.scss'
import { withFormik, Field, Form } from "formik";
import { validateTel, http, api, 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 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
        } = 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'}
                                        icon={<i className={'iconfont iconshouji'}
                                                 style={{fontSize: '22px', left: '11px'}}
                                        />}
                                    />

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

                                )
                            }}
                        />
                        <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 (!validateTel(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'),
            plat: 5
        }).then(res => {
            const data = res.data

            if (data.errno == 200) {

                if (data.data['is_set_pwd']) {
                    props.setCurrentUser({
                        hasError: false,
                        data: {
                            uid: data.data.uid
                        },
                        msg: data.data.msg
                    })
                    props.history.replace(`/passport/set-password`)
                }else {
                    location.assign(data.data['jump_url'])
                }


            } else {
                Toast.info(data.msg, 2, null, false)
            }

            /*props.setCurrentUser({
                hasError,
                data
            })*/
        })
    }
}
export default compose(
    connect(
        null,
        {setCurrentUser}
    ),
    withFormik(formikConfig),
)(BindingTel);