import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { approveTask, rejectTask, returnTask, batchApproveTask, batchRejectTask, listNextNodes } from '@/api/flow/task'
import { getInstanceAttachments } from '@/api/flow/instance'
import { useFileUpload } from './useFileUpload'
import type { FlowTask, ApprovalAction, NextNode } from '@/types/flow'

export interface UseApprovalOptions {
  onSuccess?: () => void
}

export function useApproval(options?: UseApprovalOptions) {
  const visible = ref(false)
  const form = reactive<ApprovalAction>({
    action: 'pass',
    comment: '',
  })
  const submitting = ref(false)
  const nextNodes = ref<NextNode[]>([])
  const currentTask = ref<FlowTask | null>(null)
  const currentTasks = ref<FlowTask[]>([])
  const batchMode = ref(false)

  const file = useFileUpload()

  const actionText = computed(() => {
    const map: Record<string, string> = { pass: '通过', reject: '拒绝', rollback: '回退' }
    return map[form.action] || '审批'
  })

  const title = computed(() => {
    if (batchMode.value) return `批量${actionText.value}`
    return `${actionText.value}审批`
  })

  const alertTitle = computed(() => {
    if (batchMode.value) {
      return `将对 ${currentTasks.value.length} 个待办任务执行「${actionText.value}」操作`
    }
    if (currentTask.value) {
      return `流程：${currentTask.value.definitionName} · 节点：${currentTask.value.nodeName}`
    }
    return ''
  })

  function buildActionData(): ApprovalAction {
    const data: ApprovalAction = {
      action: form.action,
      comment: form.comment,
    }
    if (form.action === 'pass' && form.targetNodeId) {
      data.targetNodeId = form.targetNodeId
    }
    if (file.attachmentList.value.length > 0) {
      data.attachmentUrls = JSON.stringify(
        file.attachmentList.value.map((f: any) => f.response || f.url).filter(Boolean)
      )
    }
    return data
  }

  async function loadNextNodes() {
    const task = batchMode.value ? currentTasks.value[0] : currentTask.value
    if (!task) {
      nextNodes.value = []
      return
    }
    try {
      nextNodes.value = await listNextNodes(task.id)
    } catch {
      nextNodes.value = []
    }
  }

  async function loadPreviousAttachments() {
    if (batchMode.value || !currentTask.value?.instanceId) {
      await file.loadPreviousAttachments()
      return
    }
    const instanceId = currentTask.value.instanceId
    await file.loadPreviousAttachments(() => getInstanceAttachments(instanceId))
  }

  async function open(tasks: FlowTask | FlowTask[], action: 'pass' | 'reject' | 'rollback') {
    reset()
    if (Array.isArray(tasks)) {
      currentTasks.value = tasks
      batchMode.value = true
    } else {
      currentTask.value = tasks
      batchMode.value = false
    }
    form.action = action
    if (action === 'pass') {
      await loadNextNodes()
    }
    await loadPreviousAttachments()
    visible.value = true
  }

  async function submit() {
    if (batchMode.value) {
      await submitBatch()
      return
    }
    await submitSingle()
  }

  async function submitSingle() {
    const task = currentTask.value
    if (!task) return
    if (form.action === 'pass' && nextNodes.value.length > 0 && !form.targetNodeId) {
      ElMessage.warning('当前节点存在多个下游分支，请选择一个目标节点')
      return
    }
    submitting.value = true
    try {
      const data = buildActionData()
      switch (form.action) {
        case 'pass':
          await approveTask(task.id, data)
          break
        case 'reject':
          await rejectTask(task.id, data)
          break
        case 'rollback':
          await returnTask(task.id, data)
          break
      }
      ElMessage.success('审批成功')
      visible.value = false
      options?.onSuccess?.()
    } finally {
      submitting.value = false
    }
  }

  async function submitBatch() {
    const taskIds = currentTasks.value.map((t) => t.id)
    if (taskIds.length === 0) return
    submitting.value = true
    try {
      const data = buildActionData()
      if (form.action === 'pass') {
        await batchApproveTask(taskIds, data)
      } else if (form.action === 'reject') {
        await batchRejectTask(taskIds, data)
      }
      ElMessage.success('批量审批成功')
      visible.value = false
      options?.onSuccess?.()
    } finally {
      submitting.value = false
    }
  }

  function reset() {
    form.action = 'pass'
    form.comment = ''
    form.targetNodeId = undefined
    submitting.value = false
    nextNodes.value = []
    currentTask.value = null
    currentTasks.value = []
    batchMode.value = false
    file.resetFileUpload()
  }

  return {
    visible,
    form,
    submitting,
    nextNodes,
    currentTask,
    currentTasks,
    batchMode,
    actionText,
    title,
    alertTitle,
    buildActionData,
    open,
    submit,
    reset,
    ...file,
  }
}
