<template>
	<div class="m-4 bg-white p-4">
		<HeaderCard
			name="新客立减"
			intro="首单下单减免金额"
			icon="new_user_discount"
			showSwitch
			v-model:isOpen="basicForm.isEnable"
		></HeaderCard>
		<div style="padding-top: 40px">
			<el-form
				ref="formRef"
				:rules="rules"
				:model="basicForm"
				label-width="120px"
				label-position="right"
			>
				<el-form-item label="活动时间">
					<div style="width: 300px">
						<el-date-picker
							v-model="validityScope"
							type="daterange"
							range-separator="至"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							@change="validityScopeChange"
						/>
					</div>
				</el-form-item>
				<el-form-item label="减免方式">
					<div>
						<el-radio-group v-model="basicForm.discountType">
							<el-radio value="FIXED">固定金额</el-radio>
							<el-radio value="RANDOM">随机立减</el-radio>
						</el-radio-group>
						<div v-if="basicForm.discountType === 'FIXED'">
							<el-input
								v-model="basicForm.discountAmount"
								placeholder="请输入金额"
								:maxlength="8"
								@input="discountAmountInput"
							>
								<template #append>元</template>
							</el-input>
						</div>
					</div>
				</el-form-item>
				<!-- 随机立减 -->
				<div v-if="basicForm.discountType == 'RANDOM'">
					<el-form-item label="随机减免方案">
						<el-button type="primary" @click="refDialogPlans.open()">
							添加方案
						</el-button>
					</el-form-item>
					<el-form-item prop="randomDiscountList">
						<el-table :data="basicForm.randomDiscountList" border style="width: 60%">
							<el-table-column prop="amount" label="减免金融（元）" align="center" />
							<el-table-column prop="probability" label="概率（%）" align="center" />

							<el-table-column label="操作" align="center">
								<template #default="scope">
									<el-button
										type="primary"
										link
										@click="refDialogPlans.open(scope.row, scope.$index)"
									>
										编辑
									</el-button>
									<el-button
										type="danger"
										link
										@click="
											basicForm.randomDiscountList.splice(scope.$index, 1)
										"
									>
										删除
									</el-button>
								</template>
							</el-table-column>
						</el-table>
					</el-form-item>
				</div>
				<div>
					<el-form-item label="可使用类型" prop="useTypeList">
						<el-checkbox-group v-model="basicForm.useTypeList">
							<el-checkbox
								v-model="item.value"
								:label="item.label"
								:value="item.value"
								v-for="item in useTypeList"
								:key="item.value"
							></el-checkbox>
						</el-checkbox-group>
					</el-form-item>
				</div>
			</el-form>
		</div>
		<div class="flex mt-10 justify-center gap-10">
			<el-button style="width: 100px" type="primary" @click="basicSubmit" size="large">
				保存
			</el-button>
			<el-button @click="close" style="width: 100px" size="large">取消</el-button>
		</div>
		<DialogPlans ref="refDialogPlans" @submitSuccess="submitSuccess"></DialogPlans>
	</div>
</template>

<script setup>
import { dayjs } from "element-plus";
import _, { cloneDeep } from "lodash";
import shopApi from "@/api/account/shop";
import consumeDiscountApi from "@/api/market/consumeDiscount";
import HeaderCard from "../components/headerCard.vue";
import DialogPlans from "./components/dialog-plans.vue";
import { ref, reactive, watch, toRaw, getCurrentInstance, onMounted } from "vue";
import { ElMessage, ElNotification } from "element-plus";
import { useRouter } from "vue-router";
import { filterNumberInput, convertTimeToDate } from "@/utils";

const inputStyle = {
	width: "340px",
};

const router = useRouter();

const refDialogPlans = ref();
const configs = [
	{ name: "basic", label: "会员基础设置" },
	{ name: "lv", label: "会员等级设置" },
	{ name: "order", label: "购买会员订单" },
];
const activeTab = ref("basic");
const useTypeList = ref([
	{ label: "堂食", value: "dine-in" },
	{ label: "自取", value: "take-out" },
	{ label: "外卖", value: "take-away" },
	{ label: "快递", value: "post" },
]);
const formRef = ref(null);
const basicForm = reactive({
	isEnable: 1,
	discountType: "RANDOM",
	discountAmount: 0.0,
	randomDiscountList: [],
	useTypeList: [],
	shopId: 0,
	startTime: "",
	endTime: "",
});

const validityScope = ref([]);
function validityScopeChange(e) {
	if (e && e.length) {
		basicForm.startTime = dayjs(e[0]).format("YYYY-MM-DD 00:00:00");
		basicForm.endTime = dayjs(e[1]).format("YYYY-MM-DD 23:59:59");
	} else {
		basicForm.startTime = "";
		basicForm.endTime = "";
	}
}

