<template>
	<div>
		<el-dialog v-model="dialogVisible" :title="titleOptions.title" width="80%" @closed="closedReset">
			<el-form ref="formRef" :model="form" :rules="formRules" label-width="100px" class="dialog-form">
				<el-form-item label="赠券门槛" prop="fullAmount">
					<div class="center">
						<el-input v-model="form.fullAmount" placeholder="请输入赠券门槛" style="width: 240px"
							input-style="text-align: center;" @input="(e) => (form.fullAmount = filterNumberInput(e))">
							<template #prepend>满</template>
							<template #append>元</template>
						</el-input>
						<el-tooltip class="box-item" effect="dark" content="每单消费满此金额后赠送券 " placement="top-start">
							<el-icon size="18">
								<QuestionFilled />
							</el-icon>
						</el-tooltip>
					</div>
				</el-form-item>
				<el-form-item label="优惠券" prop="coupon">
					<div class="center">
						<el-select v-model="couponGiftList" placeholder="请选择优惠券" style="width: 300px">
							<el-option :label="item.title" :value="item.id" v-for="item in couponList" :key="item.id" />
						</el-select>
					</div>
				</el-form-item>
				<div class="title">指定设置</div>
				<el-form-item label="可使用类型" prop="useType">
					<el-checkbox-group v-model="form.useType">
						<el-checkbox value="dine-in" label="堂食" />
						<el-checkbox value="take-out" label="外带" />
						<el-checkbox value="take-away" label="外卖" />
						<el-checkbox value="post" label="配送" />
					</el-checkbox-group>
				</el-form-item>
				<div class="title">发放设置</div>
				<el-form-item label="总发放数量" prop="giveNum">
					<div class="column">
						<div class="center">
							<el-switch v-model="infiniteGiveNum" @change="infiniteGiveNumChange" />
							<span>关闭则为无限制</span>
						</div>
						<div v-if="infiniteGiveNum" style="margin-top: 10px">
							<el-input v-model="form.giveNum" placeholder="请输入总发放数量" style="width: 200px"
								input-style="text-align: center;" @input="giveNumInput">
								<template #append>张</template>
							</el-input>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="每次赠送">
					<el-input v-model="couponGiveNum" placeholder="请输入" style="width: 200px" input-style="text-align: center;"
						@input="couponGiveNumInput">
						<template #append>张</template>
					</el-input>
				</el-form-item>
				<el-form-item label="每人限量" prop="getLimit">
					<div class="column">
						<div class="center">
							<el-switch v-model="infiniteUseLimit" @change="infiniteUseLimitChange" />
							<span>关闭则为无限制</span>
						</div>
						<div v-if="infiniteUseLimit" style="margin-top: 10px">
							<el-input v-model="form.getLimit" placeholder="请输入每人限量" style="width: 200px"
								input-style="text-align: center;" @input="getLimitInput">
								<template #append>张</template>
							</el-input>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="启用状态">
					<el-switch :active-value="1" :inactive-value="0" v-model="form.status" />
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false">取 消</el-button>
					<el-button type="primary" :loading="loading" @click="submitHandle">
						确 定
					</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import _ from "lodash";
import { ref, onMounted } from "vue";
import { filterNumberInput } from "@/utils";
import { addConsumerCoupon, couponPage, updateConsumerCouponById } from "@/api/coupon/index.js";
const shopInfo = ref("");
const dialogVisible = ref(false);
const titleOptions = reactive({
	title: "添加优惠券",
	couponTypeList: [
		{
			value: 1,
			label: "满减券",
		},
		{
			value: 2,
			label: "商品兑换券",
		},
		{
			value: 3,
			label: "折扣券",
		},
		{
			value: 4,
			label: "第二件半价券",
		},
		{
			value: 5,
			label: "消费送券",
		},
		{
			value: 6,
			label: "买一送一券",
		},
		{
			value: 7,
			label: "固定价格券",
		},
		{
			value: 8,
			label: "免配送费券",
		},
	],
});
// 是否为无限数量
const infiniteFlagNum = ref(-10086);
const infiniteGiveNum = ref(true);
function infiniteGiveNumChange(e) {
	if (!e) {
		form.value.giveNum = infiniteFlagNum.value;
	} else {
		form.value.giveNum = "";
	}
}

// 是否为无限每人领取限量
const infiniteUseLimit = ref(true);
function infiniteUseLimitChange(e) {
	if (!e) {
		form.value.getLimit = infiniteFlagNum.value;
	} else {
		form.value.getLimit = "";
	}
}

// 券的赠送数量
const couponList = ref([]);
const couponGiftList = ref("");
const couponGiveNum = ref(1);

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为不限量
	status: 1, // 状态：0-禁用，1-启用
});

