<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.title">
					<text>{{ item.title }}</text>
					<view class="u-flex" @click.stop="item.title = ''">
						<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 choose-coupon u-flex">
					<input class="u-flex-1" placeholder="" type="number" v-model="item.num" placeholder-class="color-999 u-font-28" @input="numInput($event, item)" />
					<text class="no-wrap color-999">{{ tips }}</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 './choose-coupon.vue';
import { couponPage } from '@/http/api/market/index.js';
import { filterNumberInput } from '@/utils/index.js';

const props = defineProps({
	tips: {
		type: String,
		default: '张/1个码'
	}
});

const chooseCouponData = reactive({
	couponId: '',
	show: false,
	index: -1,
	item: null
});
const modelValue = defineModel({
	type: Array,
	default: () => []
});
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].id = e.id;
	modelValue.value[chooseCouponData.index].title = e.title;
}
function removeCoupon(index) {
	modelValue.value.splice(index, 1);
}

function numInput(e, item) {
	console.log('e', e);
	console.log('item', item);
	setTimeout(() => {
		item.num = filterNumberInput(e.detail.value, 1);
	}, 50);
}

onMounted(() => {
	console.log('coupon-list', modelValue.value);
	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;
}
</style>
