// 评价结果详情
import React, { useState, useEffect } from 'react';
import { Card, Button, message, Typography } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { history, useLocation } from 'umi';
import ScoreEvaluationTable from '@/components/ScoreEvaluationTable';
import styles from './supplierEvaluateResult.less';
import { getIndicator } from '@/servers/api/supplierEvaluate';

const { Title } = Typography;

// 评价打分详情数据接口
interface IndicatorDetailData {
  category: string;
  name: string;
  taskIndicatorVo: {
    baseIndicator: string;
    indicatorDesc: string;
    score: string;
    subIndicator: {
      id: string;
      remark: string | null;
      scoreNum: string | null;
      starIndicator: string;
      stId: string;
      subIndicator: string;
      subScore: string;
    }[];
  }[];
}

const SupplierEvaluateResultByZb: React.FC = () => {
  const location = useLocation<{
    record: API.EvaluateScoreIndicator;
    parentRecord: API.EvaluateTaskRecord;
    supplierRecord: API.EvaluateSupplierRecord;
    scoreDetail: API.EvaluateScoreData;
  }>();
  const [loading, setLoading] = useState<boolean>(false);
  const [scoreRecord, setScoreRecord] = useState<API.EvaluateScoreIndicator | null>(null);
  const [parentRecord, setParentRecord] = useState<API.EvaluateTaskRecord | null>(null);
  const [supplierRecord, setSupplierRecord] = useState<API.EvaluateSupplierRecord | null>(null);
  const [indicatorDetail, setIndicatorDetail] = useState<IndicatorDetailData | null>(null);

  // 获取上级页面传递的数据
  useEffect(() => {
    if (location.state?.record) {
      setScoreRecord(location.state.record);
    }
    if (location.state?.parentRecord) {
      setParentRecord(location.state.parentRecord);
    }
    if (location.state?.supplierRecord) {
      setSupplierRecord(location.state.supplierRecord);
    }
    if (location.state?.scoreDetail) {
      // 如果有上级页面传递的评分明细数据，暂存下来
      // 稍后我们仍然会通过API获取最新数据
    }
  }, [location]);

  // 获取评价打分详情数据
  const fetchIndicatorDetail = async () => {
    if (!scoreRecord?.id) {
      message.error('缺少评价记录ID，无法获取数据');
      return;
    }

    setLoading(true);
    try {
      const response = await getIndicator(scoreRecord.id);
      if (response.data && response.success) {
        setIndicatorDetail(response.data);
      } else {
        message.error(response.message || '获取评价打分详情失败');
      }
    } catch (error) {
      console.error('获取评价打分详情失败:', error);
      message.error('获取评价打分详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 监听scoreRecord变化，获取评价详情数据
  useEffect(() => {
    if (scoreRecord?.id) {
      fetchIndicatorDetail();
    }
  }, [scoreRecord]);

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

  // 将API数据转换为ScoreEvaluationTable组件所需的格式
  const formatDataForScoreTable = () => {
    if (!indicatorDetail?.taskIndicatorVo) return [];

    return indicatorDetail.taskIndicatorVo.map(indicator => {
      return {
        baseIndicator: indicator.baseIndicator,
        descIndicator: indicator.indicatorDesc,
        score: indicator.score,
        indicatorNdList: indicator.subIndicator?.map(subItem => {
          return {
            subIndicator: subItem.subIndicator,
            score: subItem.subScore,
            isStar: subItem.starIndicator,
            id: subItem.id,
            actualScore: subItem.scoreNum || '',
            remark: subItem.remark || ''
          };
        }) || []
      };
    });
  };

  if (loading && !indicatorDetail) {
    return <div className="common-container">加载中...</div>;
  }

  const supplierName = supplierRecord?.supplierName || indicatorDetail?.name || '供应商';

  return (
    <div className="common-container">
      <div className="filter-action-row">
        <Title level={4} className={styles.pageTitle}>
          {supplierName} - 评价详情
        </Title>
        <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
          返回
        </Button>
      </div>

      <Card title="评价指标详情" bordered={false} className={styles.detailCard}>
        <ScoreEvaluationTable
          value={formatDataForScoreTable()}
          isDetail={true}
          loading={loading}
        />
      </Card>
    </div>
  );
};

export default SupplierEvaluateResultByZb;
