import { defineStore } from 'pinia'
import {
  getOrderDetailApi,
  getOrderListApi,
  submitOrderApi,
  submitOrderTelApi,
  getOrderViewListApi2,
  getOrderViewDetailApi2,
} from '@/service/order'
import { until } from '@vueuse/core'
import type { ListType } from '@/types/list'

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
      ordersphone?: string
      filesid: string
    }) => {
      const { data: order, loading } = useRequest(() => submitOrderApi(params), {
        immediate: true,
      })

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

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

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

    // 订单_产品_用户_我的优惠劵_列表(视图)
    const getOrderViewList = async (params, page: Partial<ListType>) => {
      const { data: orderViewList, loading } = useRequest(
        () => getOrderViewListApi2(params, page),
        {
          immediate: true,
        },
      )

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

    // 订单_产品_用户_我的优惠劵_详情(视图)
    const getOrderViewDetail = async (params) => {
      const { data: orderViewDetail, loading } = useRequest(() => getOrderViewDetailApi2(params), {
        immediate: true,
      })

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

    return {
      getOrderList,
      getOrderDetail,
      submitOrder,
      submitOrderTel,
      getOrderViewList,
      getOrderViewDetail,
    }
  },
  {
    persist: true,
  },
)
