import React, { useState, useEffect, useRef } from "react";
import { Tabs, Badge, Spin, List, Avatar, Tag, Popover, notification } from "antd";
import { BellOutlined, LoadingOutlined } from "@ant-design/icons";
// svg 转组件
import { ReactComponent as NoticeSvg } from '../../../public/icons/notice.svg';
import type { NotificationPlacement } from 'antd/es/notification/interface';

// import { getallnotices, getUidNotices } from "@/api/caravan/User";

import styles from "./index.module.less";
import { useNavigate } from "react-router-dom";

enum EventStatus {
  todo = "rgba(255,255,255,1)",
  urgent = "#f5222d",
  doing = "#faad14",
  processing = "#1890ff"
}

const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;

const { TabPane} = Tabs;

const Context = React.createContext({ name: 'Default' });

const Notice: React.FC = () => {
  const [visible, setVisible] = useState(false);
  const [noticeList, setNoticeList] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const noticeCount = 10;
  const intervalHandle: any = useRef(null);
  const [noticeNum, setNoticeNum] = useState(0);

  const noticeListFilter = <T extends any>(type: T) => {
    return noticeList.filter(notice => notice.type === type) as any[];
  };
  const navigate = useNavigate();
  const toManagePage = () => {
    navigate("/notice");
  };
  const getNotice = async () => {
    //查看我是否有新消息 无论如何
    // setLoading(true);
    //无论如何，清掉定时器,使用了 ref,肯定能拿到指针。
    //并且启动一个定时器，定时刷新我的消息
    clearTimeout(intervalHandle.current);
    intervalHandle.current = setTimeout(() => {
      setNoticeNum(Math.ceil(Math.random() * 1000));
    }, 1000 * 60 * 60);
    // getUidNotices()
    //   .then(result => {
    //     setLoading(false);
    //     if (result.status && result.data && Array.isArray(result.data.data)) {
    //       setNoticeList(result.data.data);
    //     }
    //   })
    //   .catch(() => {
    //     setLoading(false);
    //   });
    // getallnotices();
  };
  // const [api, contextHolder] = notification.useNotification();

  // const openNotification = (placement: NotificationPlacement) => {
  //   api.info({
  //     message: `Notification ${placement}`,
  //     description: <Context.Consumer>{({ name }) => `Hello, ${name}!`}</Context.Consumer>,
  //     placement,
  //   });
  // };

  useEffect(() => {
    getNotice();
  }, [noticeNum]);
  // const ws = new WebSocket("ws://localhost:3000/");

  // useEffect(() => {

  //    console.log(ws);
  //   // ws.onopen = function () {
  //   //   setInterval(function () {
  //   //     ws.send("客户端消息");
  //   //   }, 2000);
  //   // };

  //   ws.onmessage = function (e) {
  //     console.log(e.data);
  //     openNotification('topRight')
  //   }
  // }, []);
  useEffect(() => {
    return () => {
      clearTimeout(intervalHandle.current);
    };
  }, []);

  const onClear = () => {
    // ws.send("客户端消息");
  };
  const onViewMore = () => {};
  const tabsData = [
    {
      title: 'Ant Design Title 1',
      time: '刚刚'
    },
    {
      title: 'Ant Design Title 2Ant Design Title 2Ant Design Title 2Ant Design Title 2Ant Design Title 2Ant Design Title 2Ant Design Title 2',
      time: '刚刚'
    },
    {
      title: 'Ant Design Title 3',
      time: '刚刚'
    },
    {
      title: 'Ant Design Title 4',
      time: '刚刚'
    },
  ];
  const tabs = (
    <div className={styles.topNotice}>
      <Spin tip="Loading..." indicator={antIcon} spinning={loading}>
        <List
          dataSource={tabsData}
          renderItem={item => (
            <List.Item onClick={() => toManagePage()} style={{ cursor: "pointer" }}>
              <List.Item.Meta
                description={
                  <div>
                    <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8, fontWeight: 600 }}>
                      <span style={{ fontSize: "14px", color: "#333" }}>系统消息</span>
                      <Tag bordered={false} color="error" style={{ marginInlineEnd: 0, fontWeight: 400 }}>
                        紧急
                      </Tag>
                    </div>
                    <div style={{ fontSize: "14px", color: "#333" }}>
                      {item.title}
                    </div>
                    <div style={{ color: "#999" }}>{item.time}</div>
                  </div>
                }
              />
            </List.Item>
          )}
        />
      </Spin>
    </div>
  );
  return (
    <div style={{display: 'flex'}}>
    {/* {contextHolder} */}
      <Popover
        content={tabs}
        overlayClassName="bg-2"
        placement="bottomRight"
        trigger={['click']}
        open={visible}
        onOpenChange={v => setVisible(v)}
        arrow={{pointAtCenter: true}}
        overlayStyle={{
          width: 396,
        }}
      >
        {/* <Tooltip
          title={'消息通知'}
        > */}
          <Badge count={noticeList.length || noticeCount} overflowCount={999} offset={[8, -2]}>
            <span>
              {/* <BellOutlined style={{ fontSize: "18px" }} /> */}
              <NoticeSvg style={{ fontSize: "18px" }} />
            </span>
          </Badge>
        {/* </Tooltip> */}
      </Popover>
  </div>
  );
};

export default Notice;
