import React, { Component } from 'react'
import './forgot-password.scss'
import VeriCodeInput from '../common/veriCodeInput'
import Button from '../common/Button'
import { withFormik, Form, Field } from 'formik';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { Toast } from "antd-mobile";
import { HeaderBar, Captcha, ClearableInput } from "@/common";
import { validateTel, validateEmail, http, api } from "@/utils";
import { quickLogin } from '@/store/userAction';
import { isEmpty } from "lodash";


class ForgotPassword 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 (
            <div className={'forgot-password'}>
                <HeaderBar title='忘记密码'/>
                <div className="content">
                    <Form className='forgot-password-form'>
                        <Field
                            name={'account'}
                            render={({field, form}) => {
                                return (
                                    <ClearableInput
                                        {...field}
                                        type={'tel'}
                                        placeholder={'请输入注册时的邮箱账号或手机号'}
                                        wrapperClass={'tel-input'}
                                        setFieldValue={form.setFieldValue}
                                        icon={<i className={'iconfont iconshouji'}
                                                 style={{fontSize: '22px', left: '11px'}}
                                        />}
                                    />)
                            }}
                        />
                        {
                            this.state.validate &&
                            <Field
                                name='veriCode'
                                render={({field}) => {
                                    return (
                                        <VeriCodeInput
                                            {...field}
                                            className={'verify-code'}
                                            icon={<i className={'iconfont iconduanxin'}
                                                     style={{fontSize: '20px', left: '12px'}}
                                            />}
                                            account={values.account}
                                            challenge={this.state.validate}
                                            instance={this.state.captchaInstance}
                                        />
                                    )
                                }}
                            />
                        }
                        <Captcha getInstance={this.getCaptchaInstance} onVerify={this.onVerify}/>
                        <Button active={values.account && values.veriCode && isEmpty(errors)}>下一步</Button>
                    </Form>
                </div>
            </div>
        );
    }

}


const formikConfig = {
    mapPropsToValues: () => ({
        account: '',
        veriCode: ''
    }),
    validateOnchange: true,
    validate: values => {
        let errors = {}
        if (!validateTel(values.account) && !validateEmail(values.account)) {
            errors.account = '请输入正确的手机号或邮箱地址'
        }
        return errors
    },
    handleSubmit(values, {props}) {


        let account, address

        if (validateEmail(values.account)) {
            account = 'email'
            address = 'check_email_code'
            sessionStorage.setItem('r_type', 'email')
            sessionStorage.setItem('email', values.account)
        } else {
            account = 'phone_num'
            address = 'check_phone_code'
            sessionStorage.setItem('r_type', 'phone')
            sessionStorage.setItem('tel', values.account)
        }

        http.post(`${api['passport-api']}/${address}`, {
            [account]: values.account,
            code: values.veriCode
        }).then(res => {
            if (res.data.errno == 0) {
                props.history.push('/passport/set-password', {from: props.location})
            } else {
                Toast.info(res.data.msg)
            }
        })
    },

}

export default compose(
    connect(
        null,
        {quickLogin}
    ),
    withFormik(formikConfig)
)(ForgotPassword)