import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { addSignTask, getTransferableUsers } from '@/api/flow/task'
import type { User } from '@/types/system'

export function useAddSign() {
  const visible = ref(false)
  const userId = ref<number | undefined>()
  const loading = ref(false)
  const userList = ref<User[]>([])
  let currentTaskId = 0

  async function open(taskId: number) {
    currentTaskId = taskId
    userId.value = undefined
    loading.value = false
    try {
      userList.value = await getTransferableUsers(taskId)
    } catch {
      userList.value = []
    }
    visible.value = true
  }

  async function submit(onSuccess?: () => void) {
    if (!userId.value) {
      ElMessage.warning('请选择加签人')
      return
    }
    loading.value = true
    try {
      await addSignTask(currentTaskId, userId.value)
      ElMessage.success('加签成功')
      visible.value = false
      userId.value = undefined
      onSuccess?.()
    } finally {
      loading.value = false
    }
  }

  function reset() {
    visible.value = false
    userId.value = undefined
    loading.value = false
    userList.value = []
    currentTaskId = 0
  }

  return { visible, userId, loading, userList, open, submit, reset }
}
