import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import { queryGateOpList } from '@/services/safety';
import { useParams, useRequest } from '@umijs/max';
import { Table } from 'antd';
import { useEffect, useRef, useState } from 'react';
const DoorDetail = () => {
  const { projectId } = useParams();
  const [list, setList] = useState([]);
  const [curPagination, setCurPagination] = useState({});

  const bottomAreaOfList = useRef();
  // 是否已经发送请求 防止发送多次同样的请求
  const load = useRef();

  const { run, loading } = useRequest((data) => queryGateOpList(data), {
    defaultParams: [{ project_id: projectId }],
    onSuccess: (data) => {
      load.current = false;
      setList([...list, ...data.list]);
      setCurPagination(data.pagination);
    },
  });
  const columns = [
    {
      title: '时间',
      dataIndex: 'created_time',
      key: 'created_time',
      align: 'center',
      width: 160,
    },
    {
      title: '人员',
      dataIndex: 'user_name',
      key: 'user_name',
      align: 'center',
      width: 110,
    },
    {
      title: '门禁名称',
      dataIndex: 'gate_name',
      key: 'gate_name',
      align: 'center',
      width: 140,
    },
    {
      title: '事件',
      dataIndex: 'event_type',
      key: 'event_type',
      align: 'center',
    },
    {
      title: '验证方式',
      dataIndex: 'check_type',
      key: 'check_type',
      align: 'center',
      width: 140,
    },
    {
      title: '出入状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 140,
    },
  ];

  const handleScroll = () => {
    const { current, total } = curPagination;
    if (list.length >= total) {
      return;
    }
    const rect = bottomAreaOfList.current.getBoundingClientRect();
    const isVisible =
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <=
        (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth);

    if (isVisible && !load.current) {
      load.current = true;
      run({ project_id: projectId, current: current + 1 });
    }
  };

  // 监听滚动事件
  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, [loading]);

  return (
    <PageContent closeable={false}>
      <PageTitle children="门禁日志" returnable />

      <Table
        loading={loading}
        style={{ marginTop: '30px' }}
        dataSource={list}
        columns={columns}
        pagination={false}
      />
      <div
        ref={bottomAreaOfList}
        style={{
          height: '1px',
        }}
      />
      <div />
    </PageContent>
  );
};
export default DoorDetail;
