/**
 * 支付网关要求以 POST 表单提交签名参数，不能用普通的路由跳转替代。
 */
function resolveTarget(target, targetWindow) {
  if (!targetWindow) return target
  if (!targetWindow.name) {
    targetWindow.name = `runforge_pay_${Date.now()}_${Math.random().toString(36).slice(2)}`
  }
  return targetWindow.name
}

export function submitPayment(pay, { target = '_blank', targetWindow = null } = {}) {
  const payUrl = pay?.payUrl
  const payData = pay?.payData
  if (!payUrl || !payData || typeof payData !== 'object') return false

  const form = document.createElement('form')
  form.method = 'POST'
  form.action = payUrl
  form.target = resolveTarget(target, targetWindow)
  form.style.display = 'none'

  Object.entries(payData).forEach(([key, value]) => {
    const input = document.createElement('input')
    input.type = 'hidden'
    input.name = key
    input.value = String(value)
    form.appendChild(input)
  })

  document.body.appendChild(form)
  form.submit()
  document.body.removeChild(form)
  return true
}
