import { Layout, Dropdown, Menu, Modal, Input, Form, Space, Button } from 'antd';
import { withRouter } from 'react-router'
import { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import MyMessage from "../MyMessage";
import { panesNow } from '@reducers/tabPanes.js';
import { getTimeDetail,getCookie,setCookie } from '@utils/index';
import logo from '@images/logo.png';
import msg from '@images/msg.png';
import me from '@images/me.png';
import down from '@images/down.png';
import './index.less'
import { message } from "antd/lib/index";
import { add, active } from '@reducers/tabPanes'
import { setUnReadNum} from '@reducers/userInfo.js';
import apiObj from '@api/index';

const { post, api, xPost } = apiObj;
const propTypes = {

}
const defaultProps = {};
const { Header } = Layout;

function AHeader({ history, hideName }) {
    const dispatch = useDispatch();//当前选中的菜单
    const { panes } = useSelector(state => {
        return state.tabPanes;
    });
    const [form] = Form.useForm();
    const [dateTime, setDateTime] = useState('');
    const [visible, setVisible] = useState(false);
    //const [unReadNum,setUnReadNum] = useState(0);
    const [systemName,setSystemName] = useState("");
    //const [userName,setUserName] = useState("");
    const userName = getCookie("userName");
    const hospitalId = getCookie("hospitalId");
    const softwareArr = JSON.parse(localStorage.getItem("software"));

    const { user, unReadNum } = useSelector((state) => {
        return state.userInfo;
    });
    //退出
    function loginOut() {
        localStorage.removeItem("token");
        localStorage.removeItem("systemId");
        localStorage.removeItem("hospitalId");
        localStorage.removeItem("software")
        setCookie();
        dispatch(panesNow([]));
        history.push('/login');
    }
    //获取未读消息数量
    function getNotNoticeCount(){
        xPost(api.getNotNoticeCount).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data||{};
                let count = data.count;
                count = count>99?'99+':count;
			  	dispatch(setUnReadNum(count));
                initWebsocket(count);
            } else {
                //message.warning(res.data.msg || '请求失败');
            }
        })
    }
    //未读消息页面显示并带入未读筛选条件
    function showMyMsgPage(){
        const pageKey = 'ZNTZ-WDTZ&我的通知';
        const item = panes.find((it) => it.key === pageKey);
        if (item) {   //已存在当前tab，则定位即可不增加
            dispatch(active({idName:pageKey,isUnRead:true}));
            return;
        }
        dispatch(
            add({ title: '我的通知', content: <MyMessage />, key: pageKey,isUnRead:true})
        )
    }
    async function initWebsocket(num){
        const mqtt = require('mqtt');
        const client  = mqtt.connect(api.websocketUrl);
        //const hisId = getCookie("hospitalId");
        client.on('connect', function () {
            client.subscribe(hospitalId+"-"+user.id, function (err) {
                if (!err) {
                    console.log(hospitalId+"-"+user.id+"订阅成功")
                }
            })
        })

        client.on('message', function (topic, message) {
            let n = num>unReadNum?num:unReadNum;
            setUnReadNum(+n)
            console.log('收到消息+1：',message.toString())
        })
    }
    //获取系统、用户名称用于页头显示
    function getSysName(){
	  const mySys = (softwareArr||[]).find((it)=>{
		return it.id === +hospitalId;
	  });
	  if(mySys){
		setSystemName(mySys.name);
      }
    }
    /*function handleUserInfo(data){
        const { userInfo, software } = data;
        const sysId = getCookie("systemId");
        const hisId = getCookie("hospitalId");
        const sys = software.find((it) => {
            return +it.id === +sysId
        });
        dispatch(setUser(userInfo));
        sys && dispatch(setSys({ sysId, sysName: sys.name, hisId }));
    }
    //获取组织列表
    function getUserHos() {
        return new Promise((resolve)=>{
            xPost(api.getUserHospitals).then((res)=>{
                resolve(res);
            });
        });
    }*/
    //修改密码
    function changePsd() {
        setVisible(true)
    }
    //时间
    let interVal;
    function countTime() {
        interVal = setInterval(() => {
            setDateTime(getTimeDetail())
        }, 1000);
    }
    function cancel() {
        setVisible(false)
        form.resetFields();
    }
    const onFinish = values => {
        const params = values
        post(api.midifyPassword, params).then((res) => {
            if (res.data.code === 200) {
                message.success('修改成功');
            }
        })
    }
    useEffect(() => {
	    getSysName();
        countTime();
        getNotNoticeCount();
        return function clearUp() {
            clearInterval(interVal)
        }
    }, ['unReadNum']);
    const menu = (
        <Menu>
            <Menu.Item key="0">
                <span className='changePsd' onClick={changePsd}>修改密码</span>
            </Menu.Item>
            <Menu.Divider />
            <Menu.Item key="3" onClick={loginOut}>退出</Menu.Item>
        </Menu>
    );
    return (
        <Header className='page-header'>
            <img className='logo' src={logo} alt="" />
            {hideName ? '' : <><span className='break-line'>|</span>
                <span className='sys-name'>{systemName}</span></>}
            <div className='infos'>
                <span className='time'>{dateTime}</span>
                <span className='break-line'>|</span>
                <div className="unRead-msg-cont" onClick={showMyMsgPage}>
                    <img className='msg-icon' src={msg} alt="未读消息"/>
                    {unReadNum?<span className='unRead-msg'>{unReadNum}</span>:''}
                </div>
                <div className="user">
                    <Dropdown overlay={menu} trigger={['click']}>
                        <span className="ant-dropdown-link" onClick={e => e.preventDefault()}>
                            <img className='user-icon' src={me} alt="用户头像" />
                            <i className='user-name'>{userName}</i>
                            <img src={down} alt="" />
                        </span>
                    </Dropdown>
                </div>
            </div>
            {visible ?
                <Modal
                    title='修改密码'
                    okText='确定'
                    cancelText='取消'
                    width={'40%'}
                    visible={visible}
                    onCancel={cancel}
                    footer={null}
                    forceRender={true}
                    centered={true}
                >
                    <Form
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 16 }}
                        form={form}
                        name="register"
                        onFinish={onFinish}
                    >

                        <Form.Item
                            name="password"
                            label="原密码"
                            required
                        >
                            <Input.Password placeholder="8-12位大小写字母、数字、特殊字符" />
                        </Form.Item>
                        <Form.Item
                            name="modifyPassword"
                            label="新密码"
                            dependencies={['password']}
                            rules={[
                                {
                                    required: true,
                                    message: '8-12位大小写字母、数字、特殊字符',
                                },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        const passwordReg = /^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)(?=.*?[#@*&.]).*$/;
                                        if (!value || getFieldValue('password') === value) {
                                            return Promise.reject(new Error('新密码不能于原密码相同'));
                                        }
                                        if (!passwordReg.test(value)) {
                                            return Promise.reject(new Error('密码必须同时包含大写字母、小写字母和数字'));
                                        }
                                        if (value.length < 8 || value.length > 12) {
                                            return Promise.reject(new Error('密码长度8-12位'));
                                        }
                                    },
                                }),
                            ]}
                        >
                            <Input.Password placeholder="8-12位大小写字母、数字、特殊字符" />
                        </Form.Item>
                        <Form.Item
                            name="againnewpassword"
                            label="确认新密码"
                            dependencies={['password']}
                            rules={[
                                {
                                    required: true,
                                    message: '8-12位大小写字母、数字、特殊字符',
                                },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (!value || getFieldValue('modifyPassword') === value) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('两次密码不一致,请确认密码'));
                                    },
                                }),
                            ]}
                        >
                            <Input.Password placeholder="8-12位大小写字母、数字、特殊字符" />
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Space size="middle">
                                <Button htmlType="button" onClick={e => cancel()}>
                                    取消
                                </Button>
                                <Button type="primary" htmlType="submit">
                                    保存
                                </Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </Modal>
                : ''}
        </Header>

    )
}

AHeader.propTypes = propTypes;
AHeader.defaultProps = defaultProps;
export default withRouter(AHeader);