import { ref } from 'vue'
import { useMessage } from 'naive-ui'
import {
  listWorkflowVersions,
  getWorkflowVersionContent,
  rollbackWorkflowVersion,
  updateWorkflowVersionMessage
} from '../api/workflow'

/**
 * 工作流版本历史管理 composable
 * 抽取自 WorkflowEditor.vue，承担版本列表加载、回滚、备注编辑等逻辑
 *
 * @param {() => void} onRollbackApply 回滚成功后的画布刷新回调
 */
export function useVersionHistory(onRollbackApply) {
  const message = useMessage()

  const showVersionPanel = ref(false)
  const versions = ref([])
  const versionsLoading = ref(false)
  const selectedVersion = ref(null)
  const versionContent = ref('')
  const editingMessage = ref(false)
  const editingMessageText = ref('')

  async function loadVersions(nameOrId) {
    if (!nameOrId) return
    versionsLoading.value = true
    try {
      const res = await listWorkflowVersions(nameOrId)
      versions.value = (res.data || []).reverse()
    } catch {
      message.error('加载版本历史失败')
    } finally {
      versionsLoading.value = false
    }
  }

  async function toggleVersionPanel(nameOrId) {
    showVersionPanel.value = !showVersionPanel.value
    if (showVersionPanel.value) {
      await loadVersions(nameOrId)
    } else {
      selectedVersion.value = null
      versionContent.value = ''
    }
  }

  async function handleVersionSelect(nameOrId, v) {
    selectedVersion.value = v
    try {
      const res = await getWorkflowVersionContent(nameOrId, v.number)
      versionContent.value = res.data || ''
    } catch {
      versionContent.value = '加载失败'
    }
  }

  async function handleRollback(nameOrId, v, applyGraph) {
    try {
      const res = await rollbackWorkflowVersion(nameOrId, v.number)
      const wf = res.data
      if (wf && typeof applyGraph === 'function') {
        await applyGraph(wf)
      }
      await loadVersions(nameOrId)
      message.success('已回滚到 v' + v.number)
    } catch {
      message.error('回滚失败')
    }
  }

  function startEditMessage(v) {
    editingMessage.value = v.number
    editingMessageText.value = v.message || ''
  }

  async function saveMessage(nameOrId, v) {
    try {
      await updateWorkflowVersionMessage(nameOrId, v.number, editingMessageText.value)
      v.message = editingMessageText.value
      editingMessage.value = false
    } catch {
      message.error('保存备注失败')
    }
  }

  function cancelEditMessage() {
    editingMessage.value = false
  }

  function formatTime(dt) {
    if (!dt) return ''
    const d = new Date(dt)
    const pad = n => String(n).padStart(2, '0')
    return `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
  }

  function formatVersionJson(str) {
    try {
      const obj = JSON.parse(str)
      return JSON.stringify(obj, null, 2)
    } catch {
      return str
    }
  }

  return {
    showVersionPanel,
    versions,
    versionsLoading,
    selectedVersion,
    versionContent,
    editingMessage,
    editingMessageText,
    loadVersions,
    toggleVersionPanel,
    handleVersionSelect,
    handleRollback,
    startEditMessage,
    saveMessage,
    cancelEditMessage,
    formatTime,
    formatVersionJson
  }
}
