import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import { Alert, message,notification} from 'antd';
import React, { useState, useEffect } from 'react';
import ProForm, { ProFormCaptcha, ProFormCheckbox, ProFormText, ProFormDependency, ProFormSelect } from '@ant-design/pro-form';
import { useIntl, Link, history, FormattedMessage, SelectLang, useModel } from 'umi';
import Footer from '@/components/Footer';
import { login, getSubHosp } from '@/services/user';
import { getFakeCaptcha } from '@/services/ant-design-pro/login';
import styles from './index.less';
import CustomDialog from '@/components/Dialog';
import { getQueryString } from '../../../utils.js';


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

const Login = () => {
  const [submitting, setSubmitting] = useState(false);
  const [userLoginState, setUserLoginState] = useState({});
  const [type, setType] = useState('account');
  const [subHospList, setSubHospList] = useState([]);
  const { query = {} } = history.location;
  const { redirect,hospSign } = query;
  const { initialState, setInitialState } = useModel('@@initialState');
  const intl = useIntl();

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

  const { fetchSubHosp,sign } = initialState;

  const handleSubmit = async (values) => {
    setSubmitting(true);

    try {

      // 登录
      const loginResp = await login({ ...values, hospSign:hospSign});
      const {status,msg,data} = loginResp;
      // console.log({status,msg,data});
      if (status == 200) {
        const defaultloginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });

        if (localStorage.getItem('userData') == null || localStorage.getItem('userData') == undefined) {
          localStorage.setItem('userData',null);
        }
        if (localStorage.getItem('loginParams') == null || localStorage.getItem('loginParams') == undefined) {
          localStorage.setItem('loginParams',null);
        }
        localStorage.setItem('loginParams',JSON.stringify({hospSign:hospSign}));
        localStorage.setItem('userData',JSON.stringify({...data,avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',}));

        message.success(defaultloginSuccessMessage);
        await setInitialState((s) => ({ ...s, currentUser:data }));
        /** 此方法会跳转到 redirect 参数所在的位置 */

        if (!history) return;
        const { query } = history.location;
        const { redirect } = query;
        history.push(redirect || '/');
        return;
      }else {
        notification.error({
          message:msg
        })
      }

      setUserLoginState(data);
    } catch (error) {
      console.log({error});
      const defaultloginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      message.error(defaultloginFailureMessage);
    }

    setSubmitting(false);
  };
  //登录类型
  const { status, type: loginType } = userLoginState;

  useEffect(() => {

    fetchSubHosp().then(res => {
      if (res&&res.success) {
        const temp = res.map(item => ({
          'value': item.id,
          'label': item.name
        }))
        setSubHospList(temp);
      }
    })
  }, []);


  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.top}>
          <div className={styles.header}>
            <Link to="/">
              <img alt="logo" className={styles.logo} src="/KC-color.png" />
              <span className={styles.title}>全成本核算管理系统</span>
            </Link>
          </div>
        </div>

        <div className={styles.main}>
          <ProForm
            initialValues={{
              autoLogin: true,
            }}
            submitter={{
              searchConfig: {
                submitText: intl.formatMessage({
                  id: 'pages.login.submit',
                  defaultMessage: '登录',
                }),
              },
              render: (_, dom) => dom.pop(),
              submitButtonProps: {
                loading: submitting,
                size: 'large',
                style: {
                  width: '100%',
                },
              },
            }}
            onFinish={async (values) => {
              handleSubmit(values);
            }}
          >

            {status === 'error' && loginType === 'account' && (
              <LoginMessage
                content={intl.formatMessage({
                  id: 'pages.login.accountLogin.errorMessage',
                  defaultMessage: '账户或密码错误!',
                })}
              />
            )}
            {type === 'account' && (
              <>
                <ProFormText
                  name="account"
                  fieldProps={{
                    size: 'large',
                    prefix: <UserOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={'用户名：'}
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.username.required"
                          defaultMessage="请输入用户名!"
                        />
                      ),
                    },
                  ]}
                />
                <ProFormText.Password
                  name="password"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={'密码：'}
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.password.required"
                          defaultMessage="请输入密码！"
                        />
                      ),
                    },
                  ]}
                />
              </>
            )}

            {/* <ProFormDependency name={['name', ['name2', 'text']]}>
              {({ name, name2 }) => {
                return (
                  <ProFormSelect
                    options={
                      subHospList
                    }
                    width="md"
                    name="useMode"
                    label='请选择分院'
                  />
                );
              }}
            </ProFormDependency> */}

            <div
              style={{
                marginBottom: 24,
              }}
            >
            </div>
          </ProForm>

        </div>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
