<template>
  <!-- 根据视图模式决定容器类名，组件自包含所有样式 -->
  <div :class="containerClass">
    <!-- 默认操作按钮 -->
    <button class="action-btn" @click.stop="context.openDetail(context.row.name)" :title="context.t('View')">
      <i class="fa fa-eye"></i>
    </button>
    <button class="action-btn" @click.stop="context.editRecord(context.row)" :title="context.t('Edit')">
      <i class="fa fa-edit"></i>
    </button>
    <!-- 执行按钮 -->
    <button 
      class="action-btn execute-btn" 
      @click.stop="handleExecute" 
      :title="context.t('Execute')"
      :disabled="executing"
    >
      <i :class="executing ? 'fa fa-spinner fa-spin' : 'fa fa-play'"></i>
    </button>
    <!-- 流程编排按钮 -->
    <button 
      class="action-btn flow-builder-btn" 
      @click.stop="handleFlowBuilder" 
      :title="context.t('Flow Builder')"
    >
      <i class="fa fa-sitemap"></i>
    </button>
    <button class="action-btn delete-btn" @click.stop="context.deleteRecord(context.row.name)" :title="context.t('Delete')">
      <i class="fa fa-trash"></i>
    </button>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useMessage } from 'naive-ui'
import { pageTypeToSlug } from '@/shared/utils/slug'
import { api } from '@/shared/api/common'
import axios from 'axios'

const props = defineProps<{
  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'
  }
}>()

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

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

async function handleExecute() {
  try {
    executing.value = true
    const agentName = props.context.row.name
    
    if (!agentName) {
      message.error(props.context.t('Agent name is required'))
      return
    }
    
    const res = await api.call('jingrow.ai.utils.jlocal.execute_local_ai_agent', {
      name: agentName
    })
    
    const result = res?.message || res
    
    if (result?.success) {
      message.success(result.message || props.context.t('Agent execution started successfully'))
    } else {
      message.error(result?.error || props.context.t('Execution failed'))
    }
  } catch (error: any) {
    message.error(error?.message || props.context.t('Execution failed'))
  } finally {
    executing.value = false
  }
}

async function handleFlowBuilder() {
  try {
    const name = props.context.row.name
    let flowData: any = {}
    
    // 如果列表数据中没有 agent_flow 字段，需要从 API 获取完整记录
    if (props.context.row.agent_flow !== undefined && props.context.row.agent_flow !== null) {
      const raw = props.context.row.agent_flow
      flowData = raw
      if (typeof raw === 'string') {
        try { flowData = JSON.parse(raw) } catch { flowData = {} }
      }
    } else {
      // 从 API 获取完整记录数据，包含 agent_flow 字段
      try {
        const response = await axios.get(`/api/data/${encodeURIComponent(props.context.entity)}/${encodeURIComponent(name)}`)
        
        const record = response.data?.data || {}
        const raw = record.agent_flow ?? {}
        flowData = raw
        if (typeof raw === 'string') {
          try { flowData = JSON.parse(raw) } catch { flowData = {} }
        }
      } catch (error) {
        console.error('获取智能体数据失败:', error)
        message.error(props.context.t('Failed to load agent data'))
        return
      }
    }
    
    const pagetype = pageTypeToSlug(props.context.entity)
    
    const { useFlowBuilderStore } = await import('@/shared/stores/flowBuilder')
    const flowBuilderStore = useFlowBuilderStore()
    
    flowBuilderStore.activateFlowBuilder(flowData, name)
    
    props.context.router.push({ name: 'FlowBuilder', query: { pagetype, id: name } })
  } catch (error: any) {
    console.error('打开流程编排失败:', error)
    message.error(error?.message || props.context.t('Failed to open flow builder'))
  }
}
</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;
}

/* 流程编排按钮使用蓝色，与详情页保持一致 */
.flow-builder-btn:hover:not(:disabled) {
  background: #3b82f6;
  color: white;
}

/* 执行按钮使用绿色 */
.execute-btn:hover:not(:disabled) {
  background: #10b981;
  color: white;
}

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

