import React, { useState, useEffect } from 'react';
import { history } from 'umi';
import {
  Button,
  Card,
  Descriptions,
  Divider,
  Spin,
  message,
  Typography,
  Empty,
  Table,
  Tag,
} from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { getAnnualResultReviewDetail } from '@/servers/api/supplierAnnual';
import {
  AnnualReviewStatus,
  AnnualReviewStatusText,
  AnnualReviewStatusColor,
  ExamineResult,
  ExamineResultText,
  ExamineResultColor,
} from '@/dicts/supplierAnnualReviewDict';
import styles from './supplierAnnualResult.less';

const { Title } = Typography;

const SupplierAnnualResultDetail: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [reviewDetail, setReviewDetail] = useState<supplierAnnualResult.ReviewDetailData | null>(null);
  const [scoreResults, setScoreResults] = useState<supplierAnnualResult.TaskIndicatorVo[]>([]);

  // 从路由获取ID和其他参数
  const { id, supplierId, supplierName, taskId, annualTheme } = history.location.state as {
    id: string;
    supplierId: string;
    supplierName: string;
    taskId: string;
    annualTheme: string;
  };

  // 获取审查详情
  const fetchReviewDetail = async (reviewId: string) => {
    try {
      setLoading(true);
      const res = await getAnnualResultReviewDetail(reviewId);
      if (res.success && res.data) {
        setReviewDetail(res.data);

        // 设置评分结果
        if (res.data.taskIndicatorVo && Array.isArray(res.data.taskIndicatorVo)) {
          setScoreResults(res.data.taskIndicatorVo);
        }
      } else {
        message.error(res.message || '获取审查详情失败');
      }
    } catch (error) {
      console.error('获取审查详情失败:', error);
      message.error('获取审查详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 首次加载获取数据
  useEffect(() => {
    if (id) {
      fetchReviewDetail(id);
    } else {
      message.error('审查ID不存在，无法获取详情');
      history.goBack();
    }
  }, [id]);

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

  // 获取评审结果标签
  const getResultTag = (result: string | null) => {
    if (!result) return <Tag>未评审</Tag>;
    const color = ExamineResultColor[result as keyof typeof ExamineResultColor] || 'default';
    const text = ExamineResultText[result as keyof typeof ExamineResultText] || '未知';
    return <Tag color={color}>{text}</Tag>;
  };

  // 评分结果表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '评分项',
      dataIndex: 'itemName',
      key: 'itemName',
    },
    {
      title: '评审结果',
      dataIndex: 'examineResult',
      key: 'examineResult',
      width: 120,
      render: (result: string | null) => getResultTag(result),
    },
    {
      title: '星号项',
      dataIndex: 'isStar',
      key: 'isStar',
      width: 120,
      render: (result: string) => result === '1' ? '是' : '否',
    },
    {
      title: '评审说明',
      dataIndex: 'remark',
      key: 'remark',
    },
  ];

  return (
    <div className="common-container">
      <Card>
        <div className={styles['page-header']}>
          <Title level={4} style={{ margin: 0 }}>
            供应商年度审查详情
          </Title>
          <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
            返回
          </Button>
        </div>
        <Spin spinning={loading}>
          {reviewDetail ? (
            <>
              <Card title="基本信息" bordered={false} className={styles['detail-card']}>
                <Descriptions column={2} bordered>
                  <Descriptions.Item label="供应商名称">
                    {supplierName || reviewDetail.name}
                  </Descriptions.Item>
                  <Descriptions.Item label="年度主题">
                    {annualTheme}
                  </Descriptions.Item>
                </Descriptions>
              </Card>

              <Divider />

              <Card title="评分结果" bordered={false} className={styles['detail-card']}>
                {scoreResults.length > 0 ? (
                  <Table
                    columns={columns}
                    dataSource={scoreResults}
                    rowKey="id"
                    pagination={false}
                    bordered
                  />
                ) : (
                  <Empty description="暂无评分数据" />
                )}
              </Card>
            </>
          ) : (
            !loading && <Empty description="暂无审查详情数据" />
          )}
        </Spin>
      </Card>
    </div>
  );
};

export default SupplierAnnualResultDetail;
