<template>
	<div class="m-4 bg-white p-4">
		<div v-if="shopInfo.isHeadShop == 1 || isUse">
			<HeaderCard name="超级会员" intro="用户会员管理设置" icon="super_vip"
				:showSwitch="shopInfo.isHeadShop == 1 || shopInfo.shopType == 'only'" v-model:isOpen="basicForm.isOpen">
			</HeaderCard>
			<el-tabs class="mt-4" v-model="activeTab" type="border-card">
				<el-tab-pane :label="item.label" v-for="item in configs" :key="item.name" :name="item.name">
					<template v-if="item.name == 'basic'">
						<h3>基础设置</h3>
						<el-form ref="form" :model="basicForm">
							<el-form-item label="提交生日/姓名">
								<el-radio-group v-model="basicForm.isSubmitInfo">
									<el-radio :value="1">是</el-radio>
									<el-radio :value="0">否</el-radio>
								</el-radio-group>
								<small class="color-999 m-l-6">
									*成为会员前需提交生日、姓名、性别信息。
								</small>
							</el-form-item>
							<el-form-item label="会员开通方式">
								<el-radio-group v-model="basicForm.openType">
									<el-radio value="PAY">购买开通</el-radio>
									<el-radio value="CONDITION">条件开通</el-radio>
								</el-radio-group>
							</el-form-item>
							<!-- 购买开通 -->
							<div v-if="basicForm.openType == 'PAY'">
								<el-form-item label="会员周期列表">
									<el-button type="primary" @click="refDialogPlans.open()">
										添加方案
									</el-button>
								</el-form-item>
								<el-form-item label="">
									<el-table :data="basicForm.configList" border style="width: 60%">
										<el-table-column prop="name" label="名称" align="center" />
										<el-table-column prop="price" label="价格" align="center" />
										<el-table-column prop="reward" label="赠送成长值" align="center" />
										<el-table-column label="赠送优惠券" align="center">
											<template #default="scope">
												{{ totalCount(scope.row.couponList) }}张优惠券
											</template>
										</el-table-column>
										<el-table-column prop="is_auto_renew" label="会员周期" align="center">
											<template #default="scope">
												{{ scope.row.circleTime }} {{ scope.row.circleUnit }}
											</template>
										</el-table-column>
										<el-table-column label="操作" align="center" width="120">
											<template #default="scope">
												<el-button type="text" @click="
													refDialogPlans.open(scope.row, scope.$index)
													">
													编辑
												</el-button>
												<el-button type="text" style="color: red" @click="deletePlan(scope.row)">
													删除
												</el-button>
											</template>
										</el-table-column>
									</el-table>
								</el-form-item>
							</div>
							<!-- 条件开通 -->
							<div v-if="basicForm.openType == 'CONDITION'">
								<el-form-item label="成为会员条件">
									<div>
										<div class="m-b-2" v-for="(item, index) in conditionLists" :key="index">
											<el-checkbox v-model="item.checked">
												{{ item.label }}
											</el-checkbox>
											<el-input-number style="margin-left: 20px" v-if="item.label != '绑定手机号' && item.checked"
												v-model="item.value" :step="item.step" :precision="item.precision || 0"
												:step-strictly="item.stepStrictly || false" :min="item.min || 0" />
										</div>
									</div>
								</el-form-item>
							</div>
							<el-form-item label="参与会员价门店">
								<el-radio-group v-model="basicForm.memberPriceShopType">
									<el-radio value="ALL">全部门店</el-radio>
									<el-radio value="PART">指定门店</el-radio>
								</el-radio-group>
							</el-form-item>
							<el-form-item label="选择门店" v-if="basicForm.memberPriceShopType == 'PART'">
								<el-select style="max-width: 600px" v-model="basicForm.memberPriceShopIdList" multiple
									placeholder="请选择门店">
									<el-option v-for="item in shops" :key="item.shopId" :label="item.shopName" :value="item.shopId" />
								</el-select>
							</el-form-item>
							<el-form-item label="享受会员价">
								<div class="center">
									<el-switch v-model="basicForm.isMemberPrice" :active-value="1" :inactive-value="0"></el-switch>
									<div class="tips">开启时，会员价与会员折扣同时享用</div>
								</div>
							</el-form-item>
							<el-form-item label="规则说明">
								<el-input v-model="basicForm.remark" style="width: 400px" :autosize="{ minRows: 4, maxRows: 5 }"
									type="textarea" placeholder="请输入内容"></el-input>
							</el-form-item>
						</el-form>
						<h3>升级规则</h3>
						<el-form-item label="获取成长值升级">
							<div class="color-666">
								<div class="flex">
									<div>
										<div class="m-b-4">
											<span>每消费1元获得</span>
											<el-input-number class="m-x-2" v-model="basicForm.costReward" placeholder="请输入内容" />
											<span>成长值</span>
										</div>
										<div>
											<span>每充值1元获得</span>
											<el-input-number class="m-x-2" v-model="basicForm.rechargeReward" placeholder="请输入内容" />
											<span>成长值</span>
										</div>
									</div>

									<span class="ml-4" style="color: red; font-size: 12px">
										*两个条件必选有一条是大于0的数值
									</span>
								</div>
							</div>
						</el-form-item>
						<div class="flex mt-10 justify-center gap-10">
							<el-button style="width: 100px" type="primary" @click="basicSubmit" size="large"
								v-if="shopInfo.isHeadShop || shopInfo.shopType == 'only'">
								保存
							</el-button>
							<el-button @click="close" style="width: 100px" size="large">取消</el-button>
						</div>
					</template>
					<!-- 会员等级设置 -->
					<template v-if="item.name == 'lv'">
						<h3>会员等级设置</h3>
						<div>
							<el-button type="primary" @click="addLevel">添加会员等级</el-button>
						</div>
						<el-tabs v-model="activeLevelId" type="card" style="margin-top: 20px" @tab-remove="removeLevel"
							@tab-add="addLevel" @tab-change="levelTabChange" editable>
							<el-tab-pane v-for="(level, index) in levels" :key="level.id"
								:label="index + 1 + '级:' + level.name || '未命名等级'" :name="index">
								<!-- 编辑会员等级参数 -->
								<el-form :model="level" label-width="150px">
									<el-form-item label="会员标题" required>
										<el-input v-model="level.name" :style="inputStyle" maxlength="30" placeholder="请输入会员标题" />
									</el-form-item>
									<el-form-item label="所需成长值" required>
										<el-input-number :disabled="index == 0" v-model="level.experienceValue" type="number"
											placeholder="请输入所需成长值" :style="inputStyle" :min="levelExperienceValueMin(index, level)" />
									</el-form-item>
									<el-form-item label="会员折扣" required>
										<el-input-number v-model="level.discount" :style="inputStyle" :step="1" step-strictly :min="1"
											:max="100" type="number" placeholder="请输入会员折扣" />
										<span style="margin-left: 4px;color: #666;">%</span>
									</el-form-item>
									<el-form-item label="等级标识">
										<div>
											<!-- <small class="color-666">建议优先选择 jpg 格式，大小控制在 500k 以内</small> -->
											<div class="flex">
												<SingleImageUpload v-model="level.logo" />
											</div>
										</div>
									</el-form-item>
									<el-form-item label="消费送积分">
										<div>
											<el-switch v-model="level.isCostRewardPoints" :inactive-value="0" :active-value="1" />
											<!-- <el-radio-group v-model="level.isPointsEnabled">
                      <el-radio :value="true">已启用</el-radio>
                      <el-radio :value="false">已禁用</el-radio>
                    </el-radio-group> -->
											<div v-if="level.isCostRewardPoints" style="margin-top: 10px" class="color-666 flex">
												<span class="no-wrap">每消费</span>
												<el-input-number :min="0.01" :precision="2" :controls="false" class="m-x-2"
													v-model="level.costRewardPoints" type="number" placeholder="请输入内容" />
												<span class="no-wrap">元赠送1积分</span>
											</div>
										</div>
									</el-form-item>
									<el-form-item label="等级说明" required>
										<el-input v-model="level.remark" style="width: 400px" :maxlength="200"
											:autosize="{ minRows: 4, maxRows: 5 }" type="textarea" placeholder="请输入等级说明，最多 250 字" />
									</el-form-item>
									<!-- <el-form-item label="周期时间">
                  <div class="flex w-full gap-2">
                    <el-input
                      style="width: 140px"
                      v-model="level.cycleTime"
                      type="number"
                      placeholder="请输入周期时间"
                    />
                    <el-select style="width: 80px" v-model="level.cycleUnit" placeholder="单位">
                      <el-option label="周" value="周" />
                      <el-option label="月" value="月" />
                      <el-option label="年" value="年" />
                    </el-select>
                  </div>
                </el-form-item> -->
									<el-form-item label="自动发放">
										<div>
											<el-switch v-model="level.isCycleReward" :inactive-value="0" :active-value="1" />
											<!-- <el-radio-group v-model="level.isCycleReward">
                      <el-radio :value="true">已启用</el-radio>
                      <el-radio :value="false">已禁用</el-radio>
                    </el-radio-group> -->
											<div v-if="level.isCycleReward" style="margin-top: 10px">
												<div class="flex">
													<span class="color-666 no-wrap mr-4">周期时间</span>
													<el-input v-model="level.cycleTime" type="number" placeholder="请输入周期时间" />
													<el-select v-model="level.cycleUnit" placeholder="选择单位">
														<el-option label="周" value="周" />
														<el-option label="月" value="月" />
														<el-option label="年" value="年" />
													</el-select>
												</div>
												<div class="flex mt-4">
													<span class="color-666 no-wrap mr-4">赠送积分</span>
													<el-input-number :step="1" step-strictly :min="1" v-model="level.cycleRewardPoints"
														type="number" placeholder="赠送积分" />
												</div>
												<div class="flex mt-4" style="align-items: flex-start">
													<span class="color-666 no-wrap mr-4">送优惠券</span>
													<CouponLists v-model="level.cycleRewardCouponList" />
													<!-- <el-select v-model="level.autoSendCoupon" placeholder="选择赠送优惠券">
                          <el-option
                            v-for="coupon in couponList"
                            :key="coupon.id"
                            :label="coupon.name"
                            :value="coupon.id"
                          />
                        </el-select> -->
												</div>
											</div>
										</div>
									</el-form-item>
								</el-form>
								<div class="flex mt-10 justify-center gap-10" v-if="shopInfo.isHeadShop || shopInfo.shopType == 'only'">
									<el-button style="width: 100px" type="primary" @click="saveLevel(level)" size="large">
										保存
									</el-button>
									<el-button @click="close" style="width: 100px" size="large">
										取消
									</el-button>
								</div>
							</el-tab-pane>
						</el-tabs>
					</template>
					<template v-if="activeTab == 'order'">
						<buyVipOrder />
					</template>
				</el-tab-pane>
			</el-tabs>
		</div>
		<div style="padding-top: 14px;" v-else>门店未参与超级会员活动或主店未开启活动，如需开启参与请联系主店</div>
		<DialogPlans ref="refDialogPlans" @submitSuccess="submitSuccess"></DialogPlans>
	</div>
