<template>
  <!-- 根据视图模式决定容器类名，组件自包含所有样式 -->
  <div :class="containerClass">
    <!-- 默认操作按钮 -->
    <button class="action-btn" @click.stop="handleView" :title="t('View')">
      <i class="fa fa-eye"></i>
    </button>
    <button class="action-btn" @click.stop="handleEdit" :title="t('Edit')">
      <i class="fa fa-edit"></i>
    </button>
    <!-- Schema 编辑按钮 -->
    <button 
      class="action-btn schema-btn" 
      @click.stop="handleOpenSchemaEditor" 
      :title="t('Edit Schema')"
      :disabled="!canEditSchema"
    >
      <i class="fa fa-table"></i>
    </button>
    <button class="action-btn delete-btn" @click.stop="handleDelete" :title="t('Delete')">
      <i class="fa fa-trash"></i>
    </button>
    
    <!-- Schema 编辑器模态框 - 使用 Teleport 渲染到 body，避免事件冒泡问题 -->
    <Teleport to="body">
      <SchemaEditorModal
        v-model:visible="showSchemaEditor"
        :node-type="nodeType"
        :node-name="nodeName"
        :initial-schema="initialSchema"
        :on-save="handleSchemaSave"
        @close="showSchemaEditor = false"
      />
    </Teleport>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Teleport } from 'vue'
import { useMessage } from 'naive-ui'
import axios from 'axios'
import { t } from '@/shared/i18n'
import SchemaEditorModal from '@/core/components/SchemaEditorModal.vue'

interface Props {
  // 支持两种接口：context 或直接 props
  context?: {
    row: any
    entity: string
    openDetail: (name: string) => void
    editRecord: (row: any) => void
    deleteRecord: (name: string) => void
    router: any
    t: (key: string) => string
    viewMode?: 'card' | 'list'
  }
  row?: any
  entity?: string
  viewMode?: 'card' | 'list'
}

interface Emits {
  (e: 'view', row: any): void
  (e: 'edit', row: any): void
  (e: 'delete', row: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 兼容两种接口：优先使用直接 props，如果没有则使用 context
const row = computed(() => props.row || props.context?.row)
const entity = computed(() => props.entity || props.context?.entity)
const viewMode = computed(() => props.viewMode || props.context?.viewMode || 'list')

// 根据视图模式决定容器类名，组件自包含所有样式
const containerClass = computed(() => {
  return viewMode.value === 'card' ? 'actions-container card-actions' : 'actions-container col-actions'
})

const message = useMessage()
const showSchemaEditor = ref(false)

const nodeName = computed(() => row.value?.name || '')
const nodeType = computed(() => row.value?.node_type || '')
const initialSchema = computed(() => {
  const schema = row.value?.node_schema
  if (!schema) return {}
  if (typeof schema === 'string') {
    try {
      return JSON.parse(schema)
    } catch {
      return {}
    }
  }
  return schema
})

const canEditSchema = computed(() => {
  return !!nodeType.value
})

// 事件处理函数
function handleView() {
  if (props.context?.openDetail) {
    props.context.openDetail(row.value.name)
  } else {
    emit('view', row.value)
  }
}

function handleEdit() {
  if (props.context?.editRecord) {
    props.context.editRecord(row.value)
  } else {
    emit('edit', row.value)
  }
}

function handleDelete() {
  if (props.context?.deleteRecord) {
    props.context.deleteRecord(row.value.name)
  } else {
    emit('delete', row.value)
  }
}

async function handleOpenSchemaEditor() {
  if (!canEditSchema.value) {
    message.warning(t('Please select node type first'))
    return
  }
  
  // 如果列表数据中没有完整的 node_schema，需要从API获取完整记录
  if (!row.value?.node_schema) {
    try {
      const response = await axios.get(
        `/api/data/${encodeURIComponent(entity.value)}/${encodeURIComponent(nodeName.value)}`)
      
      const record = response.data?.data || {}
      // 更新 row 数据以便后续使用
      if (record.node_schema && row.value) {
        row.value.node_schema = record.node_schema
      }
    } catch (error) {
      console.error('获取节点数据失败:', error)
      message.error(t('Failed to load node data'))
      return
    }
  }
  
  showSchemaEditor.value = true
}

async function handleSchemaSave(schemaData: any) {
  try {
    // 保存 Schema 数据到后端
    const response = await axios.put(
      `/api/data/${encodeURIComponent(entity.value)}/${encodeURIComponent(nodeName.value)}`, {
        node_schema: schemaData
      })
    
    if (response.data?.success !== false) {
      // 更新本地 row 数据
      if (row.value) {
        row.value.node_schema = schemaData
      }
      message.success(t('Schema saved successfully'))
      showSchemaEditor.value = false
    } else {
      throw new Error(response.data?.message || t('Save failed'))
    }
  } catch (error: any) {
    console.error('保存 Schema 失败:', error)
    message.error(error?.response?.data?.message || error?.message || t('Save failed, please check permission and server logs'))
    throw error // 让组件处理错误显示
  }
}
</script>

<style scoped>
/* 操作按钮容器基础样式 */
.actions-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

/* 卡片视图样式：包含 footer 外观（padding, border-top, background） */
.card-actions {
  padding: 8px 16px;
  border-top: 1px solid #f3f4f6;
  background: #fafbfc;
  margin-top: auto;
}

/* 列表视图样式：只提供按钮排列，无背景（通过 actions-container 基础样式实现） */

/* 操作按钮通用样式 - 统一使用节点列表页的大小 */
.action-btn { 
  width: 28px; 
  height: 28px; 
  border: none; 
  background: #f3f4f6; 
  color: #6b7280; 
  border-radius: 6px; 
  cursor: pointer; 
  display: flex; 
  align-items: center; 
  justify-content: center; 
  font-size: 12px; 
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); 
}

.action-btn:hover:not(:disabled) { 
  background: #3b82f6; 
  color: white; 
}

.action-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* Schema 编辑按钮使用蓝色系，与流程编排按钮保持一致，表示配置/设置 */
.schema-btn:hover:not(:disabled) {
  background: #3b82f6;
  color: white;
}

/* 删除按钮使用红色 */
.delete-btn:hover:not(:disabled) {
  background: #ef4444;
  color: white;
}
</style>

