import React, { useState, useEffect } from 'react';
import { Modal, Button, Spin } from 'antd';
import styles from '../../supplierTaskManageDetail.less';
import EvaluateTemplateTable from '@/components/EvaluateTemplateTable/EvaluateTemplateTable';
import { getTemplateDetail } from '@/servers/api/supplierEvaluate';

interface IndicatorModalProps {
  visible: boolean;
  evaluatorId: string;
  indicators: string[];
  templateId?: string;
  onCancel: () => void;
}

const IndicatorModal: React.FC<IndicatorModalProps> = ({
  visible,
  evaluatorId,
  indicators,
  templateId,
  onCancel
}) => {
  const [loading, setLoading] = useState<boolean>(false);
  const [filteredIndicators, setFilteredIndicators] = useState<any[]>([]);

  // 获取模板详情数据
  useEffect(() => {
    const fetchTemplateData = async () => {
      if (visible && templateId) {
        setLoading(true);
        try {
          const res = await getTemplateDetail(templateId);
          if (res.success && res.data) {

            // 筛选出当前评价人员负责的指标
            if (res.data.indicatorStList && indicators.length > 0) {
              // 扁平化处理模板数据，提取出所有二级指标
              const allIndicators = [];
              for (const stItem of res.data.indicatorStList) {
                if (stItem.indicatorNdList) {
                  for (const ndItem of stItem.indicatorNdList) {
                    if (indicators.includes(ndItem.id as string)) {
                      allIndicators.push({
                        ...ndItem,
                        baseIndicator: stItem.baseIndicator,
                        descIndicator: stItem.descIndicator,
                        stScore: stItem.score,
                        indicatorType: stItem.indicatorType,
                        id: ndItem.id,
                        score: ndItem.score,
                      });
                    }
                  }
                }
              }
              setFilteredIndicators(allIndicators);
            }
          }
        } catch (error) {
          console.error('获取模板详情失败:', error);
        } finally {
          setLoading(false);
        }
      }
    };

    fetchTemplateData();
  }, [visible, templateId, indicators]);

  return (
    <Modal
      title={`评价人员 ${evaluatorId} 的指标分工`}
      visible={visible}
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>
      ]}
      width={1200} // 增加宽度以适应表格
    >
      {loading ? (
        <div className={styles.loadingContainer}>
          <Spin tip="加载中..." />
        </div>
      ) : indicators.length > 0 && filteredIndicators.length > 0 ? (
        <div className={styles.indicatorModalContent}>
          <EvaluateTemplateTable
            value={filteredIndicators}
            isDetail={true}
          />
        </div>
      ) : (
        <div className={styles.emptyData}>暂无指标分工数据</div>
      )}
    </Modal>
  );
};

export default IndicatorModal;