</template>

<script setup>
import shopApi from "@/api/account/shop";
import memberApi from "@/api/market/member";
import HeaderCard from "../components/headerCard.vue";
import DialogPlans from "./components/dialog-plans.vue";
import CouponLists from "./components/coup-lists.vue";
import buyVipOrder from "./components/buyVipOrder.vue";
import { ref, reactive, watch, toRaw, getCurrentInstance, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

const shopInfo = ref("");
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 conditionLists = ref([
	{ label: "绑定手机号", checked: false, code: "BIND_PHONE" },
	{
		label: "订单达成指定次数",
		checked: false,
		value: "",
		code: "ORDER",
		step: 1,
		stepStrictly: true,
		min: 1,
	},
	{
		label: "消费达到指定金额",
		checked: false,
		value: "",
		code: "COST_AMOUNT",
		precision: 2,
		min: 0.01,
	},
	{
		label: "充值达到指定金额",
		checked: false,
		value: "",
		code: "RECHARGE_AMOUNT",
		precision: 2,
		min: 0.01,
	},
]);
const basicForm = reactive({
	isSubmitInfo: 1,
	openType: 0,
	configList: [],
	memberPriceShopType: "ALL",
	remark: "",
	costReward: 0,
	rechargeReward: 0,
	memberPriceShopIdList: [],
	isMemberPrice: 1,
	isOpen: 0,
});
function deletePlan(row) {
	const index = basicForm.configList.indexOf(row);
	if (index > -1) {
		basicForm.configList.splice(index, 1);
	}
}
function submitSuccess(plans, index) {
	if (!basicForm.configList) {
		basicForm.configList = [];
	}
	if (index !== null && index !== undefined) {
		basicForm.configList[index] = plans;
		return;
	}
	basicForm.configList.push(plans);
}
// 会员基础设置提交
function basicSubmit() {
	const data = toRaw(basicForm);
	// if (data.openType == "PAY") {
	//   data.conditionList = null;
	// }
	// if (data.openType == "CONDITION") {
	//   data.configList = null;
	// }
	console.log(data);
	if (
		basicForm.openType == "PAY" &&
		(!basicForm.configList || basicForm.configList.length <= 0)
	) {
		return ElMessage.error("请添加会员方案");
	}
	data.conditionList = conditionLists.value
		.filter((v) => v.checked)
		.map((v) => {
			return {
				code: v.code,
				value: v.value,
			};
		});
	if (
		basicForm.openType == "CONDITION" &&
		(!data.conditionList || data.conditionList.length <= 0)
	) {
		return ElMessage.error("请选择成为会员条件");
	}
	if (basicForm.costReward <= 0 && basicForm.rechargeReward <= 0) {
		return ElMessage.error("获取成长值升级规则两个条件必选有一条是大于0的数值");
	}
	data.conditionList = conditionLists.value
		.filter((v) => v.checked)
		.map((v) => {
			return {
				code: v.code,
				value: v.value,
			};
		});
	memberApi.editConfig(data).then((res) => {
		ElMessage.success("保存成功");
	});
	// ElMessage.success("保存成功");
}

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

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

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: 100,
		logo: "",
		costRewardPoints: 1,
		isCostRewardPoints: 0,
		isCycleReward: 0,
		cycleTime: 1,
		cycleUnit: "月",
		cycleRewardPoints: 1,
		cycleRewardCouponList: [],
		remark: "",
	};
	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 memberApi.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) {
	if (level.isCycleReward) {
		if (level.cycleRewardCouponList && level.cycleRewardCouponList.length) {
			const isPass = (level.cycleRewardCouponList || []).every(
				(item) => item.num && item.coupon.id
			);
			if (!isPass) {
				ElMessage.error("请选择优惠券并输入数量");
				return;
			}
		}
		if (
			(!level.cycleRewardCouponList || level.cycleRewardCouponList.length <= 0) &&
			level.cycleRewardPoints <= 0
		) {
			ElMessage.error("赠送积分和送优惠券必须填充一项");
			return;
		}
	}

	if (level.name.trim() === "") {
		return ElMessage.error("请输入会员标题");
	}
	if (level.experienceValue === "") {
		return ElMessage.error("请输入所需成长值");
	}
	if (level.discount === "") {
		return ElMessage.error("请输入会员折扣");
	}
	if (level.remark.trim() === "") {
		return ElMessage.error("请输入等级说明");
	}
	const res = level.id ? await memberApi.levelEdit(level) : await memberApi.levelAdd(level);
	if (res) {
		ElMessage.success("保存成功");
	}
	levelRefresh();
}

