<template>
  <div>
    <div class="flex justify-between items-center mb-4">
      <div class="flex items-center">
        <h3 class="text-md font-medium mr-2">参数列表</h3>
        <el-tooltip content="查看模板标记语法指南" placement="top">
          <el-button
            type="info"
            size="small"
            circle
            @click="guideVisible = true"
          >
            <el-icon><QuestionFilled /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
      <el-button
        type="primary"
        icon="Refresh"
        :loading="parsingParams"
        :disabled="!attId"
        @click="handleReparseParams"
      >解析参数</el-button>
    </div>

    <!-- 参数表格 -->
    <el-table
      v-loading="parsingParams"
      :data="hierarchicalParamsList"
      border
      row-key="paramId"
      highlight-current-row
      style="width: 100%"
      max-height="500px"
      :tree-props="{
        children: 'children',
        hasChildren: 'hasChildren'
      }"
      :default-expand-all="true"
    >
      <el-table-column type="index" label="#" width="50" align="center" />
      <el-table-column prop="paramName" label="参数名称" min-width="180">
        <template #default="scope">
          <div class="param-name-cell">
            <!-- 容器类型参数显示文件夹图标 -->
            <el-icon v-if="isContainerType(scope.row.paramType)" class="mr-1 text-orange-500">
              <Folder />
            </el-icon>
            <!-- 普通参数显示文档图标 -->
            <el-icon v-else class="mr-1 text-blue-500">
              <Document />
            </el-icon>

            <!-- 显示参数名称，嵌套参数只显示最后一级 -->
            <span class="font-medium">
              {{ getDisplayName(scope.row) }}
            </span>

            <!-- 显示完整路径提示 -->
            <el-tooltip v-if="scope.row.paramPath && scope.row.paramPath !== scope.row.paramName"
                        :content="`完整路径: ${scope.row.paramPath}`" placement="top">
              <el-icon class="ml-1 text-gray-400 cursor-help">
                <InfoFilled />
              </el-icon>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="paramType" label="参数类型" width="120" align="center">
        <template #default="scope">
          <el-tag :type="getParamTypeTag(scope.row.paramType)" size="small">
            {{ getParamTypeText(scope.row.paramType) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="paramDesc" label="参数描述" min-width="150">
        <template #default="scope">
          <el-input
            v-model="scope.row.paramDesc"
            placeholder="请输入参数描述"
            size="small"
            @change="updateParamDetail('paramDesc', scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column prop="isRequired" label="必填" width="80" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isRequired"
            :active-value="'1'"
            :inactive-value="'0'"
            size="small"
            @change="updateParamDetail('isRequired', scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column prop="isArray" label="数组" width="80" align="center">
        <template #default="scope">
          <el-tag
            :type="scope.row.isArray === '1' ? 'warning' : 'info'"
            size="small"
          >
            {{ scope.row.isArray === '1' ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="defaultValue" label="默认值" min-width="150">
        <template #default="scope">
          <el-input
            v-model="scope.row.defaultValue"
            placeholder="请输入默认值"
            size="small"
            @change="updateParamDetail('defaultValue', scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <el-empty
      v-if="!paramsList.length && !parsingParams"
      description="请先上传模板文件并解析参数"
    />

    <!-- 参数统计信息 -->
    <div v-if="paramsList.length" class="mt-4 p-3 bg-gray-50 rounded">
      <div class="text-sm text-gray-600">
        <span class="mr-4">
          <el-icon><Document /></el-icon>
          总参数: {{ paramsList.length }}
        </span>
        <span class="mr-4">
          <el-icon><Folder /></el-icon>
          容器参数: {{ containerParamsCount }}
        </span>
        <span class="mr-4">
          嵌套参数: {{ nestedParamsCount }}
        </span>
        <span>
          根级参数: {{ rootParamsCount }}
        </span>
      </div>
    </div>

    <!-- 模板指南对话框 -->
    <el-dialog
      v-model="guideVisible"
      title="模板标记语法指南"
      width="80%"
      top="5vh"
      append-to-body
    >
      <template-guide />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { Document, Folder, QuestionFilled, InfoFilled } from '@element-plus/icons-vue';
import { TemplateParamVO } from '@/api/system/template/types';
import TemplateGuide from './TemplateGuide.vue';

type TagType = 'primary' | 'success' | 'info' | 'warning' | 'danger';

const props = defineProps({
  paramsList: {
    type: Array as PropType<TemplateParamVO[]>,
    default: () => []
  },
  templateId: {
    type: [Number, String],
    default: undefined
  },
  attId: {
    type: [Number, String],
    default: undefined
  },
  parsingParams: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update-param', 'reparse-params']);

// 指南弹窗控制
const guideVisible = ref(false);

// 构建层级参数结构
const hierarchicalParamsList = computed(() => {
  if (!props.paramsList.length) return [];

  // 创建参数映射
  const paramMap = new Map<number | string, any>();
  const rootParams: any[] = [];


  // 首先处理所有参数，建立映射关系
  props.paramsList.forEach(param => {
    const enhancedParam = {
      ...param,
      children: [],
      hasChildren: false
    };

    paramMap.set(param.paramId, enhancedParam);

    // 如果是根级参数（parentId为null或undefined）
    if (!param.parentId) {
      rootParams.push(enhancedParam);
    }
  });

  // 建立父子关系
  props.paramsList.forEach(param => {
    if (param.parentId) {
      const parent = paramMap.get(param.parentId);
      const current = paramMap.get(param.paramId);

      if (parent && current) {
        parent.children.push(current);
        parent.hasChildren = true;
      }
    }
  });

  // 排序：根据sortOrder排序
  const sortParams = (params: any[]) => {
    params.sort((a, b) => {
      const orderA = a.sortOrder || 999;
      const orderB = b.sortOrder || 999;
      return orderA - orderB;
    });

    // 递归排序子参数
    params.forEach(param => {
      if (param.children && param.children.length > 0) {
        sortParams(param.children);
      }
    });
  };

  sortParams(rootParams);

  return rootParams;
});

// 参数统计
const containerParamsCount = computed(() => {
  return props.paramsList.filter(p => isContainerType(p.paramType)).length;
});

const nestedParamsCount = computed(() => {
  return props.paramsList.filter(p => p.parentId).length;
});

const rootParamsCount = computed(() => {
  return props.paramsList.filter(p => !p.parentId).length;
});

// 判断是否为容器类型
const isContainerType = (paramType: string): boolean => {
  const containerTypes = ['list', 'conditionalList', 'nestedList', 'table'];
  return containerTypes.includes(paramType);
};

// 获取显示名称
const getDisplayName = (param: any): string => {
  // 对于嵌套参数，只显示最后一级的名称
  if (param.paramPath && param.paramPath.includes('.')) {
    const parts = param.paramPath.split('.');
    return parts[parts.length - 1];
  }
  return param.paramName;
};

// 参数类型相关方法
const getParamTypeTag = (paramType: string): TagType => {
  const typeMap: Record<string, TagType> = {
    'text': 'success',
    'list': 'warning',
    'conditionalList': 'warning',
    'nestedList': 'warning',
    'table': 'danger',
    'image': 'info'
  };
  return typeMap[paramType] || 'info';
};

const getParamTypeText = (paramType: string): string => {
  const nameMap: Record<string, string> = {
    'text': '文本',
    'list': '列表',
    'conditionalList': '条件列表',
    'nestedList': '嵌套列表',
    'table': '表格',
    'image': '图片'
  };
  return nameMap[paramType] || paramType;
};

// 更新参数详情
const updateParamDetail = (field: string, param: TemplateParamVO) => {
  if (!param) return;
  emit('update-param', field, param);
};

// 解析参数
const handleReparseParams = () => {
  emit('reparse-params');
};
</script>

<style scoped>
.param-name-cell {
  display: flex;
  align-items: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 13px;
}

:deep(.el-table .cell) {
  padding: 6px 8px;
}

/* 树形表格缩进样式 */
:deep(.el-table__expand-column .el-table__expand-icon) {
  height: 16px;
  width: 16px;
}

/* 容器参数样式 */
:deep(.el-table__row.has-children > .el-table_1_column_1 .cell) {
  font-weight: 600;
}

/* 输入框样式 */
:deep(.el-input--small .el-input__inner) {
  height: 28px;
  line-height: 28px;
}

/* 开关样式 */
:deep(.el-switch--small) {
  height: 20px;
}

/* 标签样式 */
:deep(.el-tag--small) {
  height: 20px;
  padding: 0 5px;
  font-size: 12px;
}
</style>
