<script setup lang="ts">
import { getPointsCoupons, getProductCoupons } from '../../../core/libs/requests'
import { Coupon } from '../../../core/libs/models'
import { useUserStore } from '../../../store'
import { storeToRefs } from 'pinia'
import CouponCard from './coupon-card.vue'

const props = withDefaults(
  defineProps<{
    type: 'points' | 'product'
    products?: any[]
    businessId?: number
    show?: boolean
  }>(),
  { show: false },
)
const modelValue = defineModel({ default: () => [], type: Array as PropType<Coupon[]> })
const emits = defineEmits<{ close: [] }>()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
// const show = ref(false)
const tab = ref(0)
const request = ref()
const { data: coupons, run: setCoupons } = useRequest(() => request.value(), { initialData: [] })
const handleSelect = (coupon: Coupon) => {
  // if (modelValue.value.map(({ id }) => id).includes(coupon.id)) {
  //   modelValue.value = modelValue.value.filter(({ id }) => id !== coupon.id)
  // } else {
  //   modelValue.value = [...modelValue.value, coupon]
  // }
  modelValue.value = [coupon]
  emits('close')
}
watch(
  () => props.show,
  async (val) => {
    console.log(val)

    if (val) {
      console.log(111111)

      await setCoupons()
    }
  },
)
onMounted(async () => {
  if (props.type === 'product') {
    request.value = () =>
      getProductCoupons({
        userId: userInfo.value.userId,
        productIds: props.products.map((it) => it.productId).join(','),
        isUse: 0,
      })
  }
  if (props.type === 'points') {
    request.value = () =>
      getPointsCoupons({
        userId: userInfo.value.userId,
        //   productIds: props.products.map((it) => it.productId).join(','),
        businessId: props.businessId,
        isUse: 0,
      })
  }
  //   await setCoupons()
})
</script>
<template>
  <wd-action-sheet title="优惠券" :modelValue="show" @close="emits('close')">
    <view class="">
      <wd-tabs v-model="tab">
        <wd-tab title="可用优惠券"></wd-tab>
        <!-- <wd-tab title="不可用优惠券"></wd-tab> -->
      </wd-tabs>
      <div class="h-100 overflow-y-scroll">
        <div class="bg-[#f6f6f6] py-3.5 flex flex-col gap-4 min-h-full">
          <template v-for="(it, i) in coupons" :key="i">
            <CouponCard
              :options="{ couponType: 2, ...it }"
              canSelect
              :selected="modelValue?.map(({ id }) => id).includes(it.id)"
              @select="handleSelect"
            ></CouponCard>
          </template>
        </div>
      </div>
      <!-- <wd-button block :round="false">确认</wd-button> -->
    </view>
  </wd-action-sheet>
</template>
