<template>
  <div class="ref-kind-table">
    <div class="rkt-header">
      <el-input
        v-model="search"
        :placeholder="`筛选 ${kind} ...`"
        size="small"
        clearable
        class="rkt-search"
      >
        <template #prefix><el-icon><Search /></el-icon></template>
      </el-input>
      <el-button size="small" :loading="loading" @click="refresh">刷新</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="filteredObjects"
      stripe
      border
      size="small"
      class="rkt-table"
      highlight-current-row
      @current-change="onSelect"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="名称" min-width="160" />
      <el-table-column prop="typeName" label="类型" width="180" />
      <el-table-column prop="layer" label="图层" width="120" />
      <el-table-column prop="summary" label="摘要" min-width="220" show-overflow-tooltip />
    </el-table>

    <el-card v-if="currentObject" shadow="never" class="rkt-actions">
      <template #header>
        <span>{{ currentObject.typeName }} #{{ currentObject.id }} · {{ currentObject.name }}</span>
      </template>
      <div v-if="loadingMethods" class="rkt-loading-methods">加载方法中…</div>
      <div v-else-if="methods.length === 0" class="rkt-empty">该类型未暴露 MethodMember</div>
      <div v-else class="rkt-method-grid">
        <el-tooltip
          v-for="m in methods"
          :key="m.methodName"
          :content="m.description ?? m.hint ?? ''"
          :disabled="!m.description && !m.hint"
          placement="top"
        >
          <el-button
            size="small"
            type="primary"
            plain
            :loading="executing === m.methodName"
            @click="runMethod(m)"
          >
            {{ m.label ?? m.methodName }}
          </el-button>
        </el-tooltip>
      </div>
    </el-card>
    <el-empty v-else-if="!loading && objects.length === 0" :description="emptyText ?? `当前 ${kind} 无条目`" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { reflectionApi, type ReflectionKind, type ReflectionMethod, type ReflectionObject } from '@/api/reflection'

const props = defineProps<{
  kind: ReflectionKind
  /** 额外的客户端筛选关键字（用于 taskflow / trigger 这种从 mission 派生的虚拟分类）。 */
  extraFilter?: string
  emptyText?: string
}>()

const loading = ref(false)
const loadingMethods = ref(false)
const executing = ref<string | null>(null)
const search = ref('')

const objects = ref<ReflectionObject[]>([])
const currentObject = ref<ReflectionObject | null>(null)
const methods = ref<ReflectionMethod[]>([])

const filteredObjects = computed(() => {
  let arr = objects.value
  if (props.extraFilter) {
    const k = props.extraFilter.toLowerCase()
    arr = arr.filter((o) => (o.typeName ?? '').toLowerCase().includes(k) || (o.name ?? '').toLowerCase().includes(k))
  }
  const q = search.value.trim().toLowerCase()
  if (q) {
    arr = arr.filter((o) =>
      (o.name ?? '').toLowerCase().includes(q) ||
      (o.typeName ?? '').toLowerCase().includes(q) ||
      String(o.id).includes(q)
    )
  }
  return arr
})

async function refresh() {
  loading.value = true
  try {
    objects.value = await reflectionApi.listObjects(props.kind)
  } catch (err) {
    ElMessage.error(`加载 ${props.kind} 失败：${(err as Error).message}`)
  } finally {
    loading.value = false
  }
}

async function onSelect(row: ReflectionObject | null) {
  currentObject.value = row
  methods.value = []
  if (!row) return
  loadingMethods.value = true
  try {
    methods.value = await reflectionApi.listMethods(props.kind, row.id)
  } catch (err) {
    ElMessage.error(`加载方法失败：${(err as Error).message}`)
  } finally {
    loadingMethods.value = false
  }
}

async function runMethod(m: ReflectionMethod) {
  if (!currentObject.value) return
  if (m.hasParams) {
    ElMessage.info(`方法 ${m.methodName} 需要参数，请在「设计与编排」详细面板里执行（待开发）`)
    return
  }
  executing.value = m.methodName
  try {
    const r = await reflectionApi.execute(props.kind, currentObject.value.id, m.methodName)
    ElMessage.success(`${m.label ?? m.methodName} 完成${r.returnValue ? `：${r.returnValue}` : ''}`)
  } catch (err) {
    ElMessage.error(`执行失败：${(err as Error).message}`)
  } finally {
    executing.value = null
  }
}

watch(() => props.kind, refresh)
onMounted(refresh)
</script>

<style scoped>
.ref-kind-table {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.rkt-header {
  display: flex;
  align-items: center;
  gap: 8px;
}
.rkt-search { flex: 0 0 320px; }
.rkt-table { flex: 1; min-height: 200px; }
.rkt-actions { margin-top: 8px; }
.rkt-method-grid { display: flex; flex-wrap: wrap; gap: 6px; }
.rkt-loading-methods, .rkt-empty {
  color: var(--mg-text-muted);
  font-size: 12px;
  padding: 8px 4px;
}
</style>
