import { defineStore } from 'pinia'
import { getOrderDetailApi, getOrderListApi, submitOrderApi } from '@/service/order'
import { until } from '@vueuse/core'

export const useOrderStore = defineStore(
  'order',
  () => {
    // 获取订单列表
    const getOrderList = async (ordersuserid: string) => {
      const { data: orderList, loading } = useRequest(
        () => getOrderListApi({ ordersuserid }, { pageindex: 1, rows: 999 }),
        {
          immediate: true,
        },
      )

      await until(loading).toBe(false)
      return orderList.value.Data
    }

    // 获取订单详情
    const getOrderDetail = async (ordersid: string) => {
      const { data: orderDetail, loading } = useRequest(() => getOrderDetailApi(ordersid), {
        immediate: true,
      })

      await until(loading).toBe(false)
      return orderDetail.value
    }

    // 使用优惠劵提交订单
    const submitOrder = async (params: {
      ordersproductid: string
      orderscouponid: string
      ordersproductsn: string
      ordersuserid1: string
    }) => {
      const { data: order, loading } = useRequest(() => submitOrderApi(params), {
        immediate: true,
      })

      await until(loading).toBe(false)
      return order.value
    }

    return {
      getOrderList,
      getOrderDetail,
      submitOrder,
    }
  },
  {
    persist: true,
  },
)
