<template>
	<view class="container">
		<u-form ref="formRef" label-position="top" labelWidth="200" :model="form" :rules="rules">
			<view class="u-form-card">
				<u-form-item label="赠券门槛" prop="fullAmount">
					<view class="center">
						<view class="ipt">
							<u-input placeholder="请输入内容" v-model="form.fullAmount" input-align="center" :maxlength="5" @change="fullAmountInput">
								<template v-slot:prefix>满</template>
								<template v-slot:suffix>可用</template>
							</u-input>
						</view>
						<div class="tips-icon" @click="showTipsHandle">
							<u-icon name="question-circle-fill" size="22" color="#999"></u-icon>
						</div>
					</view>
				</u-form-item>
				<u-form-item label="优惠券" prop="couponGiftList">
					<my-select-coupon v-model="couponGiftList" @load="couponLoad"></my-select-coupon>
				</u-form-item>
			</view>
			<view class="u-form-card">
				<u-form-item label="可使用类型" prop="useType">
					<my-dine-types v-model="form.useType"></my-dine-types>
				</u-form-item>
			</view>
			<view class="u-form-card">
				<u-form-item label="总发放数量" prop="giveNum">
					<view class="column">
						<view class="center">
							<u-switch v-model="infiniteGiveNum" @change="infiniteGiveNumChange"></u-switch>
							<text class="tips">关闭则为无限制</text>
						</view>
						<view class="center" v-if="infiniteGiveNum">
							<view class="ipt">
								<u-input placeholder="请输入总发放数量" :maxlength="5" v-model="form.giveNum" @change="giveNumInput">
									<template v-slot:suffix>张</template>
								</u-input>
							</view>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="每次赠送" prop="couponGiveNum">
					<u-input placeholder="赠送数量" :maxlength="5" v-model="couponGiveNum" @change="couponGiveNumInput">
						<template v-slot:suffix>张</template>
					</u-input>
				</u-form-item>
				<u-form-item label="每人限量" prop="getLimit">
					<view class="column">
						<view class="center">
							<u-switch v-model="infiniteGetLimit" @change="infiniteGetLimitChange"></u-switch>
							<text class="tips">关闭则为无限制</text>
						</view>
						<view class="center" v-if="infiniteGetLimit">
							<view class="ipt">
								<u-input placeholder="请输入每人限量" :maxlength="5" v-model="form.getLimit" @change="getLimitInput">
									<template v-slot:suffix>张</template>
								</u-input>
							</view>
						</view>
					</view>
				</u-form-item>
			</view>
		</u-form>
		<my-footer-btn @confirm="submitHandle" v-if="(shopInfo.isHeadShop && shopInfo.shopType != 'only') || !form.syncId"></my-footer-btn>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { filterNumberInput } from '@/utils/index.js';
import { couponPost, updateConsumerCouponById, getConsumerCouponById } from '@/http/api/market/index.js';

const shopInfo = ref({});

const formRef = ref(null);
const couponGiftList = ref('');
const form = ref({
	id: '',
	shopId: '',
	couponType: 1, // 1-满减券，2-商品兑换券，3-折扣券，4-第二件半价券，5-消费送券，6-买一送一券，7-固定价格券，8-免配送费券
	fullAmount: '', // 使用门槛：满多少金额
	couponGiftList: [], // 优惠券，目前单选
	useType: ['dine-in'], // 堂食 dine-in 外带 take-out 外卖 take-away 配送 post
	giveNum: '', // 总发放数量，-10086为不限量
	getLimit: '' // 每人领取限量，-10086为不限量
});

const couponList = ref([]);

// 成功加载优惠券
function couponLoad(res) {
	couponList.value = res;
}

function showTipsHandle() {
	uni.showModal({
		title: '注意',
		content: '每单消费满此金额后赠送',
		showCancel: false
	});
}

