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 { getAnnualReviewDetail } from '@/servers/api/supplierAnnual';
import {
  AnnualReviewStatus,
  AnnualReviewStatusText,
  AnnualReviewStatusColor,
  ExamineResult,
  ExamineResultText,
  ExamineResultColor,
} from '@/dicts/supplierAnnualReviewDict';
import styles from './supplierAnnualReview.less';

const { Title } = Typography;

// 模拟评分结果的数据结构
interface ScoreResult {
  id: string;
  itemName: string;
  examineResult: string;
  remark: string;
}

const SupplierAnnualReviewDetail: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [reviewDetail, setReviewDetail] = useState<supplierAnnualReview.ReviewRecord | null>(null);
  const [scoreResults, setScoreResults] = useState<ScoreResult[]>([]);

  // 从路由获取ID
  const { id } = history.location.state as { id: string };

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

        // 这里应该根据实际接口返回的数据设置评分结果
        // 由于没有具体的数据结构，这里模拟一些评分结果

        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 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 getResultTag = (result: string) => {
    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) => 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="审查主题">
                    {reviewDetail.annualreviewTheme}
                  </Descriptions.Item>
                  <Descriptions.Item label="供应商名称">
                    {reviewDetail.name}
                  </Descriptions.Item>
                  <Descriptions.Item label="所属部门">
                    {reviewDetail.deptName || '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="审查员">
                    {reviewDetail.userName || '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="开始时间">
                    {reviewDetail.startTime}
                  </Descriptions.Item>
                  <Descriptions.Item label="结束时间">
                    {reviewDetail.endTime}
                  </Descriptions.Item>
                  <Descriptions.Item label="状态">
                    {getStatusTag(reviewDetail.reviewStatus, reviewDetail.reviewStatusName)}
                  </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 SupplierAnnualReviewDetail;
