<template>
  <MainLayout>
    <div class="home">
        <!-- 只在工作流管理页面显示工作流列表 -->
        <div v-if="activeMenu === 'workflows'">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>工作流管理</span>
              <div class="header-buttons">
                <el-button @click="handleShowTemplates">从模板创建</el-button>
                <el-button @click="handleImportWorkflow">导入工作流</el-button>
                <el-button type="primary" @click="handleCreateWorkflow">创建工作流</el-button>
              </div>
            </div>
          </template>
          
          <!-- 搜索和筛选栏 -->
          <div class="filter-bar">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索工作流名称或描述..."
                  clearable
                  @clear="handleSearch"
                  @keyup.enter="handleSearch"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </el-col>
              <el-col :span="4">
                <el-select
                  v-model="filterStatus"
                  placeholder="状态筛选"
                  clearable
                  @change="handleFilter"
                >
                  <el-option label="全部" value="" />
                  <el-option label="草稿" value="draft" />
                  <el-option label="已发布" value="published" />
                  <el-option label="运行中" value="running" />
                  <el-option label="已停止" value="stopped" />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-select
                  v-model="sortBy"
                  placeholder="排序字段"
                  @change="handleSort"
                >
                  <el-option label="创建时间" value="created_at" />
                  <el-option label="更新时间" value="updated_at" />
                  <el-option label="名称" value="name" />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-select
                  v-model="sortOrder"
                  placeholder="排序方式"
                  @change="handleSort"
                >
                  <el-option label="降序" value="desc" />
                  <el-option label="升序" value="asc" />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-button @click="handleSearch" type="primary">搜索</el-button>
                <el-button @click="handleReset">重置</el-button>
                <el-button @click="handleRefresh" :loading="workflowStore.loading">刷新</el-button>
              </el-col>
            </el-row>
          </div>
          
          <!-- 批量操作栏 -->
          <div v-if="selectedWorkflows.length > 0" class="batch-actions-bar" style="margin-bottom: 15px;">
            <el-alert
              :title="`已选择 ${selectedWorkflows.length} 个工作流`"
              type="info"
              :closable="false"
              show-icon
            >
              <template #default>
                <div class="batch-actions">
                  <el-button type="primary" size="small" @click="batchExecuteDialogVisible = true">
                    <el-icon><VideoPlay /></el-icon>
                    批量执行
                  </el-button>
                  <el-button type="success" size="small" @click="handleBatchExport">
                    <el-icon><Download /></el-icon>
                    批量导出
                  </el-button>
                  <el-button type="danger" size="small" @click="handleBatchDelete">
                    <el-icon><Delete /></el-icon>
                    批量删除
                  </el-button>
                  <el-button size="small" @click="selectedWorkflows = []">
                    取消选择
                  </el-button>
                </div>
              </template>
            </el-alert>
          </div>

          <el-table 
            :data="workflowStore.workflows" 
            v-loading="workflowStore.loading" 
            style="width: 100%"
            @sort-change="handleTableSort"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="名称" sortable="custom" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" sortable="custom" width="180">
              <template #default="{ row }">
                {{ formatDate(row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column prop="updated_at" label="更新时间" sortable="custom" width="180">
              <template #default="{ row }">
                {{ formatDate(row.updated_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="450">
              <template #default="{ row }">
                <el-button size="small" @click="handleEditWorkflow(row)">编辑</el-button>
                <el-button size="small" @click="handleViewVersions(row)">版本</el-button>
                <el-button size="small" @click="handleExportWorkflow(row)">导出</el-button>
                <el-button size="small" @click="handleViewExecutions(row)">执行历史</el-button>
                <el-button size="small" type="danger" @click="handleDeleteWorkflow(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        </div>

    <!-- 模板选择对话框 -->
    <el-dialog v-model="templateDialogVisible" title="从模板创建工作流" width="800px">
      <div v-loading="templatesLoading" class="templates-container">
        <el-row :gutter="20">
          <el-col :span="12" v-for="template in templates" :key="template.id">
            <el-card class="template-card" shadow="hover" @click="handleSelectTemplate(template)">
              <template #header>
                <div class="template-header">
                  <h3>{{ template.name }}</h3>
                </div>
              </template>
              <p class="template-description">{{ template.description }}</p>
              <el-button type="primary" style="width: 100%; margin-top: 10px;">使用此模板</el-button>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 版本管理对话框 -->
    <el-dialog v-model="versionDialogVisible" title="工作流版本管理" width="900px">
      <div v-loading="versionsLoading">
        <el-table :data="versions" style="width: 100%">
          <el-table-column prop="version" label="版本号" width="100">
            <template #default="{ row }">
              <el-tag v-if="row.comment === '当前版本'" type="success">v{{ row.version }}</el-tag>
              <span v-else>v{{ row.version }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column prop="comment" label="备注" />
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button 
                size="small" 
                @click="handleViewVersionDetail(row)"
                v-if="row.comment !== '当前版本'"
              >
                查看
              </el-button>
              <el-button 
                size="small" 
                type="primary"
                @click="handleRollbackVersion(row)"
                v-if="row.comment !== '当前版本'"
              >
                回滚
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 导入工作流对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入工作流" width="600px">
      <el-upload
        class="upload-demo"
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        accept=".json"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将JSON文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传JSON格式的工作流文件
          </div>
        </template>
      </el-upload>
      <div style="margin-top: 20px;">
        <el-button type="primary" @click="handleConfirmImport" :loading="importing">导入</el-button>
        <el-button @click="importDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 批量执行对话框 -->
    <el-dialog
      v-model="batchExecuteDialogVisible"
      title="批量执行工作流"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-alert
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom: 20px;"
      >
        <template #title>
          <div style="font-size: 12px;">
            将执行选中的 {{ selectedWorkflows.length }} 个工作流
          </div>
        </template>
      </el-alert>
      <el-form :model="batchExecuteForm" label-width="100px">
        <el-form-item label="执行参数">
          <el-alert
            type="info"
            :closable="false"
            show-icon
            style="margin-bottom: 10px;"
          >
            <template #title>
              <div style="font-size: 12px;">
                输入JSON格式的执行参数，这些参数将作为所有工作流的初始输入数据。<br/>
                例如: {"input": "你好", "value": 10, "status": "active"}
              </div>
            </template>
          </el-alert>
          <el-input
            v-model="batchExecuteForm.inputData"
            type="textarea"
            :rows="8"
            placeholder='{"input": "你好", "value": 10}'
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchExecuteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmBatchExecute" :loading="batchExecuting">
          开始批量执行
        </el-button>
      </template>
    </el-dialog>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled, Search, Document, User, List, Connection, Setting, Star, VideoPlay, Download, Delete, Lock, Monitor, Bell } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useWorkflowStore } from '@/stores/workflow'
import api from '@/api'
import MainLayout from '@/components/MainLayout.vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const workflowStore = useWorkflowStore()

// 当前激活的菜单
const activeMenu = computed(() => {
  if (route.path === '/agents' || route.path.startsWith('/agents/')) return 'agents'
  if (route.path === '/executions' || route.path.startsWith('/executions/')) return 'executions'
  if (route.path === '/data-sources') return 'data-sources'
  if (route.path === '/model-configs') return 'model-configs'
  if (route.path === '/permissions') return 'permissions'
  if (route.path === '/template-market') return 'template-market'
  return 'workflows'
})

// 菜单选择
const handleMenuSelect = (key: string) => {
  if (key === 'workflows') {
    router.push('/')
  } else if (key === 'agents') {
    router.push('/agents')
  } else if (key === 'executions') {
    router.push('/executions')
  } else if (key === 'data-sources') {
    router.push('/data-sources')
  } else if (key === 'model-configs') {
    router.push('/model-configs')
  }
}

// 模板相关
const templateDialogVisible = ref(false)
const templates = ref<any[]>([])
const templatesLoading = ref(false)

// 导入相关
const importDialogVisible = ref(false)
const fileList = ref<any[]>([])
const importing = ref(false)
const importFileContent = ref<any>(null)

// 版本管理相关
const versionDialogVisible = ref(false)

// 批量操作相关
const selectedWorkflows = ref<any[]>([])
const batchExecuteDialogVisible = ref(false)
const batchExecuteForm = ref({
  inputData: '{}'
})
const batchExecuting = ref(false)
const versions = ref<any[]>([])
const versionsLoading = ref(false)
const currentWorkflowForVersion = ref<any>(null)

// 搜索、筛选、排序
const searchKeyword = ref('')
const filterStatus = ref('')
const sortBy = ref('created_at')
const sortOrder = ref('desc')

onMounted(async () => {
  // 只有在有token的情况下才尝试获取数据
  if (!userStore.token) {
    return
  }
  
  if (!userStore.user) {
    try {
      await userStore.fetchUser()
    } catch (error) {
      console.error('获取用户信息失败', error)
      // 如果获取用户信息失败，清除token并跳转到登录页
      userStore.logout()
      return
    }
  }
  
  // 只有在成功获取用户信息后才获取工作流列表
  if (userStore.user) {
    await loadWorkflows()
  }
})

// 加载工作流列表
const loadWorkflows = async () => {
  try {
    await workflowStore.fetchWorkflows({
      search: searchKeyword.value || undefined,
      status: filterStatus.value || undefined,
      sortBy: sortBy.value,
      sortOrder: sortOrder.value
    })
  } catch (error) {
    console.error('获取工作流列表失败', error)
    ElMessage.error('获取工作流列表失败')
  }
}

// 搜索
const handleSearch = () => {
  loadWorkflows()
}

// 筛选
const handleFilter = () => {
  loadWorkflows()
}

// 排序
const handleSort = () => {
  loadWorkflows()
}

// 表格排序
const handleTableSort = ({ prop, order }: any) => {
  if (prop) {
    sortBy.value = prop
    sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
    loadWorkflows()
  }
}

// 重置
const handleReset = () => {
  searchKeyword.value = ''
  filterStatus.value = ''
  sortBy.value = 'created_at'
  sortOrder.value = 'desc'
  loadWorkflows()
}

// 刷新
const handleRefresh = () => {
  loadWorkflows()
}

const getStatusType = (status: string) => {
  const map: Record<string, string> = {
    draft: 'info',
    published: 'success',
    running: 'warning',
    stopped: 'danger'
  }
  return map[status] || 'info'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    draft: '草稿',
    published: '已发布',
    running: '运行中',
    stopped: '已停止'
  }
  return map[status] || status
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

const handleCreateWorkflow = () => {
  router.push('/workflow')
}

const handleEditWorkflow = (workflow: any) => {
  router.push(`/workflow/${workflow.id}`)
}

const handleDeleteWorkflow = async (workflow: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个工作流吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await workflowStore.deleteWorkflow(workflow.id)
    ElMessage.success('删除成功')
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleViewExecutions = (workflow: any) => {
  router.push(`/executions?workflow_id=${workflow.id}`)
}

const handleLogout = () => {
  userStore.logout()
  router.push('/login')
}

// 显示模板选择对话框
const handleShowTemplates = async () => {
  templateDialogVisible.value = true
  templatesLoading.value = true
  try {
    templates.value = await workflowStore.fetchTemplates()
  } catch (error) {
    ElMessage.error('获取模板列表失败')
  } finally {
    templatesLoading.value = false
  }
}

// 选择模板
const handleSelectTemplate = async (template: any) => {
  try {
    const result = await ElMessageBox.prompt('请输入工作流名称', '从模板创建', {
      confirmButtonText: '创建',
      cancelButtonText: '取消',
      inputValue: template.name
    })
    
    const workflow = await workflowStore.createWorkflowFromTemplate(template.id, result.value)
    templateDialogVisible.value = false
    ElMessage.success('工作流创建成功')
    router.push(`/workflow/${workflow.id}`)
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('创建工作流失败')
    }
  }
}

// 显示导入对话框
const handleImportWorkflow = () => {
  importDialogVisible.value = true
  fileList.value = []
  importFileContent.value = null
}

// 文件选择
const handleFileChange = (file: any) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const content = JSON.parse(e.target?.result as string)
      importFileContent.value = content
    } catch (error) {
      ElMessage.error('文件格式错误，请上传有效的JSON文件')
      fileList.value = []
    }
  }
  reader.readAsText(file.raw)
}

// 确认导入
const handleConfirmImport = async () => {
  if (!importFileContent.value) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }
  
  importing.value = true
  try {
    const workflow = await workflowStore.importWorkflow(importFileContent.value)
    importDialogVisible.value = false
    ElMessage.success('工作流导入成功')
    router.push(`/workflow/${workflow.id}`)
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '导入工作流失败')
  } finally {
    importing.value = false
  }
}

