<script setup lang="ts">
import { computed, defineEmits, defineProps, onMounted, ref, watch } from 'vue';
// 主体框架内置的第三方方法通过window对象暴露、供外部组件使用
const axios = (window as any).$axios;
// 获取主题状态
const themeStore = (window as any).$themeStore;
// 获取消息提示
const message = (window as any).$message;
const dialog = (window as any).$dialog;
// 通过计算属性确定当前的主体色
const isDarkMode = computed(() => themeStore?.darkMode || false);
// 根据主题计算文字颜色
const textColor = computed(() => (isDarkMode.value ? 'rgba(255, 255, 255, 0.85)' : 'rgba(0, 0, 0, 0.85)'));
const legendTextColor = computed(() => (isDarkMode.value ? 'rgba(255, 255, 255, 0.65)' : 'rgba(0, 0, 0, 0.65)'));
const borderColor = computed(() => (isDarkMode.value ? '#303030' : '#ffffff'));
// CSS变量
const cssVars = computed(() => ({
  '--text-color': textColor.value,
  '--bg-color': isDarkMode.value ? '#1f1f1f' : '#f5f5f5',
  '--panel-bg': isDarkMode.value ? '#262626' : '#ffffff',
  '--card-bg': isDarkMode.value ? '#303030' : '#ffffff',
  '--border-color': isDarkMode.value ? '#434343' : '#e8e8e8'
}));

interface PlanDetailItem {
  id: number;
  testItem: string;
  standardValue: string;
  allowableRange: string;
}

const props = defineProps({
  standardKvid: {
    type: String,
    required: true
  }
});

const emit = defineEmits(['cancel', 'confirm']);

// 当前可用的方案明细数据
const planDetails = ref<PlanDetailItem[]>([]);
// 已选中的行键数组
const checkedRowKeys = ref<(string | number)[]>([]);
// 加载状态
const loading = ref<boolean>(false);

// 获取测试详情数据
async function fetchTestDetails() {
  if (!props.standardKvid) return;

  try {
    loading.value = true;

    const response = await axios.post('/Restful/Kivii.Standards.Entities.Detection/Query.json', {
      StandardKvid: props.standardKvid
    });

    if (response.data && response.data.Results) {
      // 处理树形结构数据
      const treeData = processTreeData(response.data.Results);
      planDetails.value = treeData;

      message.success(`已加载${response.data.Results.length}个测试项目`);
    } else {
      message.error('获取测试数据失败');
    }
  } catch (error) {
    message.error('获取测试详情失败');
    // console.error(error);
  } finally {
    loading.value = false;
  }
}

// 处理树形结构数据
function processTreeData(data: any[]) {
  // 创建ID到节点的映射
  const idMap: Record<string, any> = {};
  const result: any[] = [];

  // 首先将所有节点添加到映射中
  data.forEach((item, index) => {
    const node = {
      id: index + 1,
      key: item.Kvid || `item-${index}`, // 使用Kvid作为唯一标识，如果没有则使用索引
      testItem: item.Title || '未命名项目',
      standardValue: item.StandardValue || item.QualifiedValue || '未设置',
      allowableRange: item.AllowableRange || '±5%',
      parentId: item.ParentKvid || null, // 假设API返回ParentKvid表示父节点ID
      children: []
    };
    idMap[node.key] = node;
  });

  // 构建树形结构
  Object.values(idMap).forEach(node => {
    if (node.parentId && idMap[node.parentId]) {
      // 如果有父节点，将当前节点添加到父节点的children中
      idMap[node.parentId].children.push(node);
    } else {
      // 如果没有父节点，则是顶级节点
      result.push(node);
    }
  });

  // 处理空children数组
  const cleanEmptyChildren = (nodes: any[]) => {
    for (const node of nodes) {
      if (node.children.length === 0) {
        delete node.children;
      } else {
        cleanEmptyChildren(node.children);
      }
    }
  };

  cleanEmptyChildren(result);
  return result;
}

// 监听standardKvid变化，重新获取数据
watch(
  () => props.standardKvid,
  newValue => {
    if (newValue) {
      fetchTestDetails();
      // 重置选中状态
      checkedRowKeys.value = [];
    } else {
      planDetails.value = [];
    }
  },
  { immediate: true }
);

// 处理行选择变化
function handleCheckedRowKeysChange(keys: (string | number)[]) {
  checkedRowKeys.value = keys;
}

// 计算测试方案名称
const planName = computed(() => {
  // 现在从API获取数据，planName可能需要从父组件传递或使用其他方式获取
  return `测试方案 (${props.standardKvid})`;
});