const resetForm = ref(null);

// 自定义校验使用门槛
const fullAmountValidate = (rule, value, callback) => {
	if (couponGiftList.value.length == 0) {
		callback(new Error("请选择优惠券"));
	} else if (couponGiveNum.value <= 0) {
		callback(new Error("请输入每次赠送数量"));
	} else {
		callback();
	}
};

// 自定义校验每人限量
const giveNumValidate = (rule, value, callback) => {
	if (form.value.giveNum <= 0 && infiniteGiveNum.value) {
		callback(new Error("请输入总发放数量"));
	} else {
		callback();
	}
};

// 自定义校验每人每日使用限量
const useLimitValidate = (rule, value, callback) => {
	if (form.value.getLimit <= 0 && infiniteUseLimit.value) {
		callback(new Error("请输入每人限量"));
	} else {
		callback();
	}
};

const formRules = ref({
	fullAmount: [{ required: true, message: "请输入赠券门槛", trigger: "blur" }],
	coupon: [
		{
			required: true,
			validator: fullAmountValidate,
			trigger: "blur",
		},
	],
	useType: [{ required: true, message: "请选择可使用类型", trigger: "change" }],
	giveNum: [
		{
			required: true,
			validator: giveNumValidate,
			trigger: "blur",
		},
	],
	getLimit: [
		{
			required: true,
			validator: useLimitValidate,
			trigger: "blur",
		},
	],
});

// 开始提交
const formRef = ref(null);
const emits = defineEmits(["success"]);
const loading = ref(false);
function submitHandle() {
	formRef.value.validate(async (valid) => {
		try {
			if (valid) {
				let item = couponList.value.find((item) => item.id == couponGiftList.value);
				form.value.couponGiftList = [
					{
						couponName: item.title,
						couponId: item.id,
						num: couponGiveNum.value,
					},
				];
				loading.value = true;
				form.value.shopId = shopInfo.value.shopId;
				if (form.value.id) {
					await updateConsumerCouponById(form.value);
				} else {
					await addConsumerCoupon(form.value);
				}
				emits("success");
				dialogVisible.value = false;
			}
		} catch (err) {
			console.log(err);
		}
		loading.value = false;
	});
}

// 初始化form
function resetHandle() {
	form.value = { ...resetForm.value };
	infiniteGiveNum.value = true;
	infiniteUseLimit.value = true;
	couponGiftList.value = [];
	couponGiveNum.value = 1;
}

// 显示弹窗
function show(t, obj = null) {
	console.log(obj);

	let m = titleOptions.couponTypeList.find((item) => item.value == t);
	if (obj && obj.id) {
		titleOptions.title = `编辑${m.label}`;
		form.value = { ...obj };
		form.value.useType = JSON.parse(form.value.useType);
		couponGiftList.value = form.value.couponGiftList[0].couponId;
		couponGiveNum.value = form.value.couponGiftList[0].num;

		if (form.value.giveNum == infiniteFlagNum.value) {
			infiniteGiveNum.value = false;
		}

		if (form.value.getLimit == infiniteFlagNum.value) {
			infiniteUseLimit.value = false;
		}
	} else {
		titleOptions.title = `添加${m.label}`;
		resetHandle();
	}
	dialogVisible.value = true;
}

// 关闭后重置表单验证
function closedReset() {
	formRef.value.resetFields();
}

// 获取优惠券列表
async function couponPageAjax() {
	try {
		const res = await couponPage({
			page: 1,
			size: 500,
		});
		couponList.value = res.records;
	} catch (err) {
		console.log(err);
	}
}

// 从本地获取商户信息
function getLocalShopInfo() {
	shopInfo.value = JSON.parse(localStorage.getItem("userInfo"));
}
onMounted(() => {
	resetForm.value = { ...form.value };
	getLocalShopInfo();
	couponPageAjax();
});

// input过滤
const time = 500;
const couponGiveNumInput = _.debounce(function (value) {
	couponGiveNum.value = filterNumberInput(value, 1);
	if (couponGiveNum.value == "") {
		couponGiveNum.value = 1;
	}
}, time);

const giveNumInput = _.debounce(function (value) {
	form.value.giveNum = filterNumberInput(value, 1);
}, time);

const getLimitInput = _.debounce(function (value) {
	form.value.getLimit = filterNumberInput(value, 1);
}, time);

defineExpose({
	show,
});
</script>

<style scoped lang="scss">
.title {
	color: #000;
	padding: 14px;
	background-color: #f8f8f8;
	margin-bottom: 14px;
	font-size: 16px;
}

.column {
	display: flex;
	flex-direction: column;
}

.center {
	display: flex;
	align-items: center;
	gap: 10px;
}
</style>