// 导出工作流
const handleExportWorkflow = async (workflow: any) => {
  try {
    await workflowStore.exportWorkflow(workflow.id)
    ElMessage.success('工作流导出成功')
  } catch (error: any) {
    ElMessage.error('导出工作流失败')
  }
}

// 批量操作
const handleSelectionChange = (selection: any[]) => {
  selectedWorkflows.value = selection
}

const handleBatchExecute = async () => {
  if (selectedWorkflows.value.length === 0) {
    ElMessage.warning('请先选择要执行的工作流')
    return
  }
  batchExecuteDialogVisible.value = true
}

const handleConfirmBatchExecute = async () => {
  if (selectedWorkflows.value.length === 0) {
    return
  }
  
  batchExecuting.value = true
  try {
    let inputData = {}
    try {
      inputData = JSON.parse(batchExecuteForm.value.inputData)
    } catch (e) {
      ElMessage.warning('输入数据格式错误，将使用空对象')
    }
    
    const workflowIds = selectedWorkflows.value.map(w => w.id)
    const response = await api.post('/api/v1/batch/execute', {
      workflow_ids: workflowIds,
      input_data: inputData
    })
    
    ElMessage.success(`批量执行完成：成功 ${response.data.success}，失败 ${response.data.failed}`)
    batchExecuteDialogVisible.value = false
    selectedWorkflows.value = []
    batchExecuteForm.value.inputData = '{}'
    
    // 跳转到执行历史页面
    router.push('/executions')
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '批量执行失败')
  } finally {
    batchExecuting.value = false
  }
}

