/*
 * @Author: your name
 * @Date: 2021-11-09 14:58:08
 * @LastEditTime: 2025-03-27 14:13:26
 * @LastEditors: code4eat awesomedema@gmail.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /KC-MiddlePlatform/src/pages/login/index.tsx
 */

import React, { useRef, useEffect, useState } from 'react';
import { Select, notification, Row, Col, message } from 'antd';
import './style.less';

import { useModel, history, Location, Helmet } from 'umi';

import { Form, Input, Button } from 'antd';

import KCSelect from '@/components/kc-select';

import { getHospConfigBySign, getLastLoginSys, login } from '@/service/login';

import { KcimCenterSysId } from '@/constant';
import { getSysParamsByCode } from '@/service';
import { ErrorBoundary } from './ErrorBoundary';

const { Option } = Select;

export function changeFavicon(src: string) {
  const link = document.createElement('link');
  const oldLink = document.getElementById('favicon');
  link.id = 'favicon';
  link.rel = 'icon';
  link.href = src;
  if (oldLink) {
    document.head.removeChild(oldLink);
  }
  document.head.appendChild(link);
}

export interface LoginPageType {
  location: Location;
  title: string;
}

export const handleLogin = async (account: string, password: string, hospSign: string | undefined) => {
  if (!hospSign) {
    notification.error({
      message: '网址标记缺失，请检查网址！',
    });
    return null;
  }

  const resp = await login({
    account: account,
    password: password,
    hospSign: hospSign,
  });

  if (resp) {
    localStorage.setItem('userData', JSON.stringify(resp));
    localStorage.setItem('account', account);
    localStorage.setItem('tokenExpired', 'false');
    return resp;
  }
  return null;
};

export const getHospType = async () => {
  const resp = await getSysParamsByCode(KcimCenterSysId, '1864939559301812224');
  if (resp && resp.length > 0) {
    return resp[0].value;
  } else {
    return undefined;
  }
};

