<script setup lang="ts">
import useDialog from "~/composables/useDialog";
import { getCouponTime } from '~/utils/util'
import {toRefs, reactive} from "vue";
import {couponReceiveApi} from "~/server/merchantApi";
import feedback from '~/utils/feedback'

const props = defineProps({
  //列表数据
  productId: {
    type: Number,
    default: 0,
  },
})
const { productId } = toRefs(props)

const { bool: dialogVisibleCoupon, DialogOpen, DialogClose } = useDialog()
//打开
defineExpose({ DialogOpen })

//关闭
const nuxtApp = useNuxtApp()
const handleCloseCoupon = ()=>{
  DialogClose()
  nuxtApp.$onHandlerCloseCoupon()
}

/**
 * 我的优惠券列表
 */
import { PageQuery } from '~/types/global'
import {couponListApi} from "~/server/goodsApi";
const where = reactive<PageQuery>({
  page: 1,
  limit: 50,
  productId: productId?.value,
  category: 0
})
const { data: coupon, pending: listLoading } = await useAsyncData(async () => couponListApi(where), {
  default: () => ({
    list: [],
    total: 0,
  }),
})

//领取优惠券
const handleReceiveCoupon = async (item: any) => {
  if (item.isUse) return
  listLoading.value = true
  try {
    await couponReceiveApi(item.id)
    feedback.msgSuccess('领取成功')
    item.isUse = !item.isUse
    listLoading.value = false
  } catch (e) {
    listLoading.value = false
  }
}
</script>

<template>
  <el-drawer
      :append-to-body="false"
      modal-class="receiveCouponDrawer"
      v-model="dialogVisibleCoupon"
      direction="rtl"
      size="280px"
      :modal="false"
      :before-close="handleCloseCoupon"
  >

    <template #header>
      <h4>优惠券</h4>
    </template>
    <template #default>
     <div v-loading="listLoading" v-if="dialogVisibleCoupon" class="receiveCoupon mt-15px">
       <div v-for="(item,index) in coupon.list"
            @click="handleReceiveCoupon(item)" :key='index' class="receiveCouponList acea-row cursors mb-20px">
         <div class="w-200px text-#fff pl-20px pt-10px">
           <div class="text-12px mb-10px"><span class="oppoSans-M">￥</span><span class="text-30px mr-10px lh-30px dinProSemiBold">{{item.money}}</span><span class="lh-12px">满 {{item.minPrice}} 可用</span></div>
           <div class="text-12px mb-9px line2 w-177px">{{item.name}}</div>
           <div v-if="item.isFixedTime" class="text-12px">{{ getCouponTime(item.useStartTimeStr, item.useEndTimeStr) }}</div>
           <div v-else class="text-12px">{{ '领取后' + item.day + '天内可用' }}</div>
         </div>
         <div class="w-50px flex-center">
           <div class="w-20px h-80px bg-#fff b-rd-12px text-center font-color text-12px flex-center verticalClass">{{item.isUse?'已领取':'立即领取'}}</div>
         </div>
       </div>
     </div>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss">

:deep(.el-divider--horizontal){
  margin: 20px 0 30px 0 !important;
}
:deep(.el-divider__text){
  --el-bg-color:#F5F5F5;
}
.receiveCouponList{
  width: 250px;
  height: 116px;
  background-image: url("@/assets/images/yhq.png");
}
</style>