import React, { useState, useEffect } from 'react';
import { history } from 'umi';
import {
  Button,
  Table,
  Space,
  message,
  Input,
  Select,
  Form,
  Tooltip,
  Tag,
  DatePicker,
  Row,
  Col,
  Card,
} from 'antd';
import type { TablePaginationConfig } from 'antd';
import {
  SearchOutlined,
  DeleteOutlined,
  EyeOutlined,
  EditOutlined,
} from '@ant-design/icons';
import { getAnnualReviewList } from '@/servers/api/supplierAnnual';
import {
  AnnualReviewStatus,
  AnnualReviewStatusText,
  AnnualReviewStatusColor,
} from '@/dicts/supplierAnnualReviewDict';
import styles from './supplierAnnualReview.less';

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

// 搜索参数类型
interface AnnualReviewSearchParams {
  annualreviewTheme?: string;
  reviewStatus?: string;
  timeRange?: string[];
  [key: string]: any;
}

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

  const [reviewData, setReviewData] = useState<supplierAnnualReview.ReviewRecord[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条记录`,
  });
  const [searchParams, setSearchParams] = useState<AnnualReviewSearchParams>({});

  // 获取审查列表
  const fetchReviewList = async (
    current = 1,
    pageSize = 10,
    params: AnnualReviewSearchParams = searchParams,
  ) => {
    // 更新搜索参数状态
    if (params !== searchParams) {
      setSearchParams(params);
    }

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

      // 添加搜索条件
      if (params.annualreviewTheme) {
        requestParams.annualreviewTheme = params.annualreviewTheme;
      }
      if (params.reviewStatus) {
        requestParams.reviewStatus = params.reviewStatus;
      }
      if (params.timeRange && params.timeRange.length === 2) {
        requestParams.startTime = params.timeRange[0];
        requestParams.endTime = params.timeRange[1];
      }

      const response = await getAnnualReviewList(requestParams);

      if (response.success && response.data) {
        const { records, total, current: currentPage, size } = response.data;
        setReviewData(records);
        setPagination({
          ...pagination,
          current: currentPage,
          pageSize: size,
          total,
        });
      } else {
        message.error(response.message || '获取审查列表失败');
      }
    } catch (error) {
      console.error('获取审查列表失败:', error);
      message.error('获取审查列表失败');
    } finally {
      setLoading(false);
    }
  };

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

  // 处理查看
  const handleView = (record: supplierAnnualReview.ReviewRecord) => {
    history.push({
      pathname: 'supplierAnnualScoreDetail',
      state: {
        id: record.id,
      }
    });
  };

  // 处理打分
  const handleScore = (record: supplierAnnualReview.ReviewRecord) => {
    history.push({
      pathname: 'supplierAnnualScore',
      state: {
        id: record.id,
      }
    });
  };

  // 获取状态标签
  const getStatusTag = (status: string | undefined, statusName: string | undefined) => {
    if (!status) return <Tag>未知状态</Tag>;
    const color = AnnualReviewStatusColor[status as keyof typeof AnnualReviewStatusColor] || 'default';
    const text = statusName || AnnualReviewStatusText[status as keyof typeof AnnualReviewStatusText] || '未知状态';
    return <Tag color={color}>{text}</Tag>;
  };

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

  const columns = [
    {
      title: '序号',
      render: (_: any, __: supplierAnnualReview.ReviewRecord, index: number) =>
        (pagination.current! - 1) * pagination.pageSize! + index + 1,
      width: 80,
    },
    {
      title: '审查主题',
      dataIndex: 'annualreviewTheme',
      key: 'annualreviewTheme',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '供应商名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '所属部门',
      dataIndex: 'deptName',
      key: 'deptName',
      width: 150,
    },
    {
      title: '审查员',
      dataIndex: 'userName',
      key: 'userName',
      width: 120,
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 150,
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'reviewStatus',
      key: 'reviewStatus',
      width: 100,
      render: (status: string, record: supplierAnnualReview.ReviewRecord) =>
        getStatusTag(status, record.reviewStatusName),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      align: 'center' as const,
      render: (_: unknown, record: supplierAnnualReview.ReviewRecord) => (
        <Space size="middle">
          <Button
            type="link"
            onClick={() => handleView(record)}
            size="small"
          >
            查看
          </Button>
          {/* 只有待审核状态的可以打分 */}
          {record.reviewStatus === AnnualReviewStatus.WAITING && (
            <Button
              type="link"
              onClick={() => handleScore(record)}
              size="small"
            >
              打分
            </Button>
          )}
        </Space>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = (values: any) => {
    const { timeRange, ...rest } = values;
    const params: AnnualReviewSearchParams = { ...rest };

    if (timeRange && timeRange.length === 2) {
      params.timeRange = [
        timeRange[0].format('YYYY-MM-DD'),
        timeRange[1].format('YYYY-MM-DD')
      ];
    }

    fetchReviewList(1, pagination.pageSize, params);
  };

  // 重置搜索表单
  const handleReset = () => {
    form.resetFields();
    fetchReviewList(1, pagination.pageSize, {});
  };

  return (
    <div className="common-container">
      <Card>
        <div className="filter-action-row">
          <Form
            form={form}
            name="search"
            onFinish={handleSearch}
            layout="inline"
            className="filter-form"
          >
            <Form.Item name="annualreviewTheme" label="审查主题">
              <Input placeholder="请输入审查主题" allowClear />
            </Form.Item>
            <Form.Item name="reviewStatus" label="状态">
              <Select placeholder="请选择状态" allowClear style={{ width: 120 }}>
                {Object.entries(AnnualReviewStatusText).map(([key, value]) => (
                  <Option key={key} value={key}>{value}</Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="timeRange" label="时间范围">
              <RangePicker style={{ width: 240 }} />
            </Form.Item>
            <Form.Item className="filter-btns">
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button
                type="primary"
                danger
                icon={<DeleteOutlined />}
                onClick={handleReset}
              >
                重置
              </Button>
            </Form.Item>
          </Form>
        </div>

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

export default SupplierAnnualReview;