const shops = ref([]);

const isUse = ref(false)
async function levelRefresh() {
	memberApi.levelList().then((res) => {
		if (res && res.length) {
			levels.value = res;
			if (res.length != 0) {
				selectedLevel.value = res[activeLevelId.value];
			}
		}
	});
}
async function init() {
	shopApi.getBranchList().then((res) => {
		console.log(res);
		if (res) {
			shops.value = res;
		}
	});
	memberApi.getConfig().then((res) => {
		Object.assign(basicForm, res);
		basicForm.isOpen = +basicForm.isOpen;
		res.conditionList = res.conditionList || [];
		res.configList = res.configList || [];
		conditionLists.value = conditionLists.value.map((v) => {
			const findItem = res.conditionList.find((cond) => cond.code == v.code);
			if (findItem) {
				v.value = findItem.value;
				v.checked = true;
			} else {
				v.checked = false;
			}
			return v;
		});
		console.log(conditionLists.value);

		if (res.isOpen == 1) {
			if (res.memberPriceShopType == 'ALL' || shopInfo.value.shopType == 'only') {
				isUse.value = true
			} else {
				let currentShopId = shopInfo.value.shopId;
				res.memberPriceShopIdList.some((item) => {
					if (item == currentShopId) {
						isUse.value = true;
						return true;
					}
				});
			}
		} else {
			isUse.value = false;
		}
	});
	memberApi.levelList().then((res) => {
		if (res && res.length) {
			levels.value = res;
			activeLevelId.value = 0;
		}
	});
}

// 从本地获取商户信息
function getLocalShopInfo() {
	shopInfo.value = JSON.parse(localStorage.getItem("userInfo"));
}
onMounted(() => {
	init();
	getLocalShopInfo();
});
//计算总优惠券数量
function totalCount(arr) {
	return arr.reduce((total, item) => {
		return total + item.num * 1;
	}, 0);
}
//
function levelExperienceValueMin(index, level) {
	if (index == 0) {
		return 0;
	}
	return levels.value[index - 1].experienceValue + 1;
}
//返回
function close() {
	router.back();
}
//
function levelTabChange(index) { }
</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;
}

.center {
	display: flex;
	gap: 14px;

	.tips {
		color: #999;
	}
}
</style>
