import React, { useState, useEffect } from 'react';
import {
  Button,
  Table,
  Space,
  Input,
  Select,
  Form,
  Tooltip,
  Tag,
  DatePicker,
  message
} from 'antd';
import type { TablePaginationConfig } from 'antd';
import {
  SearchOutlined,
  DeleteOutlined,
  ExportOutlined
} from '@ant-design/icons';
import { useIntl } from 'umi';
import CategorySelector from '@/components/CategorySelector/CategorySelector';
import { SupplierTypeText } from '@/dicts/dataStatistics';
import { getSupplierQualificationExpire, exportSupplierQualificationExpire } from '@/servers/api/dataStatistics';
import moment from 'moment';
import './supplierQualificationWarningStatistics.less';
import { downloadFile } from '@/utils/download';
import { useSupplierDetailModal } from '@/components/SupplierDetailModalContext/SupplierDetailModalContext';

const { Option } = Select;
const { RangePicker } = DatePicker;

const SupplierQualificationWarningStatistics: React.FC = () => {
  const intl = useIntl();
  const supplierDetailModal = useSupplierDetailModal();
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();

  const [statisticsData, setStatisticsData] = useState<DataStatistics.QualificationExpireRecord[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => intl.formatMessage({ id: 'dataStatistics.common.total' }, { total }),
  });
  const [searchParams, setSearchParams] = useState<DataStatistics.QualificationExpireSearchParams>({});

  // 准入单位下拉选项 - 假数据
  const companyOptions = [
    { label: '中山市合创展包装材料有限公司', value: '中山市合创展包装材料有限公司' },
    { label: '广州市科技发展有限公司', value: '广州市科技发展有限公司' },
    { label: '深圳市创新科技有限公司', value: '深圳市创新科技有限公司' },
    { label: '东莞市制造业有限公司', value: '东莞市制造业有限公司' },
  ];

  // 境内/境外选项
  const areaOptions = [
    { label: intl.formatMessage({ id: 'dataStatistics.common.domestic' }), value: 'dvs' },
    { label: intl.formatMessage({ id: 'dataStatistics.common.foreign' }), value: 'ovs' },
  ];

  // 获取数据
  const fetchStatisticsData = async (
    current = 1,
    pageSize = 10,
    params: DataStatistics.QualificationExpireSearchParams = searchParams,
  ) => {
    if (params !== searchParams) {
      setSearchParams(params);
    }

    setLoading(true);
    try {
      // 处理日期范围
      const { termOfValidityRange, ...otherParams } = params;

      const requestParams: DataStatistics.QualificationExpireRequest = {
        basePageRequest: {
          pageNo: current,
          pageSize: pageSize,
        },
        ...otherParams
      };

      // 如果有日期范围，转换为开始和结束日期
      if (termOfValidityRange && termOfValidityRange.length === 2) {
        requestParams.termOfValidityStart = termOfValidityRange[0];
        requestParams.termOfValidityEnd = termOfValidityRange[1];
      }

      // 调用接口
      const response = await getSupplierQualificationExpire(requestParams);

      if (response.success && response.data) {
        setStatisticsData(response.data.records);
        setPagination({
          ...pagination,
          current: response.data.current,
          pageSize: response.data.size,
          total: response.data.total,
        });
      } else {
        message.error(response.message || intl.formatMessage({ id: 'dataStatistics.qualification.getDataFailed' }));
      }
    } catch (error) {
      console.error('获取资质预警统计数据失败:', error);
      message.error(intl.formatMessage({ id: 'dataStatistics.qualification.getDataFailed' }));
    } finally {
      setLoading(false);
    }
  };

  // 首次加载获取数据
  useEffect(() => {
    fetchStatisticsData(pagination.current, pagination.pageSize, {});
  }, []);

  // 处理表格分页变化
  const handleTableChange = (newPagination: TablePaginationConfig) => {
    fetchStatisticsData(newPagination.current, newPagination.pageSize, searchParams);
  };

  // 格式化日期
  const formatDate = (dateStr: string) => {
    return moment(dateStr).format('YYYY-MM-DD');
  };

  // 获取境内/境外显示文本
  const getAreaText = (areaCode: string) => {
    const area = areaOptions.find(item => item.value === areaCode);
    return area ? area.label : areaCode;
  };

  const columns = [
    {
      title: intl.formatMessage({ id: 'dataStatistics.common.serialNumber' }),
      render: (_: any, __: DataStatistics.QualificationExpireRecord, index: number) =>
        (pagination.current! - 1) * pagination.pageSize! + index + 1,
      width: 80,
    },
    {
      title: intl.formatMessage({ id: 'dataStatistics.common.supplierName' }),
      dataIndex: 'supplierName',
      key: 'supplierName',
      width: 180,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string, record: DataStatistics.QualificationExpireRecord) => (
        <Tooltip placement="topLeft" title={text}>
          <a onClick={() => supplierDetailModal?.(record.supplierId)}>{text}</a>
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'dataStatistics.common.area' }),
      dataIndex: 'area',
      key: 'area',
      width: 100,
      render: (text: string) => getAreaText(text),
    },
    {
      title: intl.formatMessage({ id: 'dataStatistics.common.category' }),
      dataIndex: 'categoryName',
      key: 'categoryName',
      width: 120,
    },
    {
      title: intl.formatMessage({ id: 'dataStatistics.common.accessUnit' }),
      dataIndex: 'accessUnit',
      key: 'accessUnit',
      width: 150,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'dataStatistics.common.accessDept' }),
      dataIndex: 'accessDept',
      key: 'accessDept',
      width: 120,
    },
    {
      title: intl.formatMessage({ id: 'dataStatistics.qualification.qualificationName' }),
      dataIndex: 'qualificationName',
      key: 'qualificationName',
      width: 150,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'dataStatistics.qualification.termOfValidity' }),
      dataIndex: 'termOfValidity',
      key: 'termOfValidity',
      width: 120,
      render: (text: string) => formatDate(text),
    },
  ];

  // 处理搜索
  const handleSearch = (values: any) => {
    // 处理日期范围
    const formattedValues = { ...values };
    if (values.termOfValidityRange && values.termOfValidityRange.length === 2) {
      formattedValues.termOfValidityRange = [
        values.termOfValidityRange[0].format('YYYY-MM-DD'),
        values.termOfValidityRange[1].format('YYYY-MM-DD'),
      ];
    }

    fetchStatisticsData(1, pagination.pageSize, formattedValues);
  };

  // 导出功能
  const handleExport = () => {
    const values = form.getFieldsValue();
    // 处理日期范围
    const exportParams = { ...values };
    if (values.termOfValidityRange && values.termOfValidityRange.length === 2) {
      exportParams.termOfValidityRange = [
        values.termOfValidityRange[0].format('YYYY-MM-DD'),
        values.termOfValidityRange[1].format('YYYY-MM-DD'),
      ];
    }

    downloadFile('/dataStatistics/exportSupplierQualificationExpire', 'GET', exportParams);
  };

  return (
    <div className="common-container supplier-qualification-statistics">
      <div className="filter-action-row">
        <Form
          form={form}
          name="search"
          onFinish={handleSearch}
          layout="inline"
          className="filter-form"
        >
          <Form.Item name="supplierName" label={intl.formatMessage({ id: 'dataStatistics.common.supplierName' })}>
            <Input placeholder={intl.formatMessage({ id: 'dataStatistics.common.pleaseInput' }) + intl.formatMessage({ id: 'dataStatistics.common.supplierName' })} allowClear />
          </Form.Item>
          <Form.Item name="accessUnit" label={intl.formatMessage({ id: 'dataStatistics.common.accessUnit' })}>
            <Select placeholder={intl.formatMessage({ id: 'dataStatistics.common.pleaseSelect' }) + intl.formatMessage({ id: 'dataStatistics.common.accessUnit' })} allowClear style={{ width: 200 }}>
              {companyOptions.map(option => (
                <Option key={option.value} value={option.value}>{option.label}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="area" label={intl.formatMessage({ id: 'dataStatistics.common.area' })}>
            <Select placeholder={intl.formatMessage({ id: 'dataStatistics.common.pleaseSelect' })} allowClear style={{ width: 120 }}>
              {areaOptions.map(option => (
                <Option key={option.value} value={option.value}>{option.label}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="termOfValidityRange" label={intl.formatMessage({ id: 'dataStatistics.qualification.validityRange' })}>
            <RangePicker style={{ width: 240 }} />
          </Form.Item>
          <Form.Item className="filter-btns">
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              {intl.formatMessage({ id: 'dataStatistics.common.search' })}
            </Button>
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                form.resetFields();
                fetchStatisticsData(1, pagination.pageSize, {});
              }}
            >
              {intl.formatMessage({ id: 'dataStatistics.common.reset' })}
            </Button>
          </Form.Item>
        </Form>
        <div className="right-buttons">
          <Button type="primary" ghost icon={<ExportOutlined />} onClick={handleExport}>
            {intl.formatMessage({ id: 'dataStatistics.common.export' })}
          </Button>
        </div>
      </div>

      <Table
        className="data-table"
        rowKey="id"
        columns={columns}
        dataSource={statisticsData}
        pagination={pagination}
        loading={loading}
        onChange={handleTableChange}
        scroll={{ x: 1200 }}
      />
    </div>
  );
};

export default SupplierQualificationWarningStatistics;
