import { useEffect, useState } from 'react';
import { message, Image } from 'antd';
import { LockOutlined, UserOutlined, VerifiedOutlined } from '@ant-design/icons';
import { ProForm, ProFormText } from '@ant-design/pro-components';
import { FormattedMessage, history, useIntl, useModel } from 'umi';

import { setLogin } from '@/utils/auth';
import services from '@/services/admin';

const { authLogin } = services.AuthController;


export default () => {
  const { initialState, setInitialState } = useModel('@@initialState');

  const fetchAuthUser = async () => {
    const authUserData = await initialState?.fetchAuthUser?.();

    if (authUserData) {
      await setInitialState((s) => ({
        ...s,
        userInfo: authUserData,
      }));
    }
  };

  const fetchAuthPermission = async () => {
    const authPermissionData = await initialState?.fetchAuthPermission?.();

    if (authPermissionData) {
      await setInitialState((s) => ({
        ...s,
        authPermissionMenu: authPermissionData?.menu,
        authPermissionAction: authPermissionData?.action,
      }));
    }
  };

  const handleSubmit = async (values) => {
    //values.key = captcha.key;
    // 登录
    try {
      const { data, success } = await authLogin({ ...values });
      if (success) {
        setLogin(data);

        await fetchAuthUser();
        await fetchAuthPermission();

        /** 跳转到 redirect 参数所在的位置 */
        if (history.location.pathname === '/login') {
          history.push('/');
        } else {
          history.push('/');
        }
      }
    } catch (error) {
      console.log(error)
    }
  };

  useEffect(() => {
    // captchaCode().then(({ data }) => {
    //   setCaptcha(data);
    // });
  }, []);



  return (
    <div
      className={`flex justify-center items-center`}
    >
      <ProForm
        className={`w-2/6 min-w-[400px] pt-[6%]`}
        onFinish={async (values) => {
          await handleSubmit(values);
        }}
        submitter={{
          searchConfig: {
            submitText: '登录',
          },
          render: (_, dom) => dom.pop(),
          submitButtonProps: {
            size: 'large',
            style: {
              width: '100%',
            },
          },
        }}
      >
        <ProFormText
          name="mobile"
          fieldProps={{
            size: 'large',
            prefix: <UserOutlined />,
          }}
          placeholder={'请输入手机号！'}
          rules={[
            {
              required: true,
              message: '请输入手机号！',
            },
          ]}
        />
        <ProFormText.Password
          name="password"
          fieldProps={{
            size: 'large',
            prefix: <LockOutlined />,
          }}
          placeholder={'请输入密码！'}
          rules={[
            {
              required: true,
              message: '请输入密码！',
            },
          ]}
        />

      </ProForm>
    </div>
  );
};
