import React, { useState, useEffect } from 'react';
import { history } from 'umi';
import {
  Button,
  Card,
  Table,
  Input,
  Row,
  Col,
  message,
  Space,
  Form,
  Select,
  Typography,
  Tag,
  DatePicker
} from 'antd';
import { ArrowLeftOutlined, SearchOutlined, DeleteOutlined } from '@ant-design/icons';
import { getAnnualResultSupplierList } from '@/servers/api/supplierAnnual';
import styles from './supplierAnnualResult.less';

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

// 定义年度审查结果状态
const resultOptions = [
  { label: '合格', value: '1' },
  { label: '不合格', value: '2' },
];

const SupplierAnnualResultQuery: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [data, setData] = useState<supplierAnnualResult.SupplierRecord[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: (total: number) => `共 ${total} 条记录`,
    showSizeChanger: true,
    showQuickJumper: true,
  });
  const [searchParams, setSearchParams] = useState({});

  // 从路由获取任务ID和主题
  const { taskId, annualTheme } = history.location.state as { taskId: string; annualTheme: string };

  // 获取供应商列表
  const fetchList = async (params: any = {}) => {
    try {
      setLoading(true);
      const { current, pageSize, ...restParams } = params;
      const res = await getAnnualResultSupplierList({
        annualreviewTaskId: taskId,
        basePageRequest: {
          pageNo: current,
          pageSize,
        },
        ...restParams,
        ...searchParams,
      });

      if (res.success) {
        setData(res.data?.records || []);
        setPagination({
          ...pagination,
          current,
          pageSize,
          total: res.data?.total || 0,
        });
      } else {
        message.error(res.message || '获取列表失败');
      }
    } catch (error) {
      console.error('获取列表失败:', error);
      message.error('获取列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 首次加载获取数据
  useEffect(() => {
    if (taskId) {
      fetchList({ current: 1, pageSize: 10 });
    } else {
      message.error('任务ID不存在，无法获取详情');
      history.goBack();
    }
  }, [taskId]);

  // 表格变化处理
  const handleTableChange = (paginationParams: any) => {
    fetchList({
      current: paginationParams.current,
      pageSize: paginationParams.pageSize,
    });
  };

  // 搜索
  const handleSearch = (values: any) => {
    const params = { ...values };

    // 处理日期范围
    if (params.reviewTime && params.reviewTime.length === 2) {
      params.startTime = params.reviewTime[0].format('YYYY-MM-DD');
      params.endTime = params.reviewTime[1].format('YYYY-MM-DD');
      delete params.reviewTime;
    }

    setSearchParams(params);
    fetchList({ current: 1, pageSize: pagination.pageSize, ...params });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    fetchList({ current: 1, pageSize: pagination.pageSize });
  };

  // 返回列表页
  const handleBack = () => {
    history.goBack();
  };

  // 查看详情
  const handleViewDetail = (record: supplierAnnualResult.SupplierRecord) => {
    history.push({
      pathname: '/supplierAnnual/supplierAnnualResultQuery2',
      state: {
        supplierId: record.supplierId,
        supplierName: record.name,
        taskId,
        annualTheme,
        annualreviewTaskId: record.annualreviewTaskId,
      },
    });
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (_: any, __: any, index: number) => index + 1 + (pagination.current - 1) * pagination.pageSize,
    },
    {
      title: '供应商名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '品类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '审查单位',
      dataIndex: 'deptName',
      key: 'deptName',
    },
    {
      title: '审查结果',
      dataIndex: 'reviewResultName',
      key: 'reviewResultName',
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (text: any, record: supplierAnnualResult.SupplierRecord) => (
        <Space size="middle">
          <Button type="link" size="small" onClick={() => handleViewDetail(record)}>
            查看
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="common-container">
      <Card>
        <div className={styles['page-header']}>
          <Title level={4} style={{ margin: 0 }}>
            {annualTheme || '供应商年度结果'}
          </Title>
          <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
            返回
          </Button>
        </div>

        <div className="filter-action-row">
          <Form
            form={form}
            layout="inline"
            onFinish={handleSearch}
            className="filter-form"
          >
            <Form.Item name="name" label="供应商名称">
              <Input placeholder="请输入供应商名称" allowClear />
            </Form.Item>
            <Form.Item name="reviewResult" label="审查结果">
              <Select placeholder="请选择审查结果" allowClear style={{ width: 150 }}>
                {resultOptions.map(item => (
                  <Option key={item.value} value={item.value}>
                    {item.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="reviewTime" label="审查时间">
              <RangePicker
                placeholder={['开始日期', '结束日期']}
                format="YYYY-MM-DD"
              />
            </Form.Item>
            <Form.Item className="filter-btns">
              <Button type="primary" icon={<SearchOutlined />} onClick={() => form.submit()}>
                搜索
              </Button>
              <Button
                type="primary"
                danger
                icon={<DeleteOutlined />}
                onClick={handleReset}
              >
                重置
              </Button>
            </Form.Item>
          </Form>
        </div>

        <div className="content-area">
          <Table
            columns={columns}
            dataSource={data}
            rowKey="supplierId"
            pagination={pagination}
            loading={loading}
            onChange={handleTableChange}
            scroll={{ x: 1100 }}
          />
        </div>
      </Card>
    </div>
  );
};

export default SupplierAnnualResultQuery;
