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 } from "@/common";
import ClearableInput from '../common/clearableInputWithCountryCodes'
import { http } from "@/utils";
import { quickLogin } from '@/store/userAction';
import OnSubmissionError from '../common/OnSubmissionError'
import { Link } from "react-router-dom";


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
            })
        }
    }
    onSubmissionError = () => {
        const errors = Object.values(this.props.errors);
        errors.length && Toast.info(errors[0], 2, null, false)
    }

    render() {
        const {
            values,
            isValid,
            country
        } = this.props
        return (
            <div className={'forgot-password'}>
                <HeaderBar title='忘记密码' arrow={true}/>
                <div className="content">
                    <Form className='forgot-password-form'>
                        <Field
                            name={'tel'}
                            render={({field, form}) => {
                                return (
                                    <ClearableInput
                                        {...field}
                                        type={'tel'}
                                        placeholder={'请输入注册时的手机号'}
                                        wrapperClass={'tel-input'}
                                        setFieldValue={form.setFieldValue}
                                        country={country}
                                    />)
                            }}
                        />
                        {
                            this.state.validate &&
                            <Field
                                name='veriCode'
                                render={({field}) => {
                                    return (
                                        <VeriCodeInput
                                            {...field}
                                            className={'verify-code'}
                                            icon={<i className={'iconfont iconduanxin'}
                                                     style={{fontSize: '20px', left: '12px'}}
                                            />}
                                            tel={values.tel}
                                            challenge={this.state.validate}
                                            instance={this.state.captchaInstance}
                                            action={'auth'}
                                            checking={1}
                                            country={country}
                                        />
                                    )
                                }}
                            />
                        }
                        <OnSubmissionError callback={this.onSubmissionError}/>
                        <Captcha getInstance={this.getCaptchaInstance} onVerify={this.onVerify}/>
                        <Button className={'next_step'} active={isValid}>下一步</Button>
                        <Link className={'to-email'} to={`/passport/forgot-password-email`} replace>邮箱找回</Link>
                    </Form>
                </div>
            </div>
        );
    }

}


const formikConfig = {
    mapPropsToValues: () => ({
        tel: '',
        veriCode: ''
    }),
    validateOnChange: true,
    validateOnBlur: true,
    validate: values => {
        let errors = {}
        if (!/\d/.test(values.tel)) {
            errors.tel = '请输入正确的手机号'
        }
        values.veriCode.toString().length !== 6 && (errors.veriCode = '验证码格式不正确')
        return errors
    },
    handleSubmit(values, {props}) {
        sessionStorage.setItem('r_type', 'phone')
        sessionStorage.setItem('tel', values.tel)
        http.post(`${API['passport-api']}/check_phone_code`, {
            phone: values.tel,
            code: values.veriCode,
            area_code: '00'+props.country.num
        }).then(res => {
            if (res.data.errno == 0) {
                props.history.push('/passport/set-password', {from: props.location})
            } else {
                Toast.info(res.data.msg, 2, null, false)
            }
        })
    },

}

export default compose(
    connect(
        state => ({country: state.country}),
        {quickLogin}
    ),
    withFormik(formikConfig)
)(ForgotPassword)