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

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

// 定义年度审查状态
const statusOptions = [
  { label: '待审核', value: '0' },
  { label: '审核中', value: '1' },
  { label: '已完成', value: '2' },
];

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

  // 获取年度结果列表
  const fetchList = async (params: any = {}) => {
    try {
      setLoading(true);
      const { current, pageSize, ...restParams } = params;
      const res = await getAnnualResultTaskList({
        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(() => {
    fetchList({ current: 1, pageSize: 10 });
  }, []);

  // 表格变化处理
  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 handleViewYearStats = (record: supplierAnnualResult.TaskRecord) => {
    history.push({
      pathname: '/supplierAnnual/supplierAnnualResultQuery',
      state: {
        taskId: record.id,
        annualTheme: record.annualreviewTheme
      },
    });
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (_: any, __: any, index: number) => index + 1 + (pagination.current - 1) * pagination.pageSize,
    },
    {
      title: '主题',
      dataIndex: 'annualreviewTheme',
      key: 'annualreviewTheme',
    },
    {
      title: '品类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '发起单位',
      dataIndex: 'deptName',
      key: 'deptName',
    },
    {
      title: '年审开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
    },
    {
      title: '年审结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
    },
    {
      title: '年审状态',
      dataIndex: 'statusName',
      key: 'statusName',
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (text: any, record: supplierAnnualResult.TaskRecord) => (
        <Space size="middle">
          <Button type="link" size="small" onClick={() => handleViewYearStats(record)}>
            查看
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="common-container">
      <div className="filter-action-row">
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          className="filter-form"
        >
          <Form.Item name="supplierName" label="供应商名称">
            <Input placeholder="请输入供应商名称" allowClear />
          </Form.Item>
          <Form.Item name="reviewTime" label="年审时间">
            <RangePicker
              placeholder={['开始日期', '结束日期']}
              format="YYYY-MM-DD"
            />
          </Form.Item>
          <Form.Item name="status" label="年审状态">
            <Select placeholder="请选择状态" allowClear style={{ width: 150 }}>
              {statusOptions.map(item => (
                <Option key={item.value} value={item.value}>
                  {item.label}
                </Option>
              ))}
            </Select>
          </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="id"
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 1100 }}
        />
      </div>
    </div>
  );
};

export default SupplierAnnualResult;
