/**
 * 工作流状态管理
 */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/api'
import type { Workflow, WorkflowNode, WorkflowEdge } from '@/types'

export const useWorkflowStore = defineStore('workflow', () => {
  const workflows = ref<Workflow[]>([])
  const currentWorkflow = ref<Workflow | null>(null)
  const loading = ref(false)

  // 获取工作流列表（支持搜索、筛选、排序）
  const fetchWorkflows = async (options?: {
    search?: string
    status?: string
    sortBy?: string
    sortOrder?: string
    skip?: number
    limit?: number
  }) => {
    loading.value = true
    try {
      const params: any = {}
      if (options?.search) params.search = options.search
      if (options?.status) params.status = options.status
      if (options?.sortBy) params.sort_by = options.sortBy
      if (options?.sortOrder) params.sort_order = options.sortOrder
      if (options?.skip !== undefined) params.skip = options.skip
      if (options?.limit !== undefined) params.limit = options.limit
      
      const response = await api.get('/api/v1/workflows', { params })
      workflows.value = response.data
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 创建工作流
  const createWorkflow = async (workflowData: {
    name: string
    description?: string
    nodes: WorkflowNode[]
    edges: WorkflowEdge[]
  }) => {
    loading.value = true
    try {
      const response = await api.post('/api/v1/workflows', workflowData)
      workflows.value.push(response.data)
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 获取工作流详情
  const fetchWorkflow = async (id: string) => {
    loading.value = true
    try {
      const response = await api.get(`/api/v1/workflows/${id}`)
      currentWorkflow.value = response.data
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 更新工作流
  const updateWorkflow = async (id: string, workflowData: Partial<Workflow>) => {
    loading.value = true
    try {
      const response = await api.put(`/api/v1/workflows/${id}`, workflowData)
      const index = workflows.value.findIndex(w => w.id === id)
      if (index !== -1) {
        workflows.value[index] = response.data
      }
      if (currentWorkflow.value?.id === id) {
        currentWorkflow.value = response.data
      }
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 删除工作流
  const deleteWorkflow = async (id: string) => {
    loading.value = true
    try {
      await api.delete(`/api/v1/workflows/${id}`)
      workflows.value = workflows.value.filter(w => w.id !== id)
      if (currentWorkflow.value?.id === id) {
        currentWorkflow.value = null
      }
    } finally {
      loading.value = false
    }
  }

  // 设置当前工作流
  const setCurrentWorkflow = (workflow: Workflow | null) => {
    currentWorkflow.value = workflow
  }

  // 获取工作流模板列表
  const fetchTemplates = async () => {
    try {
      const response = await api.get('/api/v1/workflows/templates')
      return response.data
    } catch (error) {
      console.error('获取模板列表失败', error)
      throw error
    }
  }

  // 获取模板详情
  const fetchTemplate = async (templateId: string) => {
    try {
      const response = await api.get(`/api/v1/workflows/templates/${templateId}`)
      return response.data
    } catch (error) {
      console.error('获取模板详情失败', error)
      throw error
    }
  }

  // 从模板创建工作流
  const createWorkflowFromTemplate = async (templateId: string, name?: string, description?: string) => {
    loading.value = true
    try {
      const params: any = {}
      if (name) params.name = name
      if (description) params.description = description
      const response = await api.post(`/api/v1/workflows/templates/${templateId}/create`, null, { params })
      workflows.value.push(response.data)
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 导出工作流
  const exportWorkflow = async (workflowId: string) => {
    try {
      const response = await api.get(`/api/v1/workflows/${workflowId}/export`)
      // 创建下载链接
      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 = `${response.data.name || 'workflow'}_${Date.now()}.json`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
      return response.data
    } catch (error) {
      console.error('导出工作流失败', error)
      throw error
    }
  }

  // 导入工作流
  const importWorkflow = async (workflowData: any) => {
    loading.value = true
    try {
      const response = await api.post('/api/v1/workflows/import', workflowData)
      workflows.value.push(response.data)
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 获取工作流版本列表
  const fetchWorkflowVersions = async (workflowId: string) => {
    try {
      const response = await api.get(`/api/v1/workflows/${workflowId}/versions`)
      return response.data
    } catch (error) {
      console.error('获取版本列表失败', error)
      throw error
    }
  }

  // 获取工作流特定版本
  const fetchWorkflowVersion = async (workflowId: string, version: number) => {
    try {
      const response = await api.get(`/api/v1/workflows/${workflowId}/versions/${version}`)
      return response.data
    } catch (error) {
      console.error('获取版本详情失败', error)
      throw error
    }
  }

  // 回滚工作流到指定版本
  const rollbackWorkflowVersion = async (workflowId: string, version: number, comment?: string) => {
    loading.value = true
    try {
      const response = await api.post(`/api/v1/workflows/${workflowId}/versions/${version}/rollback`, { comment })
      const index = workflows.value.findIndex(w => w.id === workflowId)
      if (index !== -1) {
        workflows.value[index] = response.data
      }
      if (currentWorkflow.value?.id === workflowId) {
        currentWorkflow.value = response.data
      }
      return response.data
    } finally {
      loading.value = false
    }
  }

  return {
    workflows,
    currentWorkflow,
    loading,
    fetchWorkflows,
    createWorkflow,
    fetchWorkflow,
    updateWorkflow,
    deleteWorkflow,
    setCurrentWorkflow,
    fetchTemplates,
    fetchTemplate,
    createWorkflowFromTemplate,
    exportWorkflow,
    importWorkflow,
    fetchWorkflowVersions,
    fetchWorkflowVersion,
    rollbackWorkflowVersion
  }
})
