import React, { Component } from 'react'
import { Form, Input, Modal, Spin, Steps, Button, Row, Col, message as Message, Select } from 'antd'
import { AntIcon } from 'components'
import { api } from 'common/api'
import { COUNT_DWON_KEY } from 'common/storage'
import store from 'store'
import { cloneDeep } from 'lodash'

const { getState } = store

const steps = [
    {
        title: '验证',
    },
    {
        title: '绑定',
    },
]

const reg = /^([a-zA-Z]|[0-9])(\w|)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/

const initState = {
    visible: false,
    loading: false,

    // 可用于验证的类型
    types: [],
    // 当前步骤
    currentStep: 0,

    nextDisabled: true,
    // 正在发送验证码
    sendingCode: false,
    // 冷却时间
    countDown: 0,
}

export default class form extends Component {
    state = cloneDeep(initState)

    form = React.createRef()

    orgCode = ''

    //打开窗口
    open = () => {
        this.setState({ visible: true })

        this.showCountDown()

        const data = getState('user')
        const types = []
        data.phone &&
            types.push({
                title: `使用手机号${data.phone}进行验证`,
                value: 1,
            })
        data.email &&
            types.push({
                title: `使用邮箱${data.email}进行验证`,
                value: 2,
            })

        this.setState({ types })
    }

    close() {
        this.setState(cloneDeep(initState))
    }

    /**
     * 将倒计时添加入到本地
     */
    addTime() {
        const now = Date.now() + 60 * 1000
        window.localStorage.setItem(COUNT_DWON_KEY, now)
    }
    /**
     * 显示倒计时
     */
    showCountDown() {
        const surplusTime = window.localStorage.getItem(COUNT_DWON_KEY)
        const nowTime = Date.now()
        if (surplusTime >= nowTime) {
            this.setState({
                countDown: parseInt((surplusTime - nowTime) / 1000),
            })
            setTimeout(() => {
                this.showCountDown()
            }, 1000)
        } else {
            this.setState({ countDown: 0 })
        }
    }

    //发送验证码
    async onSendCode() {
        const form = this.form.current

        const valid = await form.validateFields()
        if (!valid) {
            return
        }

        this.setState({ sendingCode: true })

        const data = form.getFieldsValue()
        try {
            await api.sysUserSendCode(data)
            const typeName = data.type ? [, '手机', '邮箱'][data.type] : '邮箱'
            Message.success(`已发送验证码到${typeName}，请注意查收`)
            this.addTime()
            this.showCountDown()
        } finally {
            this.setState({ sendingCode: false })
        }
    }

    // 下一步
    async onNext() {
        this.setState({ loading: true })
        const data = this.form.current.getFieldsValue()
        this.orgCode = data.orgCode

        try {
            await api.sysUserCheckBindcode(data)
            window.localStorage.removeItem(COUNT_DWON_KEY)
            this.setState({
                nextDisabled: true,
                currentStep: this.state.currentStep + 1,
            })
        } finally {
            this.setState({ loading: false })
        }
    }

    // 上一步
    onPrev() {
        window.localStorage.removeItem(COUNT_DWON_KEY)
        this.setState({
            currentStep: this.state.currentStep - 1,
        })
    }

    //完成
    async onComplete() {
        this.setState({ loading: true })
        try {
            await api.sysUserCheckBindcode({
                ...this.form.current.getFieldsValue(),
                orgCode: this.orgCode,
            })
            await this.props.loadData()
            window.localStorage.removeItem(COUNT_DWON_KEY)
            Message.success('绑定邮箱成功')
            this.close()
        } finally {
            this.setState({ loading: false })
        }
    }

    renderForm() {
        const { nextDisabled, sendingCode, countDown } = this.state

        return (
            <div className="yo-form-group">
                <Form
                    ref={this.form}
                    onValuesChange={(changedValues, allValues) => {
                        this.setState({
                            nextDisabled: !(allValues.target && allValues.code),
                        })
                    }}
                >
                    <Form.Item
                        label="邮箱"
                        name="target"
                        required={false}
                        rules={[
                            { required: true, message: '请输入邮箱' },
                            { pattern: reg, message: '邮箱格式错误' },
                        ]}
                    >
                        <Input autoComplete="off" placeholder="请输入邮箱" />
                    </Form.Item>
                    <Form.Item label="验证码">
                        <Row gutter={16} align="middle">
                            <Col flex="1">
                                <Form.Item name="code" noStyle>
                                    <Input autoComplete="off" placeholder="请输入验证码" />
                                </Form.Item>
                            </Col>
                            <Col>
                                {countDown ? (
                                    <Button disabled>{countDown}秒后重新发送</Button>
                                ) : (
                                    <Button onClick={() => this.onSendCode()} loading={sendingCode}>
                                        发送验证码
                                    </Button>
                                )}
                            </Col>
                        </Row>
                    </Form.Item>
                </Form>
                <div className="text-center pt-md pb-md">
                    <Button
                        disabled={nextDisabled}
                        onClick={() => this.onComplete()}
                        type="primary"
                    >
                        绑定
                    </Button>
                </div>
            </div>
        )
    }

