<template>
  <view>
    <view class="u-flex u-row-between u-m-b-24" style="gap: 40rpx">
      <view
        class="choose-coupon u-flex-1 u-flex u-row-between"
        @click="showCoupon(item, index)"
      >
        <template v-if="couponName">
          <text>{{ couponName }}</text>
          <view class="u-flex" @click.stop="modelValue = ''">
            <up-icon name="close" size="14"></up-icon>
          </view>
        </template>

        <template v-else>
          <text class="color-999">选择赠送券</text>
          <up-icon name="arrow-down" size="14"></up-icon>
        </template>
      </view>
    </view>
    <chooseCoupon
      v-model="chooseCouponData.couponId"
      v-model:show="chooseCouponData.show"
      @confirm="confirmCoupon"
      :list="couponList"
    ></chooseCoupon>
  </view>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from "vue";
import chooseCoupon from "./choose-coupon.vue";
import { chatCoupon } from "@/http/api/market/chatCoupon.js";

const chooseCouponData = reactive({
  couponId: "",
  show: false,
  index: -1,
  item: null,
});
const modelValue = defineModel({
  default: "",
});

const couponName = computed(() => {
  if (modelValue.value) {
    const item = couponList.value.find((item) => item.id === modelValue.value);
    return item?.title || "";
  }
  return "";
});
const couponList = ref([]);
function showCoupon(item, index) {
  chooseCouponData.couponId = modelValue.value;
  chooseCouponData.show = true;
}
function confirmCoupon(e) {
    modelValue.value=e.id
}
function removeCoupon(index) {
  modelValue.value.splice(index, 1);
}
onMounted(() => {
  chatCoupon({ size: 999 }).then((res) => {
    couponList.value = res.records;
  });
});
</script>
<style lang="scss" scoped>
.choose-coupon {
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  border: 1px solid #d9d9d9;
}
</style>
