import React, { useState, useEffect, useRef } from 'react';
import { UserOutlined, LogoutOutlined, BellOutlined } from '@ant-design/icons';
import { Button, Space, Dropdown, Drawer, Row, Col, Image } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import msgWebsocket from '@/common/websocket/websocket';
import { setUserInfo } from '@/store/modules/user';
import { getUserInfo, getMessageList, getMessageCount, setRead, setAllRead } from '../request';
import bell from '../../assets/images/bell.png';
import point1 from '../../assets/images/point1.png';
import quit from '../../assets/images/quit.png';
import slide from '../../assets/images/slide.png';

import { useGlobalContext } from '../GlobalContext';

const items = [
  {
    key: 'userinfo',
    label: (
      <Button type='link' href='/userinfo'>
        个人中心
      </Button>
    ),
  },
];

const UserInfo = ({ props, extraSlot }) => {
  const navigator = useNavigate();
  const dispatch = useDispatch();
  const [showDrawer, setShowDrawer] = useState(false);
  const drawerRef = useRef(null);
  const { userInfo } = useSelector((state) => state.user);
  const [userInfos, setUserInfos] = useState({});
  const [messageList, setMessageList] = useState([]);
  const [page, setPage] = useState(1);
  const [page_size, setpage_size] = useState(10);
  const [drawerScrolled, setDrawerScrolled] = useState(false);
  // const [unreadMessagesNum, setUnreadMessagesNum] = useState(0);
  const { unreadMessagesNum, setUnreadMessagesNum } = useGlobalContext();
  const heartbeatInterval = useRef(null);
  const [isReadSet, setIsReadSet] = useState(false);
  const {
    webSocketInit,
    wsMessage,
    setWsMessage,
    reconnect,
    sendMessage,
    closeWebSocket,
    wsReadyState,
  } = msgWebsocket({});
  const [messageListLoaded, setMessageListLoaded] = useState(false); // 新增状态来表示消息列表是否已加载

  // const [userInfos]
  // 推出登录
  const signOut = () => {
    localStorage.clear();
    navigator('/user/login');
  };
  const getInfo = async () => {
    const data = await getUserInfo();
    dispatch(setUserInfo(data));
    setUserInfos(data);
  };
  // 所有消息中心
  // 未读数
  const noneRead = async () => {
    const { num } = await getMessageCount();
    setUnreadMessagesNum(num);
  };
  // 部分已读
  const setMessageReaded = async (id) => {
    setRead({ id });
  };
  // 全部已读
  const setMessageALLReaded = async () => {
    setAllRead();
    setUnreadMessagesNum(0);
  };

  const getMessage = async () => {
    const { list } = await getMessageList({ page: 1, page_size });
    setMessageList(list);

    setMessageListLoaded(true); // 设置消息列表已加载的状态为true
  };
  // 加载下一页消息
  const loadNextPage = async () => {
    const nextPage = page + 1;
    const { list } = await getMessageList({ page: nextPage, page_size });
    setPage(nextPage);
    setMessageList((prevList) => [...prevList, ...list]);
  };
  useEffect(() => {
    getInfo();
    getMessage();
    noneRead();
  }, []);

  // 设置全部已读,且只调用一次
  useEffect(() => {
    if (!isReadSet && showDrawer && unreadMessagesNum > 0) {
      setIsReadSet(true);
    } else if (!showDrawer) {
      // noneRead();
    }
  }, [showDrawer, unreadMessagesNum, isReadSet]);

  // 加载消息的websocket
  useEffect(() => {
    if (userInfos.id > 0) {
      const wsUrl = `${import.meta.env.VITE_API_WEBSOCKET_URL}/ws`;
      // 建立websokect链接
      webSocketInit(wsUrl);
      // 获取websocket消息
      if (Object.entries(wsMessage).length > 0) {
        console.log('收到消息了');
        console.log(wsMessage);
        // 收到消息一个未读消息
        setUnreadMessagesNum(unreadMessagesNum + 1);
      }
    }
  }, [userInfos, wsMessage, wsReadyState]);

  // 重连websocket
  // useEffect(() => {
  //   if (wsReadyState.key === 3) {
  //     reconnect();
  //   }
  //   if (wsReadyState.key === 1 && userInfos.id > 0) {
  //     // 链接成功后发送消息
  //     sendMessage('{"userId":' + userInfos.id + '}');
  //     // 心跳
  //     heartbeatInterval.current = setInterval(() => {
  //       sendMessage('{"heart":1}');
  //     }, 10000);
  //     // 在组件卸载或 WebSocket 关闭时清除间隔，以防止内存泄漏
  //     return () => clearInterval(heartbeatInterval.current);
  //   }
  // }, [userInfos, wsReadyState]);
  let reconnectTimeoutId;
  // 重连websocket
  useEffect(() => {
    // ...其他逻辑不变...

    // 重连逻辑修改
    if (wsReadyState.key === 3) {
      clearTimeout(reconnectTimeoutId);
      reconnectTimeoutId = setTimeout(reconnect, 3000); // 3秒后重试
    }

    // 清理函数中取消定时器
    return () => {
      clearTimeout(reconnectTimeoutId);
      clearInterval(heartbeatInterval.current);
    };
  }, [userInfos, wsReadyState]);

  // 滚动消息抽屉翻页
  useEffect(() => {
    if (showDrawer) {
      const handleScroll = () => {
        const drawerElement = document.querySelector('.ant-drawer-body');
        if (
          drawerElement &&
          drawerElement.scrollTop + drawerElement.clientHeight >= drawerElement.scrollHeight
        ) {
          // 在抽屉滚动到底部时加载下一页数据
          loadNextPage();
          setDrawerScrolled(true);
          // 更新滚动位置，使用户能够继续向上滚动
          drawerElement.scrollTop = drawerElement.scrollHeight - drawerElement.clientHeight;
        } else {
          setDrawerScrolled(false);
        }
      };
      // 添加滚动事件监听
      document.querySelector('.ant-drawer-body').addEventListener('scroll', handleScroll);
      // 在组件卸载时移除滚动事件监听
      return () => {
        document.querySelector('.ant-drawer-body').removeEventListener('scroll', handleScroll);
      };
    }
  }, [drawerScrolled, showDrawer]);

  //
  // useEffect(() => {
  //   if (showDrawer) {
  //     const drawerElement = document.querySelector('.ant-drawer-body');

  //     // 获取上次关闭时保存的滚动位置
  //     const lastScrollPosition = localStorage.getItem('drawerScrollPosition');
  //     if (lastScrollPosition) {
  //       drawerElement.scrollTop = parseInt(lastScrollPosition, 10);
  //     }

  //     const handleScroll = () => {
  //       if (drawerElement.scrollTop + drawerElement.clientHeight >= drawerElement.scrollHeight) {
  //         // 在抽屉滚动到底部时加载下一页数据
  //         loadNextPage();
  //         setDrawerScrolled(true);
  //       } else {
  //         setDrawerScrolled(false);
  //       }
  //     };

  //     // 添加滚动事件监听
  //     drawerElement.addEventListener('scroll', handleScroll);

  //     // 在组件卸载时保存当前滚动位置
  //     return () => {
  //       localStorage.setItem('drawerScrollPosition', drawerElement.scrollTop.toString());
  //       drawerElement.removeEventListener('scroll', handleScroll);
  //     };
  //   }
  // }, [drawerScrolled, showDrawer]);

  // 在渲染时根据消息列表是否加载来决定显示哪个图标
  const renderBellIcon = () => {
    if (unreadMessagesNum > 0) {
      return (
        <span
          style={{
            display: 'inline-block',
            position: 'relative',
            width: '16px',
            height: '19px',
            pointerEvents: 'none',
          }}
        >
          <Image src={bell} style={{ width: 14 }} />
          <Image
            src={point1}
            style={{
              position: 'absolute',
              top: -18,
              right: -5,
              width: '12px',
              height: '12px',
            }}
          />
        </span>
      );
    } else {
      return (
        <span
          style={{
            display: 'inline-block',
            width: '16px',
            height: '19px',
            pointerEvents: 'none',
          }}
        >
          <Image src={bell} style={{ width: 14 }} />
        </span>
      );
    }
  };

  return (
    <div className='header-user'>
      <Drawer
        open={showDrawer}
        // closeIcon={false}
        closeIcon={
          <span
            style={{
              display: 'inline-block',
              width: '22px',
              height: '18px',
              cursor: 'pointer',
              pointerEvents: 'none',
            }}
          >
            <Image
              src={slide}
              style={{
                width: 14,
              }}
            />
          </span>
        }
        extra={
          <span
            style={{
              fontSize: '14px',
              color: '#999',
              cursor: 'pointer',
            }}
            draggable='false'
            onClick={() => setMessageALLReaded()}
          >
            全部已读
          </span>
        }
        onClose={() => {
          setShowDrawer(false);
          setMessageListLoaded(false);
        }}
      >
        {/* <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            padding: '0px 10px 20px 10px',
          }}
        >
          <span
            style={{
              display: 'inline-block',
              width: '22px',
              height: '18px',
              cursor: 'pointer',
              userSelect: 'none',
            }}
            draggable='false'
            onClick={() => {
              setShowDrawer(false);
              setMessageListLoaded(false);
              (e) => e.preventDefault();
            }}
            className='DrawerClose'
          >
            <Image
              src={slide}
              style={{
                width: 14,
                userSelect: 'none',
                WebkitUserDrag: 'none',
                userDrag: 'none',
                outline: 'none',
              }}
              draggable='false'
            />
          </span>

          <span
            style={{
              fontSize: '14px',
              color: '#999',
              cursor: 'pointer',
            }}
            draggable='false'
            onClick={() => setMessageALLReaded()}
          >
            全部已读
          </span>
        </div> */}
        {messageList &&
          messageList.length > 0 &&
          messageList.map((item, index) => (
            <Row
              key={item.id}
              className='processItem'
              style={{
                borderRadius: 4,
                border: '1px solid #E4E4E4',
                padding: 15,
                marginBottom: 20,
              }}
            >
              <Col span={1} style={{ marginRight: 15 }}>
                <Button
                  style={{
                    border: 'none',
                    background: '#fff',
                    display: 'inline-block',
                    width: '19px',
                    height: '22px',
                    pointerEvents: 'none',
                  }}
                  icon={
                    index < unreadMessagesNum && item.status === 0 ? (
                      <span
                        style={{
                          display: 'inline-block',
                          position: 'relative',
                          width: '16px',
                          height: '19px',
                          pointerEvents: 'none',
                        }}
                      >
                        <Image src={bell} style={{ width: 14 }} />
                        <Image
                          src={point1}
                          style={{
                            position: 'absolute',
                            top: -18,
                            right: -5,
                            width: '12px',
                            height: '12px',
                          }}
                        />
                      </span>
                    ) : (
                      <span
                        style={{
                          display: 'inline-block',
                          width: '16px',
                          height: '19px',
                          pointerEvents: 'none',
                        }}
                      >
                        <Image src={bell} style={{ width: 14 }} />
                      </span>
                    )
                  }
                ></Button>
              </Col>
              <Col span={22} className='process'>
                <div
                  className='head'
                  style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    marginBottom: 10,
                  }}
                >
                  <strong>审核通知</strong>
                  <span
                    className='date'
                    style={{
                      color: '#999999',
                      fontSize: 12,
                    }}
                  >
                    {item.create_time}
                  </span>
                </div>
                <div
                  className='content'
                  onClick={() => {
                    item.isRead = true;
                    if (item.type === 1) {
                      const handleType1 = async () => {
                        await navigator('/books/audit/dataset');
                        await setMessageReaded(item.id);
                        await getMessage();
                        await noneRead();
                      };
                      handleType1();
                    } else if (item.type === 2) {
                      const handleType2 = async () => {
                        await navigator('/books/sale/dataset');
                        await setMessageReaded(item.id);
                        await getMessage();
                        await noneRead();
                      };

                      handleType2();
                      // setUnreadMessagesNum(0);
                    } else {
                      const handleType3 = async () => {
                        await setMessageReaded(item.id);
                        await getMessage();
                        await noneRead();
                      };

                      handleType3();
                    }
                    setShowDrawer(false);
                  }}
                  style={{ cursor: 'pointer' }}
                >
                  {item.content}
                </div>
              </Col>
            </Row>
          ))}
      </Drawer>

      <Space>
        <div
          className='header-user-bell'
          style={{
            width: 36,
            height: 36,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            border: 'none',
            marginTop: '10px',
          }}
        >
          {' '}
          <Button
            style={{
              border: 'none',
              background: '#f6f6f6',
            }}
            onClick={() => {
              setPage(1);
              setShowDrawer(true);
              getMessage();
              // setMessageReaded();
            }}
            icon={renderBellIcon()}
          ></Button>
        </div>
        <Dropdown menu={{ items }} arrow>
          <Button
            type='link'
            className='logout'
            onClick={(e) => e.preventDefault()}
            style={{
              padding: 10,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              border: 'none',
              marginTop: '10px',
            }}
          >
            <Space>
              {userInfos.pic ? (
                <img
                  src={userInfos.pic}
                  style={{ width: '25px', height: '28px', borderRadius: '50%', marginTop: '6px' }}
                />
              ) : (
                <UserOutlined />
              )}
              {/* {<UserOutlined />} */}
              {userInfos.real_name}
            </Space>
          </Button>
        </Dropdown>
        <div
          style={{
            width: 36,
            height: 36,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <Button
            type='link'
            onClick={signOut}
            className='logout'
            style={{
              marginTop: '10px',
            }}
            icon={
              <span
                style={{
                  display: 'inline-block',
                  width: '17px',
                  height: '18px',
                  pointerEvents: 'none',

                  alignItems: 'center',
                  justifyContent: 'center',
                }}
              >
                <Image src={quit} style={{ width: 18 }} />
              </span>
            }
          >
            {/* <LogoutOutlined /> */}
          </Button>
        </div>
      </Space>
    </div>
  );
};

export default UserInfo;