const handleBatchExport = async () => {
  if (selectedWorkflows.value.length === 0) {
    ElMessage.warning('请先选择要导出的工作流')
    return
  }
  
  try {
    const workflowIds = selectedWorkflows.value.map(w => w.id)
    const response = await api.post('/api/v1/batch/export', {
      workflow_ids: workflowIds
    })
    
    // 下载JSON文件
    const dataStr = JSON.stringify(response.data, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(dataBlob)
    const link = document.createElement('a')
    link.href = url
    link.download = `workflows_export_${new Date().getTime()}.json`
    link.click()
    URL.revokeObjectURL(url)
    
    ElMessage.success(`成功导出 ${response.data.total} 个工作流`)
    selectedWorkflows.value = []
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '批量导出失败')
  }
}

const handleBatchDelete = async () => {
  if (selectedWorkflows.value.length === 0) {
    ElMessage.warning('请先选择要删除的工作流')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedWorkflows.value.length} 个工作流吗？此操作不可恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const workflowIds = selectedWorkflows.value.map(w => w.id)
    const response = await api.post('/api/v1/batch/delete', workflowIds)
    
    ElMessage.success(response.data.message)
    selectedWorkflows.value = []
    await workflowStore.fetchWorkflows()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.detail || '批量删除失败')
    }
  }
}

