/*
 * @Author: your name
 * @Date: 2021-11-09 14:58:08
 * @LastEditTime: 2022-02-10 16:52:48
 * @LastEditors: Please set LastEditors
 * @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 } from 'react';
import { Select, message } from 'antd';
import './style.less';

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

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

import logo from '../../../public/images/kc-logo.png';

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

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

const { Option } = Select;

export interface LoginPageType {
  location: Location;
}

const LoginPage: React.FC<LoginPageType> = ({ location, children }) => {
  const [transitionObj, setTransitionObj] = useState<string>();
  const [transformObj, setTransformObj] = useState<string>();
  const loginPageRef = useRef<HTMLDivElement>(null);
  const [subHospList, setSubHospList] = useState<
    { name: string; value: string | number }[]
  >([]); //分院列表
  const [ifSelectSystem, setIfSelectSystem] = useState(false); //是否跳转到选择系统界面
  const [ifLoading, setIfLoading] = useState(false);
  const [systemList, setSystemList] = useState<userRelationInfo.OwnAppsItem[]>(
    [],
  ); //可选平台列表
  const [currentHospName, setCurrentHospName] =
    useState('欢迎进入医务管理系统');
  const { initialState, setInitialState } = useModel('@@initialState');

  const onMouseMoveHandle = (mouseEvent: any) => {
    //    console.log({mouseEvent});
    const loginPage = loginPageRef.current;
    if (loginPage) {
      let centerX = loginPage.offsetLeft + loginPage.offsetWidth / 2, //div中心点到页面左边距离
        centerY = loginPage.offsetTop + loginPage.offsetHeight / 2;

      let deltaX = mouseEvent.pageX - centerX,
        deltaY = mouseEvent.pageY - centerY;

      let percentageX = deltaX / centerX, //向左或向右的 偏差率
        percentageY = deltaY / centerY;
      let deg = 20; //控制 偏差的 程度
      // console.log(percentageX*20,percentageY*20);
      setTransformObj(
        `translate(${percentageX * deg}px,${percentageY * deg}px)`,
      );
      // setTransformObj('rotateX(' + percentageY * deg + 'deg)');
    }
  };

  const onMouseLeaveHandle = () => {
    setTransformObj(`translate(0px,0px)`);
    setTransitionObj('all 0.2s linear');
  };

  //获取当前账号分院列表
  const getSubHospFunc = async () => {
    const hospSign = history.location.query?.hospSign as string;
    if (hospSign) {
      const data = await getHospConfigBySign(hospSign);
      if (!data) return;
      setSubHospList(
        data.map((t) => ({
          name: t.name,
          value: t.hospSign,
        })),
      );
      setCurrentHospName(data[0].systemName);
    }
  };

  const onFinish = async (values: LoginPageTypes.LoginInfo) => {
    setIfLoading(true);
    const hospSign = history.location.query?.hospSign as string;
    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));
      localStorage.setItem('hospSign', hospSign);

      if (initialState && initialState.getHospSubSystemListFunc) {
        const data = await initialState.getHospSubSystemListFunc();
        await setInitialState((s) => ({
          ...s,
          systemLists: data,
          userData: resp,
        }));

        setSystemList(data);

        if (data.length > 1) {
          //当前医院拥有多个子平台时，进入选择
          setIfSelectSystem(true);
          history.replace('/index');
        } else {
          //否则直接进入首页
          const { query } = history.location;
          const { redirect } = query as { redirect: string };
          history.replace(redirect || '/index');
          return;
        }
      }

      setIfLoading(false);
    }
  };

  useEffect(() => {
    //根据hospSign获取分院信息
    location.pathname == '/login' && getSubHospFunc();

    // window.addEventListener('message',(e)=>{
    //      console.log(e.origin)
    //      if(e.origin == 'http://192.168.50.76:8902'){
    //       console.log({e})
    //      }
    // }, false);
  }, []);

  // return (
  //   <div>
  //       <iframe src="http://192.168.50.76:8902/TracerMethodology/?hospSign=IGlcn5nc4xBWc08C"></iframe>
  //   </div>
  // )

  return (
    <div
      className="loginPage"
      onMouseMove={onMouseMoveHandle}
      onMouseLeave={onMouseLeaveHandle}
      ref={loginPageRef}
    >
      <div
        className="circleBigOne"
        style={{ transform: transformObj, transition: transitionObj }}
      ></div>
      <div className="circleBigerOne"></div>
      <div
        className="circleLittleOne"
        style={{ transform: transformObj, transition: transitionObj }}
      ></div>
      {location.pathname == '/login' ? (
        <div className="loginBlock">
          <div className="left">
            <img
              className="bannerImg"
              src={require('../../../public/images/loginBannner.png')}
            />
          </div>
          <div className="rightLoginArea">
            <div className="subHospSelector">
              {subHospList.length > 0 && (
                <KCSelect
                  allowClear={false}
                  style={{ width: 150 }}
                  defaultValue={subHospList[0].value}
                  suffixIcon={
                    <img
                      style={{ width: '10px', height: '6px' }}
                      src={require('../../../public/images/arrow.png')}
                    />
                  }
                >
                  {subHospList.map((item) => {
                    return (
                      <Option value={item.value} key={item.value}>
                        {item.name}
                      </Option>
                    );
                  })}
                </KCSelect>
              )}
            </div>
            <div className="systemName">{currentHospName}</div>
            <Form onFinish={onFinish}>
              <Form.Item
                name="account"
                rules={[
                  { required: true, message: 'Please input your username!' },
                ]}
              >
                <Input className="input" />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[
                  { required: true, message: 'Please input your password!' },
                ]}
              >
                <Input.Password className="input" />
              </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>
        </div>
      ) : (
        children
      )}

      <div className="bottomLogo">
        <img className="logo" src={logo} />
        <div className="copyright">© 2021 康程智医（成都）技术部出品</div>
      </div>
    </div>
  );
};

export default LoginPage;