const rules = reactive({
	useTypeList: [
		{
			required: true,
			message: "请选择可使用类型",
			trigger: "change",
		},
	],
	randomDiscountList: [
		{
			validator: (rule, value, callback) => {
				if (basicForm.randomDiscountList.length == 0) {
					callback(new Error("请添加方案"));
				} else {
					callback();
				}
			},
			trigger: "change",
		},
	],
});

const time = 500;
const discountAmountInput = _.debounce(function (e) {
	basicForm.discountAmount = filterNumberInput(e);
}, time);

function submitSuccess(plans, index = null) {
	if (index !== null && index !== undefined) {
		basicForm.randomDiscountList[index] = plans;
	} else {
		basicForm.randomDiscountList.push(plans);
	}
}
// 会员基础设置提交
function basicSubmit() {
	formRef.value.validate(async (vaild) => {
		try {
			if (vaild) {
				console.log(basicForm);
				await consumeDiscountApi.editConfig(basicForm);
				ElNotification({
					title: "注意",
					message: "保存成功",
					type: "success",
				});
			}
		} catch (err) {
			console.log(err);
		}
	});
}

// 会员等级列表
const levels = ref([]);

// 当前选中的会员等级
const selectedLevel = ref(null);

// 优惠券列表
const couponList = ref([
	{ id: 1, name: "满100减10" },
	{ id: 2, name: "满200减30" },
]);
let activeLevelId = ref(null);
// 添加会员等级
function addLevel() {
	const nowLastVip = levels.value[levels.value.length - 1];
	let name = "VIP1";
	if (levels.value.length) {
		name = "VIP" + (levels.value.length + 1);
	}
	if (nowLastVip && !nowLastVip.id) {
		ElMessage.error("请先保存当前等级");
		return;
	}

	const newLevel = {
		name,
		experienceValue: 0,
		discount: 1,
		logo: "",
		costRewardPoints: 1,
		isCostRewardPoints: 1,
		isCycleReward: 0,
		cycleTime: 1,
		cycleUnit: "月",
		cycleRewardPoints: 1,
		cycleRewardCouponList: [],
	};
	console.log(newLevel);
	levels.value.push(newLevel);
	selectedLevel.value = newLevel;
	activeLevelId.value = levels.value.length - 1;
}

// 编辑会员等级
function editLevel(level) {
	selectedLevel.value = level;
}
// 删除会员等级
async function removeLevel(index) {
	const item = levels.value[index];
	const { id } = item;
	if (!id) {
		// 本地删除
		levels.value.splice(index, 1);
		const newLevel = levels.value[index - 1];
		selectedLevel.value = newLevel;
		activeLevelId.value = index - 1;
		ElMessage.success("删除成功");
		return;
	}
	ElMessageBox.confirm("确定要删除吗？", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(async () => {
		const res = await consumeDiscountApi.levelDel({ id: id });
		if (res) {
			levels.value.splice(index, 1);
			ElMessage.success("删除成功");
		}

		const newLevel = levels.value[index - 1];
		selectedLevel.value = newLevel;
		activeLevelId.value = index - 1;
	});
}
// 保存会员等级
async function saveLevel(level) {
	const isPass = level.cycleRewardCouponList.every((item) => item.num && item.coupon.id);
	if (!isPass) {
		ElMessage.error("请选择优惠券并输入数量");
		return;
	}
	const res = level.id
		? await consumeDiscountApi.levelEdit(level)
		: await consumeDiscountApi.levelAdd(level);
	if (res) {
		ElMessage.success("保存成功");
	}
	levelRefresh();
}

const shops = ref([]);

async function levelRefresh() {
	consumeDiscountApi.levelList().then((res) => {
		if (res && res.length) {
			levels.value = res;
			if (res.length != 0) {
				selectedLevel.value = res[activeLevelId.value];
			}
		}
	});
}
async function init() {
	consumeDiscountApi.getConfig().then((res) => {
		Object.assign(basicForm, res);
		if (!res.useTypeList) {
			basicForm.useTypeList = [];
		}
		if (!res.randomDiscountList) {
			basicForm.randomDiscountList = [];
		}
		if (res.startTime) {
			validityScope.value = [res.startTime, res.endTime];
		}
	});
}

onMounted(() => {
	init();
});
//计算总优惠券数量
function totalCount(arr) {
	return arr.reduce((total, item) => {
		return total + item.num * 1;
	}, 0);
}
//返回
function close() {
	router.back();
}
</script>

<style lang="scss" scoped>
:deep(.el-tabs--border-card) {
	border: none;
}
:deep(.el-tabs--border-card > .el-tabs__header) {
	border: none;
	padding: 4px;
}
:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item) {
	border: none;
}
:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active) {
	border: none;
}
</style>
