import { payOrder, cancelPay, confirmReceive } from '@/api/order'
import { useActionGuard } from '@/utils/actionGuard'

const payModalGuard = useActionGuard()
const confirmReceiveGuard = useActionGuard()
import { ORDER_ACTION } from '@/constants/order'
import { goGoodsDetail } from '@/utils/goodsDetail'
import { goReviewEdit, goReviewView, goReviewList, goAftersaleSubmit } from '@/utils/orderNav'
import { PAGE_ORDER_REVIEW_LIST } from '@/utils/pageRoute'

/**
 * 执行订单操作按钮
 * @param {string} code 操作枚举
 * @param {object} ctx { orderId, firstItem, items, onRefresh }
 */
export function runOrderAction(code, ctx = {}) {
  const orderId = ctx.orderId
  switch (code) {
    case ORDER_ACTION.PAY:
      return ctx.onPay?.(orderId) ?? Promise.resolve()
    case ORDER_ACTION.CONFIRM_RECEIVE:
      return doConfirmReceive(orderId, ctx.onRefresh)
    case ORDER_ACTION.REVIEW:
      goReviewEdit(orderId, ctx.orderItemId)
      return Promise.resolve()
    case ORDER_ACTION.VIEW_REVIEW:
      if (ctx.orderItemId) {
        goReviewView(orderId, ctx.orderItemId)
      } else {
        uni.navigateTo({ url: `${PAGE_ORDER_REVIEW_LIST}?tab=DONE&orderId=${orderId}` })
      }
      return Promise.resolve()
    case ORDER_ACTION.AFTERSALE:
      return openAftersalePicker(ctx)
    case ORDER_ACTION.BUY_AGAIN:
      return doBuyAgain(ctx)
    default:
      return Promise.resolve()
  }
}

function doBuyAgain(ctx) {
  const goodsId =
    ctx.firstItem?.goodsId ||
    (ctx.items && ctx.items[0] && ctx.items[0].goodsId)
  if (!goodsId) {
    uni.showToast({ title: '商品信息缺失', icon: 'none' })
    return Promise.resolve()
  }
  goGoodsDetail(goodsId)
  return Promise.resolve()
}

function openAftersalePicker(ctx) {
  if (!ctx.orderId) {
    uni.showToast({ title: '订单信息缺失', icon: 'none' })
    return Promise.resolve()
  }
  goAftersaleSubmit(ctx.orderId)
  return Promise.resolve()
}

function doConfirmReceive(orderId, onRefresh) {
  return new Promise((resolve) => {
    uni.showModal({
      title: '确认收货',
      content: '请确认您已收到商品',
      success: (res) => {
        if (!res.confirm) {
          resolve()
          return
        }
        confirmReceiveGuard.run(async () => {
          try {
            await confirmReceive(orderId)
            uni.showToast({ title: '已确认收货', icon: 'success' })
            if (typeof onRefresh === 'function') {
              await onRefresh()
            }
            uni.showModal({
              title: '提示',
              content: '交易成功，是否去评价？',
              confirmText: '去评价',
              cancelText: '稍后',
              success: (r) => {
                if (r.confirm) {
                  goReviewList('PENDING')
                }
              }
            })
          } catch (e) {
            // request 已 Toast
          }
          resolve()
        })
      }
    })
  })
}

/** Mock 支付弹窗流程（与确认订单一致） */
export function openPayModal(orderId, orderNo, payAmountText) {
  return new Promise((resolve) => {
    uni.showModal({
      title: '微信支付',
      content: `订单号：${orderNo || '—'}\n应付金额：¥${payAmountText || '—'}`,
      confirmText: '确认支付',
      cancelText: '取消支付',
      success: (res) => {
        payModalGuard.run(async () => {
          try {
            if (res.confirm) {
              await payOrder(orderId)
              uni.showToast({ title: '支付成功', icon: 'success' })
              resolve({ status: 'success' })
              return
            }
            await cancelPay(orderId)
            uni.showToast({ title: '订单已关闭', icon: 'none' })
            resolve({ status: 'closed' })
          } catch (e) {
            resolve({ status: 'error' })
          }
        })
      },
      fail: () => resolve({ status: 'cancel' })
    })
  })
}
