/*
 * @Author: your name
 * @Date: 2021-11-09 14:58:08
 * @LastEditTime: 2023-09-18 15:47:56
 * @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, Children, ReactEventHandler } from 'react';
import { Select, message, Row, Col, Modal } from 'antd';
import './style.less';

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

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

import logo from '../../../public/images/kclogo_colorful.png';

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

import { getHospConfigBySign, getLastLoginSys, getLoginTipType, login } from '@/service/login';
import Divider from '@ant-design/pro-card/lib/components/Divider';
import { getAllParams } from '@/service';

const { Option } = Select;

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

const LoginPage: React.FC<LoginPageType> = ({ location, children, title }) => {

  const loginPageRef = useRef<HTMLDivElement>(null);
  const [subHospList, setSubHospList] = useState<{
    loadType: number;
    id:string;
    hospAbbreviation: any; name: string; value: string | number 
}[]>([]); //分院列表
  const [ifLoading, setIfLoading] = useState(false);
  // const [systemList, setSystemList] = useState<userRelationInfo.OwnAppsItem[]>([]); //可选平台列表
  const [currentHospName, setCurrentHospName] = useState('欢迎进入医务管理系统');
  const { initialState, setInitialState } = useModel('@@initialState');
  const [windowWidth, set_windowWidth] = useState(0);
  const [ifShowLeftBlock, set_ifShowLeftBlock] = useState(true);
  const [currentSelectedSubHop,set_currentSelectedSubHop] = useState<any|undefined>(undefined);  //当前选中的院区

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

  

  //获取当前账号分院列表
  const getSubHospFunc = async () => {
    const hospSign = history.location.query?.hospSign as string;
    if (hospSign) {
      const data = await getHospConfigBySign(hospSign);
   
      if(data as any instanceof Array){
        setSubHospList(
          data.map((t) => ({
            name: t.name,
            value: t.hospSign,
            id:t.id,
            hospAbbreviation:t.hospAbbreviation,
            loadType:t.loadType
          })),
        );
        setCurrentHospName(data[0].systemName);
        set_currentSelectedSubHop(data[0]);
        localStorage.setItem('currentSelectedSubHop',JSON.stringify(data[0]));
        localStorage.setItem('hospAbbreviation',data[0].hospAbbreviation);
        localStorage.setItem('currentHospName',data[0].systemName);
      }
      
    }
  };

  const onFinish = async (values: LoginPageTypes.LoginInfo) => {
    setIfLoading(true);
    if (!hospSign) {
      notification.error({
        message: '网址标记缺失，请检查网址！',
      });
      setIfLoading(false);
      return;
    }
    const resp = await login({
      account: values.account,
      password: values.password,
      hospSign: hospSign,
      // remember:false,
    });

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

      if(values.password == '123456'){
            //如果密码为默认密码时
            const loginTipeType = await getAllParams();
            if(loginTipeType){
  
                 const needItem = loginTipeType.filter((a:any)=>a.code == '1688483840064098304');
  
                 if(needItem.length>0){
                      if(needItem[0].value == 2){
                        Modal.confirm({
                          title:'提醒',
                          content:'您的账号存在密码泄露风险，请尽快修改密码！',
                          okText:'去更改',
                          cancelText:'稍后',
                          onOk(...args) {
                            history.replace('/personalCenter');
                          },
                        })
                      }
                      if(needItem[0].value == 3){
                        Modal.warn({
                          title:'提醒',
                          content:'您的账号存在密码泄露风险，请先修改密码！',
                          okText:'去更改',
                          onOk(...args) {
                            history.replace('/personalCenter');
                          },
                        })
                      }
                 }
            }
  
      }
      
      setIfLoading(false);
    }
  };

  const handleResize = (e: Event) => {
    // console.log('innerWidth',(e.target as Window).innerWidth);
    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(() => {
    //根据hospSign获取分院信息
    location.pathname == '/login' && getSubHospFunc();
    setInitialState((s) => ({ ...s, currentSelectedSys: undefined, openedSysLists: [] }));

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

    const hospSign = history.location.query?.hospSign as string;
    localStorage.setItem('hospSign', hospSign);
    set_hospSign(hospSign);

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

  }, []);
  
  

  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'>
                    <img className='logo' src={logo} alt="康程智医" />
                    <div className='logoDesc'>助力医疗机构高质量发展</div>
                  </div>
                  <img className='loginbanner' src={require('../../../public/images/loginBannner.png')} alt="" />
                </div>
              </Col>
            )
          }
          <Col flex="auto">
            <div className="rightLoginArea">
              {
                !ifShowLeftBlock && (
                  <div className='topLogo'>
                    <img className='logo' src={logo} alt="康程智医" />
                    <div className='logoDesc'>助力医疗机构高质量发展</div>
                  </div>
                )
              }

              <div className="subHospSelector">
                {subHospList.length > 0 && (
                  <KCSelect
                    allowClear={false}
                    style={{ width: 180 }}
                    defaultValue={subHospList[0].value}
                    onSelect={(val:any,option)=>{
                      // localStorage.removeItem('hospSign');
                      // localStorage.setItem('hospSign', val);
                      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.Item name="remember" valuePropName="checked">
                    <Checkbox className="checkBtn">记住密码</Checkbox>
                  </Form.Item> */}
              </Form>
              <div className='bottomCopyright'>© 2022 康程智医（成都）技术部出品</div>
              <div className='versionInfo'>精益管理决策平台 V1.0</div>
            </div>
          </Col>
        </Row>

      ) : (
        children
      )}
    </div>
  );
};

export default LoginPage;
