import BlueTable from '@/components/BlueTable';
import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';
import services from '@/services';
import { useSetState } from 'ahooks';
import { DatePicker, Flex } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import styles from './index.less';

interface PipelineAssessmentProps {
  facilityType?: string;
  metaData: any;
}

interface MainAssessmentType {
  pipelineName: string;
  assessmentType: string;
  startDate: string;
  endDate: string;
  mainContent: string;
  result: string;
  operation: string;
}

interface AuxiliaryAssessmentType {
  pipelineName: string;
  facilityType: string;
  startDate: string;
  endDate: string;
  mainIssues: string;
  suggestion: string;
}

const PipelineAssessment: React.FC<PipelineAssessmentProps> = ({
  facilityType: defaultFacilityType,
  metaData,
}) => {
  const [year, setYear] = useState<dayjs.Dayjs>(dayjs().subtract(1, 'year'));
  const [facilityType, setFacilityType] = useState(
    defaultFacilityType || 'main',
  );
  const { dispatch } = useGlobalModalServices();

  const [dataSource, setDataSource] = useSetState<any>({});

  const btPageInfo = useRef({
    page: 0,
    pageSize: 10,
    total: 0,
  });

  const fsssPageInfo = useRef({
    page: 0,
    pageSize: 10,
    total: 0,
  });

  // 当外部传入的facilityType变化时更新内部状态
  useEffect(() => {
    if (defaultFacilityType) {
      setFacilityType(defaultFacilityType);
    }
  }, [defaultFacilityType]);

  const getBtData = (page: number) => {
    services.DataBase.getSjdzInfoData({
      typeCode: 'hyzm-gl-btjgjcpg',
      params: {
        startTime: year.startOf('year').format('YYYY-MM-DD'),
        endTime: year.endOf('year').format('YYYY-MM-DD'),
        glId: metaData?.id,
        pageSize: 10,
        pageNo: page,
      },
    }).then((res) => {
      if (res.code === 200) {
        const { list, page } = res.data?.data?.records[0];

        setDataSource({
          btTableData: list,
        });
        btPageInfo.current = {
          page: page.currentPage,
          pageSize: page.pageSize,
          total: page.total,
        };
      }
    });
  };

  const getFsssData = (page: number) => {
    services.DataBase.getSjdzInfoData({
      typeCode: 'hyzm-gl-ffssjclb',
      params: {
        startTime: year.startOf('year').format('YYYY-MM-DD'),
        endTime: year.endOf('year').format('YYYY-MM-DD'),
        glId: metaData?.id,
        pageSize: 10,
        pageNo: page,
      },
    }).then((res) => {
      if (res.code === 200) {
        const { list, page } = res.data?.data?.records[0];

        setDataSource({
          fsssTableData: list,
        });
        fsssPageInfo.current = {
          page: page.currentPage,
          pageSize: page.pageSize,
          total: page.total,
        };
      }
    });
  };

  // 管廊本体检测评估信息表格列配置
  const columnsMain: ColumnsType<MainAssessmentType> = [
    {
      title: '管廊名称',
      dataIndex: 'glmc',
      key: 'glmc',

      className: styles.tableCell,
    },
    {
      title: '检测评估类别名称',
      dataIndex: 'jcpglbmc',
      key: 'jcpglbmc',

      className: styles.tableCell,
    },
    {
      title: '开始日期',
      dataIndex: 'ksrq',
      key: 'ksrq',

      className: styles.tableCell,
    },
    {
      title: '完成日期',
      dataIndex: 'wcrq',
      key: 'wcrq',

      className: styles.tableCell,
    },
    {
      title: '主要内容',
      dataIndex: 'zynr',
      key: 'zynr',

      className: styles.tableCell,
    },
    {
      title: '结果',
      dataIndex: 'jg',
      key: 'jg',
      className: styles.tableCell,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',

      render: (_, record) => (
        <span
          className={styles.operation}
          onClick={() => {
            dispatch.push(
              'PipelineAssessmentDetail',
              {
                props: {
                  metaData: record,
                },
              },
              3,
            );
          }}
        >
          详情
        </span>
      ),
    },
  ];

  useEffect(() => {
    getBtData(0);
    getFsssData(0);
  }, [year]);

  // 附属设施检测评估基础信息表格列配置
  const columnsAuxiliary: ColumnsType<AuxiliaryAssessmentType> = [
    {
      title: '管廊名称',
      dataIndex: 'glmc',
      key: 'glmc',

      className: styles.tableCell,
    },
    {
      title: '附属设施所属类别',
      dataIndex: 'fssssslbmc',
      key: 'fssssslbmc',

      className: styles.tableCell,
    },
    {
      title: '开始日期',
      dataIndex: 'ksrq',
      key: 'ksrq',

      render(value, record, index) {
        return dayjs(value).format('YYYY-MM-DD');
      },
      className: styles.tableCell,
    },
    {
      title: '完成日期',
      dataIndex: 'wcrq',
      key: 'wcrq',

      render(value, record, index) {
        return dayjs(value).format('YYYY-MM-DD');
      },
      className: styles.tableCell,
    },
    {
      title: '主要问题',
      dataIndex: 'zywt',
      key: 'zywt',

      className: styles.tableCell,
    },
    {
      title: '维护建议',
      dataIndex: 'whjy',
      key: 'whjy',

      className: styles.tableCell,
    },
  ];

  return (
    <div className={styles.container}>
      {/* 筛选条件区域 */}
      <div className={styles.filters}>
        <Flex gap={20} align="center">
          {/* <span className={styles.label}>评估时间</span> */}
          <DatePicker
            value={year}
            onChange={(date) => {
              if (date) {
                setYear(date);
              }
            }}
            picker="year"
            format="YYYY年"
            className={styles.datePicker}
          />
          {/* <span className={styles.label} style={{marginLeft: '40px'}}>评估类型</span> */}
          <div className={styles.facilityTabs}>
            <div
              className={`${styles.facilityTab} ${
                facilityType === 'main' ? styles.active : ''
              }`}
              onClick={() => setFacilityType('main')}
            >
              管廊本体检测评估信息
            </div>
            <div
              className={`${styles.facilityTab} ${
                facilityType === 'auxiliary' ? styles.active : ''
              }`}
              onClick={() => setFacilityType('auxiliary')}
            >
              附属设施检测评估基础信息
            </div>
          </div>
        </Flex>
      </div>

      {/* 表格区域 */}

      {facilityType === 'main' ? (
        <BlueTable
          columns={columnsMain}
          dataSource={dataSource.btTableData}
          scroll={{ y: 520 }}
          pagination={{
            total: btPageInfo.current.total,
            pageSize: 10,
            current: btPageInfo.current.page + 1,
            onChange(page) {
              getBtData(page - 1);
            },
          }}
        />
      ) : (
        <BlueTable
          columns={columnsAuxiliary}
          dataSource={dataSource.fsssTableData}
          scroll={{ y: 520 }}
          pagination={{
            total: fsssPageInfo.current.total,
            pageSize: 10,
            current: fsssPageInfo.current.page + 1,
            onChange(page) {
              getFsssData(page - 1);
            },
          }}
        />
      )}
    </div>
  );
};

export default PipelineAssessment;