// 开始提交
function submitHandle() {
	console.log('前置form', form.value);
	formRef.value
		.validate()
		.then(async (res) => {
			try {
				form.value.shopId = shopInfo.value.id;
				form.value.useType = JSON.stringify(form.value.useType);
				let item = couponList.value.find((item) => item.id == couponGiftList.value);
				form.value.couponGiftList = [
					{
						couponName: item.title,
						couponId: item.id,
						num: couponGiveNum.value
					}
				];
				console.log('终极form', form.value);
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				if (form.value.id) {
					await updateConsumerCouponById(form.value);
				} else {
					await couponPost(form.value);
				}
				uni.showToast({
					title: '保存成功',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1000);
			} catch (error) {
				console.log(error);
			}
			setTimeout(() => {
				uni.hideLoading();
			}, 500);
		})
		.catch((res) => {});
}

const rules = ref({
	fullAmount: [
		{
			required: true,
			trigger: ['blur'],
			message: '请输入使用门槛',
			validator: (rule, value, callback) => {
				if (form.value.fullAmount < 0 || form.value.fullAmount === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	couponGiftList: [
		{
			required: true,
			trigger: ['change'],
			message: '请选择优惠券',
			validator: (rule, value, callback) => {
				if (couponGiftList.value === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	useType: [
		{
			required: true,
			trigger: ['change'],
			message: '请选择可使用类型',
			validator: (rule, value, callback) => {
				if (form.value.useType.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	giveNum: [
		{
			trigger: ['blur'],
			message: '请输入总发放数量',
			validator: (rule, value, callback) => {
				if (infiniteGiveNum.value && form.value.giveNum === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	couponGiveNum: [
		{
			trigger: ['blur'],
			message: '请输入赠送数量',
			validator: (rule, value, callback) => {
				if (couponGiveNum.value.giveNum === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	getLimit: [
		{
			trigger: ['blur'],
			message: '请输入每人限量',
			validator: (rule, value, callback) => {
				if (infiniteGetLimit.value && form.value.getLimit === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	]
});

const inputTime = 50;
function fullAmountInput(e) {
	setTimeout(() => {
		form.value.fullAmount = filterNumberInput(e);
	}, inputTime);
}

const infiniteNum = -10086; // 无限
const infiniteGiveNum = ref(true);
function infiniteGiveNumChange(e) {
	if (!e) {
		form.value.giveNum = infiniteNum;
	} else {
		form.value.giveNum = '';
	}
}

function giveNumInput(e) {
	setTimeout(() => {
		form.value.giveNum = filterNumberInput(e, 1);
	}, inputTime);
}

// 优惠券赠送数量
const couponGiveNum = ref(1);
function couponGiveNumInput(e) {
	setTimeout(() => {
		couponGiveNum.value = filterNumberInput(e, 1);
	}, inputTime);
}

const infiniteGetLimit = ref(true);
function getLimitInput(e) {
	setTimeout(() => {
		form.value.getLimit = filterNumberInput(e);
	}, inputTime);
}
function infiniteGetLimitChange(e) {
	if (!e) {
		form.value.getLimit = infiniteNum;
	} else {
		form.value.getLimit = '';
	}
}

const id = ref('');
async function getConsumerCouponByIdAjax() {
	try {
		uni.showLoading({
			title: '加载中...',
			mask: true
		});
		const res = await getConsumerCouponById({ id: id.value });
		couponGiftList.value = res.couponGiftList[0].couponId;
		res.useType = JSON.parse(res.useType);
		if (res.giveNum == infiniteNum) {
			infiniteGiveNum.value = false;
		}

		if (res.getLimit == infiniteNum) {
			infiniteGetLimit.value = false;
		}

		form.value = res;
	} catch (error) {
		console.log(error);
	}
	setTimeout(() => {
		uni.hideLoading();
	}, 500);
}

onLoad((options) => {
	shopInfo.value = uni.getStorageSync('shopInfo');
	if (options.id) {
		id.value = options.id;
		uni.setNavigationBarTitle({
			title: '编辑消费赠券'
		});
		getConsumerCouponByIdAjax();
	}
});
</script>

<style>
page {
	background-color: #f7f7f7;
}
</style>
<style scoped lang="scss">
.container {
	padding: 28upx;
}
.center {
	display: flex;
	gap: 28upx;
	align-items: center;
	.ipt {
		flex: 1;
	}
}
.tips {
	font-size: 28upx;
	color: #999;
}
.column {
	display: flex;
	flex-direction: column;
	gap: 20upx;
}
</style>
