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 MaintenanceDataType {
  pipelineName: string;
  facilityName: string;
  planName: string;
  discoveryDate: string;
  maintenanceDate: string;
  operation: string;
}

interface RoutineDataType {
  pipelineName: string;
  objectName: string;
  objectCode: string;
  lastMaintenanceDate: string;
  maintenanceCycle: string;
  maintenanceResult: string;
  remark: string;
}

const PipelineMaintenance: React.FC = ({ metaData }: any) => {
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(1, 'month').set('date', 21),
    dayjs().set('date', 20),
  ]);
  const [facilityType, setFacilityType] = useState('all');
  const [activeTab, setActiveTab] = useState('daily');
  const { dispatch } = useGlobalModalServices();
  const [dataSource, setDataSource] = useSetState<any>({});

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

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

  const getWxData = (page: number) => {
    const type =
      facilityType === 'all'
        ? undefined
        : facilityType === 'main'
        ? '本体'
        : '附属设施';

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

        const newList = list.map((v: any) => {
          return {
            pipelineName: v.glmc,
            discoveryDate: v.bhfxrq,

            maintenanceDate: v.wcrq,

            facilityName: v.bhsssbmc,
            inspectionResult: v.xjjg,
            ...v,
          };
        });
        setDataSource({
          whTableData: newList,
        });
        wxPageInfo.current = {
          page: page.currentPage,
          pageSize: page.pageSize,
          total: page.total,
        };
      }
    });
  };

  const getByData = (page: number) => {
    const type =
      facilityType === 'all'
        ? undefined
        : facilityType === 'main'
        ? '本体'
        : '附属设施';

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

        setDataSource({
          byTableData: list,
        });
        byPageInfo.current = {
          page: page.currentPage,
          pageSize: page.pageSize,
          total: page.total,
        };
      }
    });
  };
  const columnsMaintenance: ColumnsType<MaintenanceDataType> = [
    {
      title: '管廊名称',
      dataIndex: 'pipelineName',
      key: 'pipelineName',
      width: 200,
      className: styles.tableCell,
    },
    {
      title: '病害设施设备名称',
      dataIndex: 'facilityName',
      key: 'facilityName',
      width: 200,
      className: styles.tableCell,
    },

    {
      title: '病害发现日期',
      dataIndex: 'discoveryDate',
      key: 'discoveryDate',
      width: 250,
      className: styles.tableCell,
    },
    {
      title: '完成日期',
      dataIndex: 'maintenanceDate',
      key: 'maintenanceDate',
      width: 250,
      className: styles.tableCell,
    },
    {
      title: '工程量',
      dataIndex: 'gcl',
      key: 'gcl',
      width: 250,
      className: styles.tableCell,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: 120,
      render: (_, record) => (
        <span
          className={styles.operation}
          onClick={() => {
            if (true) {
              dispatch.push('PipelineMaintenanceDetail', {
                props: {
                  metaData: record,
                },
              });
            }
          }}
        >
          详情
        </span>
      ),
    },
  ];

  const columnsRoutine: ColumnsType<RoutineDataType> = [
    {
      title: '管廊名称',
      dataIndex: 'glmc',
      key: 'glmc',
      width: 200,
      className: styles.tableCell,
    },
    {
      title: '保养对象名称',
      dataIndex: 'bydxmc',
      key: 'bydxmc',
      width: 200,
      className: styles.tableCell,
    },
    {
      title: '上一次保养日期',
      dataIndex: 'sycbyrq',
      key: 'sycbyrq',
      width: 200,
      className: styles.tableCell,
    },
    {
      title: '保养周期',
      dataIndex: 'byzq',
      key: 'byzq',
      width: 150,
      className: styles.tableCell,
    },
  ];

  /** 获取统计信息 */
  const getStatisticsInfo = () => {
    services.DataBase.getSjdzInfoData({
      typeCode: 'hyzm-gl-rxwhqk',
      params: {
        startTime: dateRange[0].format('YYYY-MM-DD'),
        endTime: dateRange[1].format('YYYY-MM-DD'),
        glId: metaData.id,
      },
    }).then((res) => {
      if (res.code === 200) {
        const data = res.data?.data?.records[0];
        const repairNum = data.btjg.rcwx + data.fsss.rcwx;
        const upkeepNum = data.btjg.rcby + data.fsss.rcby;
        setDataSource({
          statisticsInfo: {
            all: {
              repairNum,
              upkeepNum,
            },
            main: {
              repairNum: data.btjg.rcwx,
              upkeepNum: data.btjg.rcby,
            },
            auxiliary: {
              repairNum: data.fsss.rcwx,
              upkeepNum: data.fsss.rcby,
            },
          },
        });
      }
    });
  };

  useEffect(() => {
    getStatisticsInfo();
    getWxData(0);
    getByData(0);
  }, [dateRange]);

  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}
          />
          <span className={styles.label} style={{ marginLeft: '40px' }}>
            维护设施类型
          </span>
          <div className={styles.facilityTabs}>
            <div
              className={`${styles.facilityTab} ${
                facilityType === 'all' ? styles.active : ''
              }`}
              onClick={() => setFacilityType('all')}
            >
              全部
            </div>
            <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>

      {/* 统计数据区域 */}
      <Flex gap={40} className={styles.stats}>
        <div
          className={`${styles.statsTab} ${
            activeTab === 'daily' ? styles.active : ''
          }`}
          onClick={() => setActiveTab('daily')}
        >
          日常维修
          <span className={styles.count}>
            {dataSource.statisticsInfo?.[facilityType].repairNum}
          </span>
          处
        </div>
        <div
          className={`${styles.statsTab} ${
            activeTab === 'routine' ? styles.active : ''
          }`}
          onClick={() => setActiveTab('routine')}
        >
          日常保养
          <span className={styles.count}>
            {dataSource.statisticsInfo?.[facilityType].upkeepNum}
          </span>
          处
        </div>
      </Flex>

      {/* 表格区域 */}
      {activeTab === 'daily' ? (
        <BlueTable
          columns={columnsMaintenance}
          dataSource={dataSource.whTableData}
          scroll={{ y: 430 }}
          pagination={{
            total: wxPageInfo.current.total,
            pageSize: 10,
            current: wxPageInfo.current.page + 1,
            onChange(page) {
              getWxData(page - 1);
            },
          }}
        />
      ) : (
        <BlueTable
          columns={columnsRoutine}
          dataSource={dataSource.byTableData}
          scroll={{ y: 430 }}
          pagination={{
            total: byPageInfo.current.total,
            pageSize: 10,
            current: byPageInfo.current.page + 1,
            onChange(page) {
              getByData(page - 1);
            },
          }}
        />
      )}
    </div>
  );
};

export default PipelineMaintenance;
