import { defineStore } from 'pinia'
import { getCouponListApi, receiveCouponApi, getCoupon2idApi } from '@/service/coupon1'
import { until } from '@vueuse/core'

export const useCouponStore = defineStore(
  'coupon',
  () => {
    // 获取优惠券列表
    const getCouponList = async (couponproductids: string) => {
      const { data: couponList, loading } = useRequest(
        () => getCouponListApi({ couponproductids }, { pageindex: 1, rows: 999 }),
        {
          immediate: true,
        },
      )

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

    // 领取优惠券
    const receiveCoupon = async (couponid: string) => {
      const { data: couponList, loading } = useRequest(() => receiveCouponApi(couponid), {
        immediate: true,
      })

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

    // 获取该用户下，已领取的优惠劵id，用于判断是否可以领取
    const getCoupon2id = async (params) => {
      const { data: couponList, loading } = useRequest(() => getCoupon2idApi(params), {
        immediate: true,
      })

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

    return {
      getCouponList,
      receiveCoupon,
      getCoupon2id,
    }
  },
  {
    persist: true,
  },
)
