<template>
  <view>
    <view
      class="u-flex u-row-between u-m-b-24"
      style="gap: 40rpx"
      v-for="(item, index) in modelValue"
      :key="index"
    >
      <view
        class="choose-coupon u-flex-1 u-flex u-row-between"
        @click="showCoupon(item, index)"
      >
        <template v-if="item.coupon.title">
          <text>{{ item.coupon.title }}</text>
          <view class="u-flex" @click.stop="clearCoupon(index)">
            <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 class="u-flex-1 u-flex">
        <view class="u-flex-1 input-number-box u-flex">
          <input
            class="u-flex-1 input"
            type="number"
            v-model="item.num"
            placeholder=""
            placeholder-class="color-999 u-font-28"
          />
          <text class="no-wrap color-999 number">数量</text>
        </view>
        <view class="u-m-l-20">
          <up-icon
            name="minus-circle-fill"
            color="#EB4F4F"
            size="18"
            @click="removeCoupon(index)"
          ></up-icon>
        </view>
      </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 } from "vue";
import chooseCoupon from "@/pageMarket/components/choose-coupon.vue";
import { couponPage } from "@/http/api/market/index.js";

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

function clearCoupon(index) {
  modelValue.value[index].coupon = { id: null };
}
const couponList = ref([]);
function showCoupon(item, index) {
  chooseCouponData.couponId = item ? item.id : "";
  chooseCouponData.show = true;
  chooseCouponData.index = index;
  chooseCouponData.item = item;
}
function confirmCoupon(e) {
  modelValue.value[chooseCouponData.index].coupon = e
}
function removeCoupon(index) {
  modelValue.value.splice(index, 1);
}
onMounted(() => {
  couponPage({ 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;
}
.input-number-box {
  border-radius: 8rpx;
  border: 1px solid #d9d9d9;
  .input {
    padding: 10rpx 20rpx;
  }
}
.number {
  background-color: #f7f7fa;
  padding: 10rpx 20rpx;
}
</style>
