import React, { useState, useEffect } from 'react';
import { Button, Table, Input, Select, Form, Tooltip, Tag, message, DatePicker } from 'antd';
import type { TablePaginationConfig } from 'antd';
import { SearchOutlined, DeleteOutlined, ExportOutlined } from '@ant-design/icons';
import { useIntl } from 'umi';
import { AnnualReviewResultText, AnnualReviewResultColor } from '@/dicts/dataStatistics';
import { getSupplierAdmissionStatistics } from '@/servers/api/dataStatistics';
import { downloadFile } from '@/utils/download';
import moment from 'moment';

const { Option } = Select;

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

  const [statisticsData, setStatisticsData] = useState<
    DataStatistics.AnnualReviewStatisticsRecord[]
  >([]);
  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.AnnualReviewStatisticsSearchParams>({});

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

  // 年审结果选项
  const annualResultOptions = Object.entries(AnnualReviewResultText).map(([key, value]) => ({
    label: value,
    value: key,
  }));

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

    setLoading(true);
    try {
      // 构建请求参数
      const requestParams: DataStatistics.AnnualReviewStatisticsRequest = {
        basePageRequest: {
          pageNo: current,
          pageSize: pageSize,
        },
        ...params,
      };

      // 调用接口
      const response = await getSupplierAdmissionStatistics(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.annual.getDataFailed' }),
        );
      }
    } catch (error) {
      console.error('获取年审统计数据失败:', error);
      message.error(intl.formatMessage({ id: 'dataStatistics.annual.getDataFailed' }));
    } finally {
      setLoading(false);
    }
  };

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

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

  // 获取年审结果标签
  const getResultTag = (result: string) => {
    const color =
      AnnualReviewResultColor[result as keyof typeof AnnualReviewResultColor] || 'default';
    const text =
      result === '1'
        ? intl.formatMessage({ id: 'dataStatistics.annual.qualified' })
        : intl.formatMessage({ id: 'dataStatistics.annual.unqualified' });
    return <Tag color={color}>{text}</Tag>;
  };

  const columns = [
    {
      title: intl.formatMessage({ id: 'dataStatistics.common.serialNumber' }),
      render: (_: any, __: DataStatistics.AnnualReviewStatisticsRecord, 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) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'dataStatistics.common.area' }),
      dataIndex: 'area',
      key: 'area',
      width: 100,
    },
    {
      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: 180,
      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.common.year' }),
      dataIndex: 'annualreviewYear',
      key: 'annualreviewYear',
      width: 100,
      render: (year: string) =>
        intl.formatMessage({ id: 'dataStatistics.common.yearFormat' }, { year }),
    },
    {
      title: intl.formatMessage({ id: 'dataStatistics.annual.annualStatisticsResult' }),
      dataIndex: 'annualStatisticsResult',
      key: 'annualStatisticsResult',
      width: 100,
      render: (result: string) => getResultTag(result),
    },
  ];

  // 处理搜索
  const handleSearch = (values: any) => {
    fetchStatisticsData(1, pagination.pageSize, values);
  };

  // 导出功能
  const handleExport = () => {
    const values = form.getFieldsValue();
    downloadFile('/dataStatistics/exportSupplierAnnualReviewStatistics', 'GET', values);
  };

  return (
    <div className="common-container supplier-annual-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="annualreviewYear"
            getValueProps={(value) => ({
              value: value ? moment(value) : undefined,
            })}
            normalize={(value) => value && value.format('YYYY')}
            label={intl.formatMessage({ id: 'dataStatistics.annual.annualYear' })}
          >
            <DatePicker
              style={{ width: '100%' }}
              format="YYYY"
              placeholder={
                intl.formatMessage({ id: 'dataStatistics.common.pleaseSelect' }) +
                intl.formatMessage({ id: 'dataStatistics.common.year' })
              }
              picker="year"
            />
          </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="annualStatisticsResult"
            label={intl.formatMessage({ id: 'dataStatistics.annual.annualResult' })}
          >
            <Select
              placeholder={
                intl.formatMessage({ id: 'dataStatistics.common.pleaseSelect' }) +
                intl.formatMessage({ id: 'dataStatistics.annual.annualResult' })
              }
              allowClear
              style={{ width: 120 }}
            >
              {annualResultOptions.map((option) => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </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 SupplierAnnualStatistics;
