import React, { Component } from 'react'
import './wechatLogin.scss'
import Input from "../common/Input"
import LoginButton from '../common/LoginButton'
import LoginWays from '../common/LoginWays'
import Header from '../common/Header'
import VeriCodeInput from '../common/veriCodeInput'
import { Form, Field, withFormik } from "formik"
import Captcha from '@/common/Captcha'
import { quickLogin } from '@/store/userAction';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { isEmpty } from 'lodash'
import { Toast } from 'antd-mobile';
import { validateTel } from "@/utils";


class Login extends Component {
    state = {
        validate: null,
        captchaInstance: null
    }

    loginWaysClick = method => {
        const {history, loginWays, location} = this.props

        const item = loginWays.find(item => item.text === method)

        switch (method) {
            case '账号登录':
                history.push('/passport/account-login', location.state)
                break;
            case '微信':
                let {from} = location.state || {from: {pathname: '/'}}

                const redirectURI = window.location.protocol + '//' + window.location.hostname + from.pathname

                // alert(redirectURI)
                window.location.assign(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23dac6775ac82877&redirect_uri=${encodeURIComponent(redirectURI)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`)
                break;
            default:
                window.location.assign(item.url)
        }

    }

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

    render() {
        const {
            loginWays,
            errors,
            values
        } = this.props
        return (
            <div className='login'>
                <Header/>
                <Form className="login-info">
                    <Field
                        name='tel'
                        render={({field}) => (
                            <Input
                                {...field}
                                type={'tel'}
                                placeholder={'手机号快捷登录(免注册)'}
                                wrapperClass={'tel-input'}
                                icon={<i className={'iconfont iconshouji'}
                                         style={{fontSize: '22px', left: '10px'}}
                                />}
                            />
                        )}
                    >
                    </Field>
                    {
                        this.state.validate &&
                        <Field
                            type='number'
                            name='veriCode'
                            render={({field}) => (
                                <VeriCodeInput
                                    {...field}
                                    className={'verification'}
                                    icon={<i className={'iconfont iconduanxin'}
                                             style={{fontSize: '20px', left: '12px'}}
                                    />}
                                    tel={values.tel}
                                    challenge={this.state.validate}
                                    errors={errors}
                                    placeholder={'请输入验证码'}
                                    instance={this.state.captchaInstance}
                                />
                            )}
                        />
                    }
                    <Captcha getInstance={this.getCaptchaInstance}
                             onVerify={this.onVerify}
                    />
                    <LoginButton active={values.tel && values.veriCode && isEmpty(errors)}/>
                </Form>

                <LoginWays onClick={this.loginWaysClick} loginWays={loginWays}/>
            </div>
        )
    }
}

const FormikConfig = {
    mapPropsToValues: () => ({
        tel: '',
        veriCode: ''
    }),
    handleSubmit(values, {props}) {
        props.quickLogin({
            phone_num: values.tel,
            phone_code: values.veriCode
        }).then(res => {
            if (res.hasError) {
                Toast.info(res.msg);
            } else {
                let state = props.location.state || {from: {pathname: '/'}}

                props.history.replace(state.from)
            }
        })
    },
    validateOnChange: true,
    validate: (values) => {
        let errors = {}
        if (!validateTel(values.tel)) {
            errors.tel = '请填写正确格式的手机号'
        }
        if (!/[0-9]{6}/.test(values.veriCode)) {
            errors.veriCode = '请输入验证码'
        }
        return errors
    }
}

export default compose(
    connect(
        null,
        {quickLogin}
    ),
    withFormik(FormikConfig),
)(Login)