import React, { useEffect, useState } from 'react';
import { useModel } from '@umijs/max';
import styles from './index.less';
import services from '@/services';
import ModuleTitleWithTabs from '@/pages/Home_v_2504/components/common/ModuleTitleWithTabs';

// 接口数据类型定义
interface IndexItem {
  id: string;
  indexType: string;
  hierarchy: string;
  lastFlag: string;
  name: string;
  lostScore: number;
  children?: IndexItem[];
}

// 组织后的树形结构
interface TreeNode {
  level1: IndexItem;
  children: {
    level2: IndexItem;
    children: IndexItem[];
  }[];
}

/**
 * 失分溯源组件
 * 展示CQI指标体系失分情况
 */
const LostScoreTracing: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const areaId = initialState?.areaId || '510100';

  const [loading, setLoading] = useState<boolean>(true);
  const [indexSystemData, setIndexSystemData] = useState<IndexItem | null>(null);
  const [treeData, setTreeData] = useState<TreeNode[]>([]);

  // 获取指标体系数据
  const fetchIndexSystemData = async () => {
    try {
      setLoading(true);
      const params = {
        objectId: areaId,
        indexId: '1', // CQI的指标ID
      };
      
      const res = await services.Physicalsign.getIndexSystem(params);
      if (res.code === 200 && res.data) {
        const typedData = res.data as unknown as IndexItem;
        setIndexSystemData(typedData);
        
        // 处理数据，将树状结构组织为更容易渲染的格式
        if (typedData.children) {
          const processed = processData(typedData.children);
          setTreeData(processed);
        }
      } else {
        setIndexSystemData(null);
        setTreeData([]);
      }
    } catch (error) {
      console.error('Failed to fetch index system data:', error);
      setIndexSystemData(null);
      setTreeData([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchIndexSystemData();
    
    // 设置定时刷新（2小时刷新一次）
    const intervalId = setInterval(() => {
      fetchIndexSystemData();
    }, 60000 * 60 * 2);
    
    return () => clearInterval(intervalId);
  }, [areaId]);

  // 计算父节点的失分总和
  // 界面展示的都是2位小数，实际上是多位小数，比如 0.206， 0.207， 结果是 0.413，但是取2位小数，看上去分别是 0.21， 0.21， 0.41， 用户看起来会觉得应该是 0.42
  const calculateLostScore = (items: IndexItem[]): number => {
    if (!items || items.length === 0) return 0;
    
    return 0;

    // 先计算原始值总和，保留多位小数
    const rawTotal = items.reduce((total, item) => {
      if (item.lostScore > 0) {
        return total + item.lostScore;
      }
      
      // 如果当前节点没有失分值但有子节点，递归计算子节点失分总和
      if (item.children && item.children.length > 0) {
        return total + calculateLostScore(item.children);
      }
      
      return total;
    }, 0);

    // 对最终结果进行四舍五入，保留2位小数
    return Math.round(rawTotal * 100) / 100;
  };

  // 处理数据，组织为树形结构
  const processData = (items: IndexItem[]): TreeNode[] => {
    const result: TreeNode[] = [];
    
    // 定义一级指标的排序顺序
    const level1Order = ['安全', '整洁', '有序', '便民', '美观'];
    
    // 筛选一级指标（hierarchy = 2）并按指定顺序排序
    const level1Items = items
      .filter(item => item.hierarchy === '2')
      .sort((a, b) => {
        const aIndex = level1Order.indexOf(a.name);
        const bIndex = level1Order.indexOf(b.name);
        return aIndex - bIndex;
      });
    
    level1Items.forEach((level1Item) => {
      const node: TreeNode = {
        level1: level1Item,
        children: [],
      };
      
      // 获取二级指标（hierarchy = 3）
      if (level1Item.children) {
        level1Item.children.forEach((level2Item) => {
          if (level2Item.hierarchy === '3') {
            const level2Node = {
              level2: level2Item,
              children: [] as IndexItem[],
            };
            
            // 获取三级指标（hierarchy = 4）
            if (level2Item.children) {
              level2Item.children.forEach((level3Item) => {
                if (level3Item.hierarchy === '4') {
                  level2Node.children.push(level3Item);
                }
              });
            }
            
            node.children.push(level2Node);
          }
        });
      }
      
      result.push(node);
    });
    
    return result;
  };

  // 固定高度（像素）
  const FIXED_ROW_HEIGHT = 50; // 固定每行的高度为50px
  const MARGIN_BOTTOM = 10; // 行间距

  // 渲染树结构
  const renderTree = () => {
    return treeData.map((node, index) => {
      // 计算一级指标的总行数
      const totalLevel3Items = node.children.reduce((total, level2) => 
        total + Math.max(1, level2.children.length), 
      0);
      
      // 计算一级指标的总高度，包含间距
      const level1Height = (totalLevel3Items * FIXED_ROW_HEIGHT) + 
        ((totalLevel3Items - 1) * MARGIN_BOTTOM);
      
      return (
        <div key={index} className={styles.section}>
          <div className={styles.level1Container}>
            {/* 一级指标 */}
            <div 
              className={styles.treeCol1} 
              style={{ height: `${level1Height}px` }}
            >
              <div>
                {node.level1.name}
                {node.level1.lostScore > 0 ? (
                  <span className={styles.lostScore}> {-node.level1.lostScore.toFixed(2)}</span>
                ) : (
                  // 如果一级指标没有lostScore，计算其所有子节点的lostScore总和
                  <span className={styles.lostScore}> {-(
                    calculateLostScore(node.level1.children || [])
                  ).toFixed(2)}</span>
                )}
              </div>
            </div>
            
            <div className={styles.level2AndLevel3Container}>
              {node.children.map((level2Node, l2Index) => {
                // 计算这个二级指标下的三级指标数量（至少为1）
                const level3Count = Math.max(1, level2Node.children.length);
                
                // 计算二级指标的高度，包含间距
                const level2Height = (level3Count * FIXED_ROW_HEIGHT) + 
                  ((level3Count - 1) * MARGIN_BOTTOM);
                
                return (
                  <div key={l2Index} className={styles.level2WithChildren}>
                    {/* 二级指标 */}
                    <div 
                      className={styles.treeCol2} 
                      style={{ height: `${level2Height}px` }}
                    >
                      <div>
                        {level2Node.level2.name}
                        {level2Node.level2.lostScore > 0 ? (
                          <span className={styles.lostScore}> {-level2Node.level2.lostScore.toFixed(2)}</span>
                        ) : (
                          // 如果二级指标没有lostScore，计算其所有子节点的lostScore总和
                          <span className={styles.lostScore}> {-(
                            calculateLostScore(level2Node.level2.children || [])
                          ).toFixed(2)}</span>
                        )}
                      </div>
                    </div>
                    
                    {/* 三级指标列表 */}
                    <div className={styles.level3List}>
                      {level2Node.children.length > 0 ? (
                        level2Node.children.map((level3Item, l3Index) => (
                          <div 
                            key={l3Index} 
                            className={styles.treeCol3} 
                            style={{ height: `${FIXED_ROW_HEIGHT}px` }}
                          >
                            <div>
                              {level3Item.name}
                              {level3Item.lostScore > 0 && (
                                <span className={styles.lostScore}> {-level3Item.lostScore.toFixed(2)}</span>
                              )}
                            </div>
                          </div>
                        ))
                      ) : (
                        // 如果没有三级指标，显示空的占位符
                        <div className={styles.treeCol3} style={{ height: `${FIXED_ROW_HEIGHT}px` }}>
                          {/* 无三级指标 */}
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
              
              {/* 如果没有二级指标，显示空的占位符 */}
              {node.children.length === 0 && (
                <div className={styles.level2WithChildren}>
                  <div className={styles.treeCol2} style={{ height: `${FIXED_ROW_HEIGHT}px` }}>
                    {/* 无二级指标 */}
                  </div>
                  <div className={styles.level3List}>
                    <div className={styles.treeCol3} style={{ height: `${FIXED_ROW_HEIGHT}px` }}>
                      {/* 无三级指标 */}
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      );
    });
  };

  return (
    <div className={styles.container}>
      <ModuleTitleWithTabs title="失分溯源" />
      
      {/* 表头 - 固定在顶部 */}
      <div className={styles.tableHeader}>
        <div className={styles.headerCol1}>一级指标</div>
        <div className={styles.headerCol2}>二级指标</div>
        <div className={styles.headerCol3}>三级指标</div>
      </div>
      
      {/* 内容区域 - 可滚动 */}
      <div className={styles.content}>
        {!loading && treeData.length > 0 && (
          <div>
            {renderTree()}
          </div>
        )}
        
        {loading && (
          <div style={{ textAlign: 'center', color: '#fff', marginTop: 20 }}>加载中...</div>
        )}
        
        {!loading && treeData.length === 0 && (
          <div style={{ textAlign: 'center', color: '#fff', marginTop: 20 }}>暂无数据</div>
        )}
      </div>
    </div>
  );
};

export default LostScoreTracing; 