const LoginPage: React.FC<Partial<LoginPageType>> = ({ location = { pathname: '/login' } as Location, children, title = '用户登录' }) => {
  const loginPageRef = useRef<HTMLDivElement>(null);
  const [subHospList, setSubHospList] = useState<
    {
      loadType: number;
      id: string;
      hospAbbreviation: any;
      name: string;
      value: string | number;
      loginPic?: string;
      loginTips?: string;
      systemName?: string;
    }[]
  >([]); // 分院列表
  const [ifLoading, setIfLoading] = useState(false);
  const [currentHospName, setCurrentHospName] = useState(title);
  const { initialState, setInitialState } = useModel('@@initialState');
  const [windowWidth, set_windowWidth] = useState(0);
  const [ifShowLeftBlock, set_ifShowLeftBlock] = useState(true);
  const [currentSelectedSubHop, set_currentSelectedSubHop] = useState<any | undefined>({
    id: undefined,
    loginTips: '',
    loginPic: '',
  }); // 当前选中的院区

  const [hospSign, set_hospSign] = useState<undefined | string>(undefined); // 登陆用的hospSign

  // 获取当前账号分院列表
  const getSubHospFunc = async () => {
    if (hospSign) {
      const data = await getHospConfigBySign(hospSign);
      if ((data as any) instanceof Array) {
        setSubHospList(
          data.map((t) => {
            const temp = {
              name: t.name,
              value: t.hospSign,
              id: t.id,
              hospAbbreviation: t.hospAbbreviation,
              loadType: t.loadType,
              loginPic: t.loginPic ? t.loginPic : '',
              loginTips: t.loginTips ? t.loginTips : '',
              systemName: t.systemName,
            };
            if (t.hospSign == hospSign) {
              setCurrentHospName(temp.systemName || title);
              set_currentSelectedSubHop(temp);
              localStorage.setItem('currentSelectedSubHop', JSON.stringify(temp));
              localStorage.setItem('hospAbbreviation', temp.hospAbbreviation);
              localStorage.setItem('currentHospName', temp.systemName || '');
            }
            return temp;
          }),
        );
      }
    } else {
      alert('网址格式不正确，请添加正确的链接hospSign标识！');
    }
  };

  const handleResize = (e: Event) => {
    set_windowWidth((e.target as Window).innerWidth);
  };

  useEffect(() => {
    setCurrentHospName(title);
  }, [title]);

  useEffect(() => {
    if (windowWidth <= 1000 && windowWidth !== 0) {
      set_ifShowLeftBlock(false);
    } else {
      set_ifShowLeftBlock(true);
    }
  }, [windowWidth]);

  useEffect(() => {
    if (currentSelectedSubHop && currentSelectedSubHop.loginPic && currentSelectedSubHop.loginPic.length > 0) {
      const arr = currentSelectedSubHop.loginPic.split('|');
      if (arr.length === 2) {
        changeFavicon(arr[1]);
      }
    }
  }, [currentSelectedSubHop]);

  useEffect(() => {
    if (hospSign) {
      location.pathname === '/login' && getSubHospFunc();
    }
  }, [hospSign, location.pathname]);

  useEffect(() => {
    // 根据hospSign获取分院信息
    setInitialState((s: any) => ({ ...(s || {}), currentSelectedSys: undefined, openedSysLists: [] }));

    window.addEventListener('resize', (e) => handleResize(e)); // 监听窗口大小改变

    const queryHospSign = history.location.query?.hospSign as string;
    localStorage.setItem('hospSign', queryHospSign);
    set_hospSign(queryHospSign);
    if (!queryHospSign) {
      message.error('网址格式不正确，请添加正确的链接hospSign标识！');
    }

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [setInitialState]);

  const onFinish = async (values: { account: string; password: string }) => {
    setIfLoading(true);
    const resp = await handleLogin(values.account, values.password, hospSign);
    setIfLoading(false);

    if (resp) {
      const currentSelectedSubHopStr = localStorage.getItem('currentSelectedSubHop') || '{}';
      const currentSelectedSubHop = JSON.parse(currentSelectedSubHopStr);
      const customerType = await getHospType();
      setInitialState((s: any) => ({ ...(s || {}), userData: resp, customerType }));
      localStorage.setItem('customerType', customerType || '');

      if (currentSelectedSubHop.loadType) {
        const lastLoginSysData = await getLastLoginSys({ hospId: currentSelectedSubHop.id, userId: resp.userId });
        if (lastLoginSysData) {
          history.replace(lastLoginSysData.path);
          localStorage.setItem('currentSelectedTab', JSON.stringify({ ...lastLoginSysData, menuId: lastLoginSysData.systemId }));
        }
      } else {
        history.replace('/index');
      }
    }
  };

  const loginPicArr = currentSelectedSubHop?.loginPic ? currentSelectedSubHop.loginPic.split('|') : [];
  const loginTipsArr = currentSelectedSubHop?.loginTips ? currentSelectedSubHop.loginTips.split('|') : [];

  return (
    <div className="loginPage">
      <Helmet>
        <title>{currentHospName}</title>
      </Helmet>
      {location.pathname === '/login' ? (
        <>
          <Row style={{ height: '100%' }}>
            {ifShowLeftBlock && (
              <Col flex="500px">
                <div className="left">
                  <div className="topLogo">
                    {loginPicArr[0] && <img className="logo" src={loginPicArr[0]} alt="康程智医" />}
                    {loginTipsArr[0] && (
                      <div className="logoDesc" style={{ borderLeft: loginPicArr[0] ? '1px solid #CFD6E6' : 'none' }}>
                        {loginTipsArr[0]}
                      </div>
                    )}
                  </div>
                  <img className="loginbanner" src={require('../../../public/images/loginBannner.png')} alt="" />
                </div>
              </Col>
            )}
            <Col flex="auto">
              <div className="rightLoginArea">
                {!ifShowLeftBlock && (
                  <div className="topLogo">
                    {loginPicArr[0] && <img className="logo" src={loginPicArr[0]} alt="康程智医" />}
                    {loginTipsArr[0] && <div className="logoDesc">{loginTipsArr[0]}</div>}
                  </div>
                )}

                <div className="subHospSelector">
                  {subHospList.length > 0 && (
                    <KCSelect
                      allowClear={false}
                      style={{ width: 180 }}
                      defaultValue={hospSign}
                      onSelect={(val: any, option) => {
                        set_hospSign(val);
                        localStorage.setItem('hospAbbreviation', option.item.hospAbbreviation);
                        localStorage.setItem('currentSelectedSubHop', JSON.stringify(option.item));
                        set_currentSelectedSubHop(option.item);
                      }}
                      suffixIcon={<img style={{ width: '10px', height: '6px' }} src={require('../../../public/images/arrow.png')} />}
                    >
                      {subHospList.map((item) => {
                        return (
                          <Option value={item.value} item={item} key={item.value}>
                            {item.name}
                          </Option>
                        );
                      })}
                    </KCSelect>
                  )}
                </div>
                <div className="systemName">{currentHospName}</div>
                <Form onFinish={onFinish}>
                  <Form.Item name="account" rules={[{ required: true, message: '请输入用户名!' }]}>
                    <Input className="input" placeholder="请输入用户名" />
                  </Form.Item>

                  <Form.Item name="password" rules={[{ required: true, message: '请输入密码!' }]}>
                    <Input.Password className="input" placeholder="请输入密码" />
                  </Form.Item>

                  <Form.Item>
                    <Button className="loginBtn" type="primary" htmlType="submit" loading={ifLoading}>
                      登录
                    </Button>
                  </Form.Item>
                </Form>
                <div className="bottomCopyright">
                  {loginTipsArr[1]}
                  <span style={{ paddingLeft: 16 }}>{loginTipsArr[2]}</span>
                  <a target="_blank" href="https://beian.miit.gov.cn/" style={{ display: 'inline-block', textDecoration: 'none', marginLeft: 10, color: '#515866' }} rel="noreferrer">
                    滇ICP备2024031095号
                  </a>
                </div>
              </div>
            </Col>
          </Row>
        </>
      ) : (
        children
      )}
    </div>
  );
};

// 使用ErrorBoundary包裹LoginPage，使得LoginPage内部的错误能被捕获
const WrappedLoginPage = () => (
  <ErrorBoundary>
    <LoginPage />
  </ErrorBoundary>
);

export default WrappedLoginPage;
