import React, { useCallback, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { Input, Button, Form, Spin } from '@easyv/antd';
import classNames from 'classnames';
import Title from '../../components/Title';
import { login, updateCaptcha } from 'models/user';
import styles from './index.less';
import {getAssetsUrl} from 'utils/utils';
import defaultLoginLogo from '../../../images/login_logo.png';

const FormItem = Form.Item;

function Login({ location, history, login, updateCaptcha }) {
  const isMobile = /(iphone|android|ucweb|windows phone)/.test(navigator.userAgent.toLowerCase());
  const [authCode, setAuthCode] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);

  useEffect(() => {
    onUpdateCaptcha();
  }, []);

  const onUpdateCaptcha = useCallback(async () => {
    setLoading(true);
    const result = await updateCaptcha();
    result && setAuthCode(result?.svg);
    setLoading(false);
  }, []);

  const handleSubmit = useCallback(
    (values) => {
      const { search } = location;
      login(
        { ...values, svg: authCode },
        () => {
          if (search && search.indexOf('redirectUrl') > -1) {
            const entries = search.slice(1).split('&');
            const redirectUrlStr = entries.find((d) => d.indexOf('redirectUrl') > -1);
            const redirectVal = redirectUrlStr.split('=')[1];
            if (redirectUrlStr && redirectVal && redirectVal.includes(window.location.host)) {
              // history.push(redirectUrlStr.split('=')[1]);
              window.location.href = redirectVal;
            } else {
              history.push('/');
            }
          } else {
            history.push('/');
          }
          onUpdateCaptcha();
        },
        () => {
          onUpdateCaptcha();
        }
      );
      // eslint-disable-next-line react-hooks/exhaustive-deps
    },
    [authCode]
  );
  const { LOGIN_LOGO } = window.appConfig;
  const validate = (value) => {
    if (/\s+/.test(value)) {
      return Promise.reject('不允许输入空格');
    }
    return Promise.resolve();
  };
  const changeUpdateAuthCode = () => {
    // 更新验证码
    onUpdateCaptcha();
  };

  return (
    <div className={classNames(styles.container, { [styles.mobile]: isMobile })}>
      <Title title="登录" />
      <div className={styles.login}>
        <div
          className={styles.logo}
          style={{ backgroundImage: LOGIN_LOGO ? `url(${getAssetsUrl(LOGIN_LOGO)})` : `url(${defaultLoginLogo})` }}
        />
        <Form onFinish={handleSubmit}>
          <FormItem name="name" rules={[{ required: true, message: '输入用户名', validator: (_, value) => validate(value) }]}>
            <Input className={styles.input} placeholder="输入账号" />
          </FormItem>
          <FormItem name="password" rules={[{ required: true, message: '输入密码' }]}>
            <Input className={styles.input} type="password" placeholder="输入密码" />
          </FormItem>
          <FormItem>
            <Form.Item name="code" noStyle rules={[{ required: true, message: '输入验证码' }]}>
              <Input className={styles.code} type="text" placeholder="输入验证码" />
            </Form.Item>
            <div className={styles.authCode}>
              <Spin spinning={loading}>
                {authCode ? (
                  <span
                    className={styles.codeBox}
                    onClick={changeUpdateAuthCode}
                    title="更新验证码"
                    dangerouslySetInnerHTML={{ __html: authCode }}
                  />
                ) : (
                  <span className={styles.codeBox} title="验证码更新失败，请重试" onClick={changeUpdateAuthCode}>
                    验证码更新失败
                  </span>
                )}
              </Spin>
            </div>
          </FormItem>
          <FormItem style={{ marginBottom: 0 }}>
            <Button className={styles.btn} type="primary" htmlType="submit">
              登录
            </Button>
          </FormItem>
        </Form>
      </div>
    </div>
  );
}

const mapDispatchToProps = {
  login: login,
  updateCaptcha
};

export default connect(null, mapDispatchToProps)(Login);
