/*
 * @Author: your name
 * @Date: 2021-11-09 14:58:08
 * @LastEditTime: 2021-11-19 16:42:22
 * @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 } from 'react'
import { Select, message } from 'antd';
import './style.less'

import { useModel, history } from 'umi';

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

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

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

import { getSubHosp, login,getHospSubSystemList } from '@/service/login';

const { Option } = Select;

const LoginPage: React.FC<any> = () => {
    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<SystemListItem[]>([]);  //可选平台列表
    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 { list } = await getSubHosp();
        setSubHospList(list);
    }

    const getHospSubSystemListFunc = async ()=>{
         const data = await getHospSubSystemList();
         if(data)setSystemList(data);
    }

    const onFinish = async (values:LoginPageTypes.LoginInfo) => {
        setIfLoading(true);
        const resp = await login(values);
        setIfLoading(false);
        if (resp) {
            message.success('登录成功！');
            await getHospSubSystemListFunc();
            await setInitialState((s) => ({ ...s, userData: resp,systemLists:systemList }));
            localStorage.setItem('KC-MiddlePlatformUserData', JSON.stringify(resp));
            
            if(systemList.length>1){
                //当前医院拥有多个子平台时，进入选择
                setIfSelectSystem(true);
            }else {
                //否则直接进入首页
                const { query } = history.location;
                const { redirect } = query as { redirect: string };
                history.push(redirect || '/');
                return;
            }
            setIfLoading(false);
            
        }
    }

    const selectSysHandle = (systemInfo:LoginPageTypes.SystemListItem)=>{
        const { query } = history.location;
        const { redirect } = query as { redirect: string };
        history.push(redirect || '/');
    }

    useEffect(() => {
        //根据hospSign获取分院信息
        getSubHospFunc();
    }, []);




    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>
            <div className='loginBlock'>
                {
                    ifSelectSystem ? (
                        <div className='systemSelector'>
                            {
                                systemList.map((t)=>(
                                      <div className='sysItem' key={t.id} onClick={()=>selectSysHandle(t)}>
                                          <img className='icon' src={t.icon} alt="" />
                                          <span className='sysName'>{t.name}</span>
                                      </div>
                                ))
                            }
                        </div>
                    ) : (
                        <>
                            <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: 200 }} 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'>欢迎进入医务管理系统</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>
            <div className='bottomLogo'>
                <img className='logo' src={logo} />
                <div className='copyright'>© 2021 康程智医（成都）技术部出品</div>
            </div>
        </div>
    )
}

export default LoginPage;