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

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

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

const SupplierAnnualReview: React.FC = () => {
  const intl = useIntl();
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();
  const [reviewStatus, setReviewStatus] = useState<DictItem[]>([]);
  const [reviewData, setReviewData] = useState<supplierAnnualReview.ReviewRecord[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => intl.formatMessage({ id: 'supplierAnnualReview.common.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.status) {
        requestParams.status = params.status;
      }
      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 || intl.formatMessage({ id: 'supplierAnnualReview.list.getListFailed' }));
      }
    } catch (error) {
      console.error('获取审查列表失败:', error);
      message.error(intl.formatMessage({ id: 'supplierAnnualReview.list.getListFailed' }));
    } finally {
      setLoading(false);
    }
  };

  // 首次加载获取数据
  useEffect(() => {
    fetchReviewList(pagination.current, pagination.pageSize, {});
    getDictList('project_status ').then((res) => {
      if (res.success) {
        setReviewStatus(res.data);
      }
    });
  }, []);

  // 处理查看
  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>{intl.formatMessage({ id: 'supplierAnnualReview.common.unknownStatus' })}</Tag>;
    const color = AnnualReviewStatusColor[status as keyof typeof AnnualReviewStatusColor] || 'default';
    const text = statusName || AnnualReviewStatusText[status as keyof typeof AnnualReviewStatusText] || intl.formatMessage({ id: 'supplierAnnualReview.common.unknownStatus' });
    return <Tag color={color}>{text}</Tag>;
  };

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

  const columns = [
    {
      title: intl.formatMessage({ id: 'supplierAnnualReview.common.serialNumber' }),
      render: (_: any, __: supplierAnnualReview.ReviewRecord, index: number) =>
        (pagination.current! - 1) * pagination.pageSize! + index + 1,
      width: 80,
    },
    {
      title: intl.formatMessage({ id: 'supplierAnnualReview.list.reviewTheme' }),
      dataIndex: 'annualreviewTheme',
      key: 'annualreviewTheme',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'supplierAnnualReview.list.supplierName' }),
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'supplierAnnualReview.list.department' }),
      dataIndex: 'deptName',
      key: 'deptName',
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'supplierAnnualReview.list.reviewer' }),
      dataIndex: 'userName',
      key: 'userName',
      width: 120,
    },
    {
      title: intl.formatMessage({ id: 'supplierAnnualReview.list.startTime' }),
      dataIndex: 'startTime',
      key: 'startTime',
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'supplierAnnualReview.list.endTime' }),
      dataIndex: 'endTime',
      key: 'endTime',
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'supplierAnnualReview.list.status' }),
      dataIndex: 'statusName',
      key: 'statusName',
      width: 100
    },
    {
      title: "提交状态",
      dataIndex: 'reviewStatusName',
      key: 'reviewStatusName',
      width: 100
    },
    {
      title: intl.formatMessage({ id: 'supplierAnnualReview.common.operation' }),
      key: 'action',
      width: 150,
      align: 'center' as const,
      render: (_: unknown, record: supplierAnnualReview.ReviewRecord) => (
        <Space size="middle">
          <Button
            type="link"
            onClick={() => handleView(record)}
            size="small"
          >
            {intl.formatMessage({ id: 'supplierAnnualReview.common.view' })}
          </Button>
          {/* 只有待审核状态的可以打分 */}
          {record.status !== "0" && record.reviewStatus === "0" && (
            <Button
              type="link"
              onClick={() => handleScore(record)}
              size="small"
            >
              {intl.formatMessage({ id: 'supplierAnnualReview.common.score' })}
            </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={intl.formatMessage({ id: 'supplierAnnualReview.list.reviewTheme' })}>
              <Input placeholder={intl.formatMessage({ id: 'supplierAnnualReview.list.pleaseInputReviewTheme' })} allowClear />
            </Form.Item>
            <Form.Item name="status" label={intl.formatMessage({ id: 'supplierAnnualReview.list.status' })}>
              <Select placeholder={intl.formatMessage({ id: 'supplierAnnualReview.list.pleaseSelectStatus' })} allowClear style={{ width: 120 }}>
                {reviewStatus.map((item) => (
                  <Option key={item.code} value={item.code}>{item.dicName}</Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="timeRange" label={intl.formatMessage({ id: 'supplierAnnualReview.list.timeRange' })}>
              <RangePicker style={{ width: 240 }} />
            </Form.Item>
            <Form.Item className="filter-btns">
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                {intl.formatMessage({ id: 'supplierAnnualReview.common.search' })}
              </Button>
              <Button
                type="primary"
                danger
                icon={<DeleteOutlined />}
                onClick={handleReset}
              >
                {intl.formatMessage({ id: 'supplierAnnualReview.common.reset' })}
              </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;
