import React, { Component } from 'react'
import { Alert, Button, Form, Input, message as Message, Modal } from 'antd'
import Container from 'components/container'
import { encryptByRSA } from 'util/rsa'
import { RSA_PUBLIC_KEY } from 'util/global'
import { api } from 'common/api'
import { token } from 'common/token'

export default class index extends Component {
    state = {
        loading: false,

        focusUser: false,
        focusPassword: false,

        btnDisabled: true,

        pattern: '',
        descriptions: '',
        visible: false,
    }

    backgroundImage = require(`assets/image/login-bg-0${Math.floor(Math.random() * 4)}.jpg`)

    focus = {
        user: false,
        password: false,
    }

    form = React.createRef()

    onLogin = values => {
        this.setState({ loading: true })

        let { account, password } = values
        password = encryptByRSA(password, RSA_PUBLIC_KEY)
        api.login({ account, password })
            .then(({ success, data, message }) => {
                if (success) {
                    const { passed, pattern, descriptions, token } = data
                    // 简单密码需要更改
                    if (!passed) {
                        this.setState({
                            visible: true,
                            loading: false,
                            btnDisabled: true,
                            pattern,
                            descriptions,
                        })
                    } else {
                        this.onLoginSuccess(token)
                    }
                } else {
                    this.setState({ loading: false })
                    Message.error(message)
                }
            })
            .catch(({ message }) => {
                if (typeof message === 'object' && message[0]) {
                    Message.error(message[0].messages[0])
                }
                this.setState({ loading: false })
            })
    }

    onLoginPass = values => {
        this.setState({ loading: true })
        const account = this.form.current.getFieldValue('account')
        let { password, newPassword } = values
        password = encryptByRSA(password, RSA_PUBLIC_KEY)
        newPassword = encryptByRSA(newPassword, RSA_PUBLIC_KEY)
        const confirm = newPassword // 前端验证两次密码即可.不需要加密

        api.loginPass({ account, password, newPassword, confirm })
            .then(({ success, data, message }) => {
                if (success) {
                    const { passed, pattern, descriptions, token } = data
                    // 简单密码需要更改
                    if (!passed) {
                        this.setState({
                            visible: true,
                            loading: false,
                            btnDisabled: true,
                            pattern,
                            descriptions,
                        })
                    } else {
                        this.onLoginSuccess(token)
                    }
                } else {
                    this.setState({ loading: false })
                    Message.error(message)
                }
            })
            .catch(({ message }) => {
                if (typeof message === 'object' && message[0]) {
                    Message.error(message[0].messages[0])
                }
                this.setState({ loading: false })
            })
    }

    onLoginSuccess(jwtToken) {
        token.value = jwtToken
        Message.success('登录成功')
        this.props.history.replace('/')
    }

    render() {
        const { loading, focusUser, focusPassword, btnDisabled, visible, pattern, descriptions } =
            this.state

        return (
            <div className="yo-login">
                <img src={this.backgroundImage.default} alt="" />
                <div className="yo-login--placeholder">
                    <Container mode="sm">
                        <Form
                            ref={this.form}
                            layout="vertical"
                            onFinish={this.onLogin}
                            onValuesChange={(changedValues, values) => {
                                this.setState({
                                    btnDisabled: !values.account || !values.password,
                                })
                            }}
                        >
                            <Form.Item
                                name="account"
                                className={!focusUser && 'yo-login--label'}
                                colon={false}
                                label="用户名"
                            >
                                <Input
                                    onBlur={() => {
                                        this.setState({
                                            focusUser: !!this.form.current.getFieldValue('account'),
                                        })
                                    }}
                                    onFocus={() => {
                                        this.setState({ focusUser: true })
                                    }}
                                    size="large"
                                    autoComplete="off"
                                    placeholder={focusUser && '请输入用户名/手机号/邮箱'}
                                />
                            </Form.Item>
                            <Form.Item
                                name="password"
                                className={!focusPassword && 'yo-login--label'}
                                colon={false}
                                label="密码"
                            >
                                <Input.Password
                                    onBlur={() => {
                                        this.setState({
                                            focusPassword:
                                                !!this.form.current.getFieldValue('password'),
                                        })
                                    }}
                                    onFocus={() => {
                                        this.setState({ focusPassword: true })
                                    }}
                                    size="large"
                                    autoComplete="off"
                                    placeholder={focusPassword && '请输入密码'}
                                />
                            </Form.Item>
                            <Form.Item className="mt-lg">
                                <Button
                                    disabled={btnDisabled}
                                    loading={loading}
                                    block
                                    htmlType="submit"
                                    size="large"
                                    type="primary"
                                >
                                    登录
                                </Button>
                            </Form.Item>
                        </Form>
                    </Container>
                </div>
                <Modal visible={visible} closable={false} footer={false}>
                    <Alert type="error" message="密码过于简单，请修改密码！" />
                    <br />
                    <Form className="yo-form" onFinish={this.onLoginPass}>
                        <div className="yo-form-group">
                            <Form.Item
                                label="旧密码"
                                rules={[{ required: true, message: '请输入旧密码' }]}
                                name="password"
                            >
                                <Input.Password autoComplete="off" placeholder="请输入旧密码" />
                            </Form.Item>
                            <Form.Item
                                label="新密码"
                                rules={[
                                    { required: true, message: '请输入新密码' },
                                    { pattern, message: '密码格式错误' },
                                ]}
                                name="newPassword"
                                tooltip={descriptions}
                            >
                                <Input.Password autoComplete="off" placeholder="请输入新密码" />
                            </Form.Item>
                            <Form.Item
                                label="确认新密码"
                                rules={[
                                    { required: true, message: '请确认新密码' },
                                    ({ getFieldValue }) => ({
                                        validator(_, value) {
                                            if (!value || getFieldValue('newPassword') === value) {
                                                return Promise.resolve()
                                            }
                                            return Promise.reject(new Error('确认新密码不匹配'))
                                        },
                                    }),
                                ]}
                                name="confirm"
                            >
                                <Input.Password autoComplete="off" placeholder="请确认新密码" />
                            </Form.Item>
                        </div>
                        <Form.Item noStyle>
                            <Button htmlType="submit" type="primary" block loading={loading}>
                                确认
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        )
    }
}
