import {
  EnvironmentOutlined,
  HomeOutlined,
  LockOutlined,
  SafetyCertificateOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Button, Checkbox, Form, Input, message } from 'antd';
import qs from 'query-string';
import React, { useEffect, useMemo } from 'react';
import loginDefault from '../../assets/images/login.png';
import loginBgDefault from '../../assets/images/loginBg.png';
import {
  ConfigurationController,
  LoginController,
  CommonController,
} from '../../services';
import store, { sessionStore } from '../../utils/store';
import styles from './index.less';
import { deCrypt, enCrypt } from './utils';
import { getAppIdHolder, getMenuHolder } from '../../utils/initial';
import { isEffectiveRoute, pathHolder } from '../../utils/route';
const Login: React.FC = () => {
  const {
    platformName,
    loginBgImg,
    loginImg,
    loginLogoImg,
    isShowLoginBgImg = 'y',
    isShowLoginImg = 'y',
    isShowLoginLogoImg = 'y',
  } = useMemo(() => {
    const systemConfig: ConfigurationController.SystemConfigFields =
      sessionStore.get('system-config') || {};
    const { configValue: configValueSource } = systemConfig;
    const configValue: ConfigurationController.SystemConfigValueFields =
      JSON.parse(configValueSource || '{}');
    return configValue;
  }, []);

  const { data: codeInfo, run: getCodeRun } = useRequest(
    LoginController.getCodeApi,
  );
  const [form] = Form.useForm();
  const {
    data: medicalInfo,
    run: getMedicalInfo,
    mutate,
  } = useRequest(LoginController.getMedicalInfoApi, { manual: true });

  const { userName, orgName, deptName } = useMemo(() => {
    const { userName = '', orgName = '', deptName = '' } = medicalInfo || {};
    return {
      userName,
      orgName,
      deptName,
    };
  }, [medicalInfo]);

  const onFinish = async (
    values: Omit<LoginController.LoginParams, 'uuid'>,
  ) => {
    const { remember, username, password } = values || {};
    if (remember) {
      store.set('account-info', {
        username,
        password: enCrypt(password),
      });
    } else {
      store.move('account-info');
    }
    try {
      const { data: loginInfo } = await LoginController.loginApi({
        ...values,
        uuid: codeInfo?.uuid || '',
      });
      sessionStore.set('login-info', loginInfo);
      const userInfo = await CommonController.getUserInfoApi();
      const [role] = userInfo?.user?.roles || [];
      const { defaultPage } = role || {};
      const { redirect } = qs.parse(
        location.href.replace(/^(.*?)(\?)/, ''),
      ) as Record<string, string | undefined>;

      const appId = await getAppIdHolder();

      if (appId && (redirect || defaultPage)) {
        const { origin } = location;
        const { url: redirectUrl, query: redirectQuery } = qs.parseUrl(
          redirect || '',
        );
        const { url: defaultPathname, query: defaultQuery } = qs.parseUrl(
          defaultPage || '',
        );
        const redirectPathname = (redirectUrl || '').replace(origin, '');
        const { _groupName_: redirectGroupName } = (redirectQuery ||
          {}) as Record<string, string | undefined>;
        const { _groupName_: defaultGroupName } = (defaultQuery ||
          {}) as Record<string, string | undefined>;

        if (redirectPathname) {
          await getMenuHolder(appId, redirectGroupName || '');
          if (isEffectiveRoute(redirectPathname)) {
            location.replace(redirect as string);
          } else {
            await getMenuHolder(appId, defaultGroupName || '');
            if (isEffectiveRoute(pathHolder(defaultPathname))) {
              location.replace(pathHolder(defaultPage));
            } else {
              message.error('抱歉，您没有权限！');
            }
          }
        } else {
          await getMenuHolder(appId, defaultGroupName || '');
          if (isEffectiveRoute(pathHolder(defaultPathname))) {
            location.replace(pathHolder(defaultPage));
          } else {
            message.error('抱歉，您没有权限！');
          }
        }
      } else {
        message.error('抱歉，您没有权限！');
      }
    } catch (error) {
      getCodeRun();
    }
  };

  useEffect(() => {
    const { username, password: enPassword } = store.get('account-info') || {};
    if (username) {
      const formData = new FormData();
      formData.append('username', username);
      form.setFieldValue('username', username);
      getMedicalInfo(formData);
    }
    if (enPassword) {
      const password = deCrypt(enPassword);
      form.setFieldValue('password', password);
    }
  }, [form, getMedicalInfo]);

  return (
    <div className={styles.container}>
      <div
        className={styles.imgBlock}
        style={{
          backgroundImage:
            isShowLoginBgImg === 'y'
              ? `url(${loginBgImg || loginBgDefault})`
              : '',
        }}
      >
        {loginLogoImg && isShowLoginLogoImg === 'y' && (
          <img className={styles.imgLogo} src={loginLogoImg} />
        )}
        {isShowLoginImg === 'y' && (
          <img className={styles.imgCenter} src={loginImg || loginDefault} />
        )}
      </div>
      <div className={styles.bodyBlock}>
        <LoginForm
          form={form}
          onFinish={onFinish}
          actions={
            <Button size="large" block onClick={() => form.resetFields()}>
              重置
            </Button>
          }
        >
          <h1 className={styles.loginTitle}>
            {platformName || '全民健康信息平台'}
          </h1>
          <div style={{ display: 'flex', alignItems: 'flex-start' }}>
            <div style={{ flex: 1 }}>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                  onBlur: (e) => {
                    const username = e.target.value;
                    if (username) {
                      const formData = new FormData();
                      formData.append('username', username);
                      getMedicalInfo(formData);
                    }
                  },
                  onChange: (e) => {
                    if (!e.target.value) {
                      mutate(undefined);
                    }
                  },
                }}
              />
            </div>
            <div className={styles.inputRightBlock}>
              <Input
                className={styles.inputRightBody}
                value={userName}
                disabled={true}
              />
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-start' }}>
            <div style={{ flex: 1 }}>
              <ProFormText
                disabled={true}
                name="org"
                fieldProps={{
                  placeholder: '',
                  size: 'large',
                  value: orgName,
                  prefix: <HomeOutlined />,
                }}
              />
            </div>
            <div className={styles.inputRightBlock}>
              <Input
                prefix={<EnvironmentOutlined />}
                className={styles.inputRightBody}
                value={deptName}
                disabled={true}
              />
            </div>
          </div>
          <ProFormText.Password
            name="password"
            allowClear
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined />,
              visibilityToggle: false,
            }}
            placeholder={'请输入密码'}
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },
            ]}
          />
          {codeInfo?.captchaEnabled ? (
            <div style={{ display: 'flex', alignItems: 'flex-start' }}>
              <div style={{ flex: 1 }}>
                <ProFormText
                  fieldProps={{
                    size: 'large',
                    prefix: <SafetyCertificateOutlined />,
                  }}
                  name="code"
                  placeholder={'请输入图形验证码'}
                  rules={[
                    {
                      required: true,
                      message: '请输入图形验证码！',
                    },
                  ]}
                />
              </div>
              <div className={styles.inputRightBlock}>
                <img
                  src={'data:image/png;base64,' + codeInfo?.img}
                  className={styles.inputRightBody}
                  onClick={getCodeRun}
                />
              </div>
            </div>
          ) : null}
          <Form.Item
            valuePropName="checked"
            initialValue={true}
            name="remember"
          >
            <Checkbox>记住密码</Checkbox>
          </Form.Item>
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