    renderStepForm() {
        const { types, currentStep, sendingCode, countDown } = this.state

        return (
            <div className="yo-form-group">
                <Row>
                    <Col span={12} offset={6} className="pt-md pb-md">
                        <Steps current={currentStep}>
                            {steps.map(item => (
                                <Steps.Step key={item.title} title={item.title} />
                            ))}
                        </Steps>
                    </Col>
                </Row>
                <Form
                    ref={this.form}
                    onValuesChange={(changedValues, allValues) => {
                        this.setState({
                            nextDisabled: !(
                                allValues.orgCode ||
                                (allValues.target && allValues.code)
                            ),
                        })
                    }}
                >
                    {currentStep === 0 && (
                        <>
                            <Form.Item
                                label="选择验证方式"
                                name="type"
                                required={false}
                                rules={[{ required: true, message: '请选择一种验证方式' }]}
                            >
                                <Select placeholder="请选择验证方式">
                                    {types.map(item => (
                                        <Select.Option key={item.value} value={item.value}>
                                            {item.title}
                                        </Select.Option>
                                    ))}
                                </Select>
                            </Form.Item>
                            <Form.Item label="验证码">
                                <Row gutter={16}>
                                    <Col flex="1">
                                        <Form.Item name="orgCode" noStyle>
                                            <Input autoComplete="off" placeholder="请输入验证码" />
                                        </Form.Item>
                                    </Col>
                                    <Col>
                                        {countDown ? (
                                            <Button disabled>
                                                {countDown}
                                                秒后重新发送
                                            </Button>
                                        ) : (
                                            <Button
                                                onClick={() => this.onSendCode()}
                                                loading={sendingCode}
                                            >
                                                发送验证码
                                            </Button>
                                        )}
                                    </Col>
                                </Row>
                            </Form.Item>
                        </>
                    )}
                    {currentStep === 1 && (
                        <>
                            <Form.Item
                                label="新邮箱"
                                name="target"
                                required={false}
                                rules={[
                                    { required: true, message: '请输入邮箱' },
                                    { pattern: reg, message: '邮箱格式错误' },
                                ]}
                            >
                                <Input autoComplete="off" placeholder="请输入邮箱" />
                            </Form.Item>
                            <Form.Item label="验证码">
                                <Row gutter={16}>
                                    <Col flex="1">
                                        <Form.Item name="code" noStyle>
                                            <Input autoComplete="off" placeholder="请输入验证码" />
                                        </Form.Item>
                                    </Col>
                                    <Col>
                                        {countDown ? (
                                            <Button disabled>
                                                {countDown}
                                                秒后重新发送
                                            </Button>
                                        ) : (
                                            <Button
                                                onClick={() => this.onSendCode()}
                                                loading={sendingCode}
                                            >
                                                发送验证码
                                            </Button>
                                        )}
                                    </Col>
                                </Row>
                            </Form.Item>
                        </>
                    )}
                </Form>
                <div className="text-center pt-md pb-md">
                    {currentStep === 0 && (
                        <>
                            <Button
                                onClick={() => this.onNext(this.form)}
                                type="primary"
                                disabled={this.state.nextDisabled}
                            >
                                下一步，绑定
                            </Button>
                        </>
                    )}
                    {currentStep === 1 && (
                        <>
                            <Button onClick={() => this.onPrev()} className="mr-sm">
                                上一步，验证
                            </Button>
                            <Button
                                disabled={this.state.nextDisabled}
                                onClick={() => this.onComplete()}
                                type="primary"
                            >
                                完成
                            </Button>
                        </>
                    )}
                </div>
            </div>
        )
    }

    render() {
        const { visible, loading, types } = this.state

        return (
            <Modal
                destroyOnClose
                footer={false}
                onCancel={() => this.close()}
                visible={visible}
                className="yo-modal-form"
                title="绑定邮箱"
            >
                <Spin spinning={loading} indicator={<AntIcon type="loading" />}>
                    <div className="yo-form">
                        {types.length ? this.renderStepForm() : this.renderForm()}
                    </div>
                </Spin>
            </Modal>
        )
    }
}
