import {
  LoginForm,
  ProForm,
  ProFormCaptcha,
  ProFormText,
} from '@ant-design/pro-components';
import { Button } from 'antd';
import React, { useState } from 'react';
import { history } from 'umi';
import styles from './index.less';
import { login, sendCaptcha, sendEmailCaptcha } from '@/services/login';
import Cookies from 'js-cookie';
import { useModel } from '@@/plugin-model/useModel';
import login_logo from '../asset/ic_login_logo.png';
import { Toast } from 'antd-mobile/es';
import { getPageQuery } from '@/utils/utils';

const paperId = parseInt(getPageQuery().paperId + '');

const Login: React.FC = () => {
  const LOGIN_TYPE_PHONE_CAPTCHA = 1;
  const LOGIN_TYPE_EMAIL_CAPTCHA = 2;

  const [form] = ProForm.useForm();
  const { initialState, setInitialState } = useModel('@@initialState');
  const [loginType, setLoginType] = useState(LOGIN_TYPE_PHONE_CAPTCHA);

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s) => ({
        ...s,
        currentUser: userInfo,
      }));
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      const response = await login({ ...values, type: loginType });
      if (response.code === 200) {
        await setInitialState((s) => ({
          ...s,
          currentUser: response.data,
        }));
        Cookies.set('ut', response!.data!.token!, { expires: 1 });
        await fetchUserInfo();
        if (!history) return;
        const { query } = history.location;
        const { redirect } = query as { redirect: string };
        if (redirect) {
          window.location.href = decodeURIComponent(redirect);
        }
        return;
      }
      Toast.show({
        icon: 'fail',
        content: response.message,
      });
    } catch (error) {
      Toast.show({
        icon: 'fail',
        content: '登录失败，请重试',
      });
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.logoWrapper}>
          <img src={login_logo} className={styles.logo} />
        </div>
        <div className={styles.title}>欢迎登录</div>
        <LoginForm
          form={form}
          initialValues={{}}
          actions={[]}
          onFinish={async (values) => {
            await handleSubmit({ ...values, sourceId: paperId });
          }}
          submitter={{
            render: (props, doms) => {
              return [
                <Button
                  type="primary"
                  shape="round"
                  size={'large'}
                  className={styles.submit}
                  onClick={() => props.form?.submit?.()}
                >
                  登录
                </Button>,
              ];
            },
          }}
        >
          <>
            {loginType == LOGIN_TYPE_PHONE_CAPTCHA && (
              <ProFormText
                className={styles.formItem}
                fieldProps={{
                  size: 'large',
                  className: styles.input,
                }}
                name="phone"
                placeholder="手机号"
                rules={[
                  {
                    required: true,
                    message: '请输入手机号！',
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: '手机号格式错误！',
                  },
                ]}
              />
            )}

            {loginType == LOGIN_TYPE_EMAIL_CAPTCHA && (
              <ProFormText
                className={styles.formItem}
                fieldProps={{
                  size: 'large',
                  className: styles.input,
                }}
                name="email"
                placeholder="邮箱"
                rules={[
                  {
                    required: true,
                    message: '请输入邮箱！',
                  },
                  {
                    pattern:
                      /^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/,
                    message: '邮箱格式错误！',
                  },
                ]}
              />
            )}

            <ProFormCaptcha
              className={styles.captchaItem}
              fieldProps={{
                size: 'large',
                className: styles.input,
              }}
              captchaProps={{
                size: 'large',
                className: styles.input,
              }}
              placeholder="请输入验证码"
              captchaTextRender={(timing, count) => {
                if (timing) {
                  return `${count} 获取验证码`;
                }
                return '获取验证码';
              }}
              name="captcha"
              rules={[
                {
                  required: true,
                  message: '请输入验证码！',
                },
                {
                  min: 4,
                },
                {
                  max: 6,
                },
              ]}
              onGetCaptcha={async () => {
                if (loginType == LOGIN_TYPE_PHONE_CAPTCHA) {
                  const phone = form.getFieldValue('phone');
                  if (!phone) {
                    Toast.show({
                      icon: 'fail',
                      content: '请先输入手机号',
                    });
                    throw new Error('请先输入手机号');
                  }
                  const result = await sendCaptcha({
                    phone,
                  });
                  console.log(result);
                  if (result === false) {
                    return;
                  }
                } else if (loginType == LOGIN_TYPE_EMAIL_CAPTCHA) {
                  const email = form.getFieldValue('email');
                  if (!email) {
                    Toast.show({
                      icon: 'fail',
                      content: '请先输入邮箱',
                    });
                    throw new Error('请先输入邮箱');
                  }
                  const result = await sendEmailCaptcha({
                    email,
                  });
                  console.log(result);
                  if (result === false) {
                    return;
                  }
                }
              }}
            />
          </>
          <div
            style={{
              marginBottom: 24,
            }}
          ></div>
          {loginType == LOGIN_TYPE_PHONE_CAPTCHA && (
            <div
              className={styles.changeLogin}
              onClick={() => {
                setLoginType(LOGIN_TYPE_EMAIL_CAPTCHA);
              }}
            >
              切换邮箱登录
            </div>
          )}

          {loginType == LOGIN_TYPE_EMAIL_CAPTCHA && (
            <div
              className={styles.changeLogin}
              onClick={() => {
                setLoginType(LOGIN_TYPE_PHONE_CAPTCHA);
              }}
            >
              切换手机登录
            </div>
          )}
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
