import { defineStore } from 'pinia'
import {
  getCouponListApi,
  receiveCouponApi,
  getCoupon2idApi,
  getCoupon2ListApi,
} from '@/service/coupon1'
import { getCoupon2ViewmListApi } from '@/service/coupon2'
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, coupon2phone, coupon2productids }) => {
      const { data: couponList, loading } = useRequest(
        () => receiveCouponApi({ couponid, coupon2phone, coupon2productids }),
        {
          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
    }

    // 通过优惠券id获取产品信息（视图）
    const getCoupon2ViewmList = async (params: { coupon2code: string }) => {
      const { data: couponList, loading } = useRequest(
        () => getCoupon2ViewmListApi(params, { pageindex: 1, rows: 999 }),
        {
          immediate: true,
        },
      )

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

    // 获取已关联到当前用户的优惠券列表
    const getCoupon2List = async (params: { coupon2userid: string }) => {
      const { data: couponList, loading } = useRequest(
        () => getCoupon2ListApi(params, { pageindex: 1, rows: 999 }),
        {
          immediate: true,
        },
      )

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

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