import Footer from '@/components/Footer';
import { LockOutlined, MobileOutlined } from '@ant-design/icons';
import {
  LoginForm,
  ProForm,
  ProFormCaptcha,
  ProFormText,
} from '@ant-design/pro-components';
import { Alert, message, Tabs } from 'antd';
import React, { useState } from 'react';
import { history } from 'umi';
import styles from './index.less';
import { login, sendCaptcha } from '@/services/login';
import Cookies from 'js-cookie';
import { useModel } from '@@/plugin-model/useModel';
import { USER_TYPE_ADMIN, USER_TYPE_PLATFORM } from '@/services/constants';

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [errorMsg, setErrorMsg] = useState<string>('');
  const [type, setType] = useState<string>('password');
  const [form] = ProForm.useForm();
  const { initialState, setInitialState } = useModel('@@initialState');

  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: type == 'password' ? 0 : 1,
      });
      console.log(response);
      if (response.code === 200) {
        if (
          response.data?.type !== USER_TYPE_ADMIN &&
          response.data?.type !== USER_TYPE_PLATFORM
        ) {
          message.success('登录成功');
          await setInitialState((s) => ({
            ...s,
            currentUser: response.data,
          }));
          Cookies.set('ut', response!.data!.token!);
          await fetchUserInfo();
          if (!history) return;
          const { query } = history.location;
          const { redirect } = query as { redirect: string };
          history.push(redirect || '/welcome');
          return;
        } else {
          setErrorMsg('登录平台错误');
          return;
        }
      }
      // 如果失败去设置用户错误信息
      setErrorMsg(response.message || '');
    } catch (error) {
      message.error('登录失败，请重试！');
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          form={form}
          title="高潜咨询"
          subTitle={'中国企业人效的未来'}
          initialValues={{}}
          actions={[]}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <Tabs activeKey={type} onChange={setType}>
            <Tabs.TabPane key="password" tab={'手机号密码登录'} />
            <Tabs.TabPane key="captcha" tab={'手机号验证码登录'} />
          </Tabs>

          {errorMsg && <LoginMessage content={errorMsg} />}

          {type === 'password' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined className={styles.prefixIcon} />,
                }}
                name="phone"
                placeholder="手机号"
                rules={[
                  {
                    required: true,
                    message: '请输入手机号！',
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: '手机号格式错误！',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'密码'}
                rules={[
                  {
                    required: true,
                    message: '请输入密码',
                  },
                ]}
              />
            </>
          )}

          {type === 'captcha' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined className={styles.prefixIcon} />,
                }}
                name="phone"
                placeholder="手机号"
                rules={[
                  {
                    required: true,
                    message: '请输入手机号！',
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: '手机号格式错误！',
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder="请输入验证码"
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} 获取验证码`;
                  }
                  return '获取验证码';
                }}
                name="captcha"
                rules={[
                  {
                    required: true,
                    message: '请输入验证码！',
                  },
                ]}
                onGetCaptcha={async () => {
                  const phone = form.getFieldValue('phone');
                  if (!phone) {
                    message.error('请先输入手机号');
                    throw new Error('请先输入手机号');
                  }
                  const result = await sendCaptcha({
                    phone,
                  });
                  console.log(result);
                  if (result === false) {
                    return;
                  }
                  message.success('获取验证码成功');
                }}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          ></div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