// 表格列定义
const columns = [
  {
    type: 'selection'
  },
  { title: '测试项目', key: 'testItem', align: 'center' },
  { title: '标准值', key: 'standardValue', align: 'center' },
  { title: '允许偏差范围', key: 'allowableRange', align: 'center' }
];

// 取消选择
function cancel() {
  emit('cancel');
}

// 确认选择
function confirm() {
  if (checkedRowKeys.value.length === 0) {
    message.warning('请至少选择一个测试项目');
    return;
  }

  // 提取完整树形结构中被选中的节点和它们的子节点
  const cloneTreeData = JSON.parse(JSON.stringify(planDetails.value));

  // 过滤并标记选中的树节点
  const filterSelectedNodes = (nodes: any[]) => {
    const result: any[] = [];

    for (const node of nodes) {
      const isSelected = checkedRowKeys.value.includes(node.key);

      // 如果当前节点被选中或者有被选中的子节点，则保留
      if (isSelected) {
        // 创建一个节点副本，只保留需要的属性
        const newNode = {
          id: node.id,
          key: node.key,
          testItem: node.testItem,
          standardValue: node.standardValue,
          allowableRange: node.allowableRange
        };

        // 如果有子节点，递归处理
        if (node.children && node.children.length > 0) {
          const selectedChildren = filterSelectedNodes(node.children);
          if (selectedChildren.length > 0) {
            newNode.children = selectedChildren;
          }
        }

        result.push(newNode);
      } else if (node.children && node.children.length > 0) {
        // 如果当前节点未被选中，但可能有被选中的子节点
        const selectedChildren = filterSelectedNodes(node.children);
        if (selectedChildren.length > 0) {
          // 创建一个节点副本，并添加被选中的子节点
          const newNode = {
            id: node.id,
            key: node.key,
            testItem: node.testItem,
            standardValue: node.standardValue,
            allowableRange: node.allowableRange,
            children: selectedChildren
          };
          result.push(newNode);
        }
      }
    }

    return result;
  };

  const selectedTreeData = filterSelectedNodes(cloneTreeData);

  // 计算选中的项目总数
  const countSelectedItems = (nodes: any[]): number => {
    let count = 0;
    for (const node of nodes) {
      count += 1; // 计算当前节点
      if (node.children && node.children.length > 0) {
        count += countSelectedItems(node.children); // 递归计算子节点
      }
    }
    return count;
  };

  const selectedCount = countSelectedItems(selectedTreeData);

  // 将处理后的树形结构传递给父组件
  emit('confirm', selectedTreeData);
  message.success(`已选择${selectedCount}个测试项目`);
}

// 页面加载时获取数据
onMounted(() => {
  // 删除此处的fetchTestDetails调用，避免重复调用API
  // watch中的immediate:true已经确保了初始加载数据
});
</script>

<template>
  <div class="plan-detail-selector">
    <!--
 <div class="header">
      <div class="title">测试方案明细选择</div>
      <n-space style="display: flex; align-items: center;">
        <span class="plan-name">{{ planName }}</span>
        <n-tag type="info">{{ checkedRowKeys.length }}项已选择</n-tag>
      </n-space>
    </div> 
-->

    <NAlert type="info" style="margin-bottom: 16px">
      请选择需要进行比对测试的项目，选中的项目将被添加到测试数据表格中。
    </NAlert>

    <NDataTable
      :columns="columns"
      :data="planDetails"
      :bordered="false"
      :row-key="row => row.key"
      :checked-row-keys="checkedRowKeys"
      children-key="children"
      :indent="20"
      :max-height="300"
      :min-height="300"
      :pagination="false"
      striped
      :loading="loading"
      @update:checked-row-keys="handleCheckedRowKeysChange"
    ></NDataTable>

    <div class="footer">
      <NSpace justify="end">
        <NButton @click="cancel">取消</NButton>
        <NButton type="primary" :disabled="checkedRowKeys.length === 0" @click="confirm">
          确认选择({{ checkedRowKeys.length }})
        </NButton>
      </NSpace>
    </div>
  </div>
</template>

<style scoped>
.plan-detail-selector {
  /* padding: 0 0 16px 0; */
  height: 450px;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.plan-name {
  font-weight: bold;
  color: #2080f0;
}

.footer {
  padding-top: 10px;
  /* padding-bottom: 16px; */
  border-top: 1px solid #f0f0f0;
  margin-top: auto;
}
</style>