// 查看版本
const handleViewVersions = async (workflow: any) => {
  currentWorkflowForVersion.value = workflow
  versionDialogVisible.value = true
  versionsLoading.value = true
  try {
    versions.value = await workflowStore.fetchWorkflowVersions(workflow.id)
  } catch (error: any) {
    ElMessage.error('获取版本列表失败')
  } finally {
    versionsLoading.value = false
  }
}

// 查看版本详情
const handleViewVersionDetail = async (version: any) => {
  try {
    const versionData = await workflowStore.fetchWorkflowVersion(
      version.workflow_id,
      version.version
    )
    // 跳转到工作流编辑页面，并加载该版本的数据
    router.push(`/workflow/${version.workflow_id}?version=${version.version}`)
    versionDialogVisible.value = false
  } catch (error: any) {
    ElMessage.error('获取版本详情失败')
  }
}

// 回滚版本
const handleRollbackVersion = async (version: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要回滚到版本 v${version.version} 吗？当前版本将被保存为历史版本。`,
      '确认回滚',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await workflowStore.rollbackWorkflowVersion(version.workflow_id, version.version)
    ElMessage.success('回滚成功')
    
    // 刷新版本列表
    versions.value = await workflowStore.fetchWorkflowVersions(version.workflow_id)
    
    // 刷新工作流列表
    await loadWorkflows()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('回滚失败')
    }
  }
}
</script>

<style scoped>
.home {
  width: 100%;
  height: 100vh;
}

.el-header {
  background-color: #409eff;
  color: white;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.el-header h1 {
  margin: 0;
  font-size: 24px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.nav-menu {
  margin-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.el-main {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
}

.header-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-bar {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.templates-container {
  max-height: 500px;
  overflow-y: auto;
}

.template-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.template-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.template-header h3 {
  margin: 0;
  font-size: 16px;
}

.template-description {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  margin: 10px 0;
}
</style>
