import services from '@/services';
import { DatePicker, Divider, Flex, Skeleton } from 'antd';
import classNames from 'classnames';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import styles from './index.less';

interface DefectRecord {
  planName: string;
  deviceCode: string;
  deviceName: string;
  inspectionType: string;
  defectDesc: string;
  location: string;
  status: string;
  discoveryDate: string;
  treatment: string;
  remark: string;
}

const PipelineDefectList: React.FC = ({ metaData }: any) => {
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(1, 'month').set('date', 21),
    dayjs().set('date', 20),
  ]);
  const [dataSource, setDataSource] = useState<any[]>([]);

  const pageInfo = useRef({
    total: 0,
    currentPage: 0,
  });

  const [loading, setLoading] = useState(false);

  const loadMoreData = (page?: number) => {
    // console.log('触发');
    if (loading) {
      return;
    }
    setLoading(true);
    services.DataBase.getSjdzInfoData({
      typeCode: 'hyzm-gl-rcxclb',
      params: {
        pageNo: page != undefined ? page : pageInfo.current.currentPage + 1,
        pageSize: '10',
        glId: metaData?.id,
        startTime: dateRange[0].format('YYYY-MM-DD'),
        endTime: dateRange[1].format('YYYY-MM-DD'),
      },
    })
      .then((res) => {
        if (res.code === 200) {
          const record = res.data?.data?.records?.[0];
          pageInfo.current = record.page;

          if (page === 0) {
            setDataSource(record.list);
          } else
            setDataSource((pre) => {
              return [...pre, ...record.list];
            });
        }

        console.log(pageInfo);
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    loadMoreData(0);
  }, [dateRange]);
  const renderDefectRecord = (record: any) => {
    return (
      <div className={styles.recordItem}>
        <div className={styles.recordHeader}>
          <span className={styles.planName}>{record.bhsssbmc}</span>
          {record.sfjjbh === '是' && (
            <span
              className={classNames(styles.tag, {
                [styles.tagUrgent]: true,
              })}
            >
              紧急病害
            </span>
          )}
          {record.sfzdbh === '是' && (
            <span
              className={classNames(styles.tag, {
                [styles.tagSerious]: true,
              })}
            >
              重大病害
            </span>
          )}
        </div>
        <div className={styles.recordContent}>
          <div className={styles.infoRow}>
            <div className={styles.infoItem}>
              <span className={styles.label}>巡检计划名称：</span>
              <span className={styles.value}>{record.xjjhmc}</span>
            </div>
            <div className={styles.infoItem}>
              <span className={styles.label}>病害发现日期：</span>
              <span className={styles.value}>
                {dayjs(record.bhfxrq).format('YYYY-MM-DD')}
              </span>
            </div>
          </div>
          <div className={styles.infoRow}>
            <div className={styles.infoItem}>
              <span className={styles.label}>巡检对象类别：</span>
              <span className={styles.value}>{record.xjdxlbmc}</span>
            </div>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>病害描述：</span>
            <span className={styles.value}>{record.bhms}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>位置描述：</span>
            <span className={styles.value}>{record.wzms}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>处理情况：</span>
            <span className={styles.value}>{record.clqk}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.label}>备注：</span>
            <span className={styles.value}>{record.bz}</span>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className={styles.container}>
      {/* 筛选条件区域 */}
      <div className={styles.filters}>
        <Flex gap={20} align="center">
          <span className={styles.label}>巡检时间</span>
          <DatePicker.RangePicker
            value={dateRange}
            onChange={(dates) => {
              if (dates && dates[0] && dates[1]) {
                setDateRange([dates[0], dates[1]]);
              }
            }}
            format="YYYY年MM月DD日"
            className={styles.datePicker}
          />
        </Flex>
      </div>

      {/* 记录列表区域 */}
      <div className={styles.recordList} id="scrollableDiv">
        <InfiniteScroll
          dataLength={dataSource.length}
          next={loadMoreData}
          hasMore={dataSource.length < pageInfo.current.total}
          loader={
            <Skeleton
              paragraph={{
                rows: 1,
                width: '100%',
              }}
              title={false}
              active
            />
          }
          endMessage={<Divider plain>没有更多了</Divider>}
          scrollableTarget="scrollableDiv"
        >
          {dataSource.map((record, index) => (
            <div key={index}>{renderDefectRecord(record)}</div>
          ))}
        </InfiniteScroll>
      </div>
    </div>
  );
};

export default PipelineDefectList;
