<template>
	<div class="gyq_container">
		<div class="gyq_content" v-if="shopInfo.isHeadShop == 1 || isUse">
			<HeaderCard name="智慧充值" intro="允许客户充值并使用余额支付" icon="zhcz" showSwitch v-model:isOpen="form.isEnable"></HeaderCard>
			<div style="padding-top: 14px">
				<el-tabs v-model="tabsValue">
					<el-tab-pane label="基础设置" :name="1">
						<el-form ref="formRef" :model="form" :rules="rules" label-width="120" label-position="right">
							<el-form-item label="充值面额" required>
								<el-button type="primary" @click="AddDialogRef.open()">
									添加面额
								</el-button>
							</el-form-item>
							<el-form-item prop="rechargeDetailList">
								<el-table :data="form.rechargeDetailList" border stripe>
									<el-table-column label="ID" prop="id"></el-table-column>
									<el-table-column label="充值金额（元）" prop="amount"></el-table-column>
									<el-table-column label="赠送金额" prop="rewardAmount"></el-table-column>
									<el-table-column label="赠送积分" prop="rewardPoints"></el-table-column>
									<el-table-column label="赠送优惠券" prop="couponInfoList">
										<template #default="scope">
											<div class="column">
												<div v-for="item in scope.row.couponInfoList">
													<el-tag type="primary" disable-transitions>
														{{ couponListFilter(item.id) }}x{{
															item.num
														}}张
													</el-tag>
												</div>
											</div>
										</template>
									</el-table-column>
									<el-table-column label="操作" width="120">
										<template #default="scope">
											<el-button type="primary" link @click="AddDialogRef.open(scope.row, scope.$index)">
												编辑
											</el-button>
											<el-button type="danger" link @click="
												form.rechargeDetailList.splice(scope.$index, 1)
												">
												删除
											</el-button>
										</template>
									</el-table-column>
								</el-table>
							</el-form-item>
							<el-form-item label="选择门店" prop="useType" v-if="shopInfo.isHeadShop">
								<el-radio-group v-model="form.useType">
									<el-radio label="全部门店" value="all"></el-radio>
									<el-radio label="指定门店可用" value="part"></el-radio>
								</el-radio-group>
							</el-form-item>
							<el-form-item label="选择门店" v-if="form.useType == 'part'" prop="shopIdList">
								<selectBranchs all v-model="form.shopIdList" />
							</el-form-item>
							<el-form-item label="自定义金额">
								<div class="column">
									<div class="center">
										<el-switch v-model="form.isCustom" :active-value="1" :inactive-value="0" />
										<span class="tips">自定义金额不参与赠送优惠</span>
									</div>
								</div>
							</el-form-item>
							<el-form-item label="充值并下单">
								<div class="column">
									<div class="center">
										<el-switch v-model="form.isOrder" :active-value="1" :inactive-value="0" />
										<span class="tips">开启后，订单支付页面显示充值选项</span>
									</div>
								</div>
							</el-form-item>
							<el-form-item label="充值说明" prop="remark">
								<div class="column">
									<div class="item">
										<el-input type="textarea" :rows="4" :maxlength="250" v-model="form.remark"
											placeholder="填写内容"></el-input>
									</div>
									<div class="item textarea-num">
										{{ form.remark.length }}/250字内，单文本
									</div>
								</div>
							</el-form-item>
						</el-form>
						<div class="footer" v-if="shopInfo.isHeadShop || shopInfo.shopType == 'only'">
							<el-button type="primary" size="large" @click="submitHandle">
								保存
							</el-button>
							<el-button size="large" @click="back">取消</el-button>
						</div>
					</el-tab-pane>
					<el-tab-pane label="充值记录" :name="2">
						<ChargeList />
					</el-tab-pane>
				</el-tabs>
			</div>
		</div>
		<div class="gyq_content err" v-else>门店未参与智慧充值活动，如需开启参与请联系主店</div>
		<AddDialog ref="AddDialogRef" :couponList="couponList" @success="addSuccess" />
	</div>
</template>

<script setup>
import HeaderCard from "../components/headerCard.vue";
import AddDialog from "./components/addDialog.vue";
import ChargeList from "@/views/user/charge/index.vue";
import selectBranchs from "../components/selectBranchs.vue";
import { couponPage, getBranchPage, shopRecharge, shopRechargeGet } from "@/api/coupon/index.js";
import { useRouter } from "vue-router";
import { ElNotification } from "element-plus";

const router = useRouter();
const AddDialogRef = ref(null);
const tabsValue = ref(1);
const formRef = ref(null);
const form = ref({
	isEnable: 1,
	id: "",
	shopIdList: "",
	useType: "all",
	isCustom: 0,
	isOrder: 0,
	remark: "",
	rechargeDetailList: [],
});
const rules = ref({
	rechargeDetailList: [
		{
			validator: (rule, value, callback) => {
				if (form.value.rechargeDetailList.length == 0) {
					callback(new Error("请添加面额"));
				} else {
					callback();
				}
			},
			trigger: "change",
		},
	],
	remark: [{ required: true, message: "请输入充值说明", trigger: "blur" }],
	shopIdList: [{ required: true, message: '请选择门店', trigger: 'change' }]
});

function submitHandle() {
	formRef.value.validate(async (valid) => {
		try {
			if (valid) {
				await shopRecharge(form.value);
				ElNotification({
					title: "注意",
					message: "保存成功",
					type: "success",
				});
			}
		} catch (err) {
			console.log(err);
		}
	});
}

// 点前登录店铺信息
const shopInfo = ref("");

// 获取分店列表
const branchList = ref([]);
async function getBranchPageAjax() {
	try {
		const res = await getBranchPage();
		branchList.value = res.records;
	} catch (err) {
		console.log(err);
	}
}

function addSuccess(data) {
	console.log("addSuccess===", data);
	if (data.index == null) {
		form.value.rechargeDetailList.push(data.data);
	} else {
		form.value.rechargeDetailList[data.index] = data.data;
	}
}

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

// 用id寻找优惠券名称
function couponListFilter(id) {
	if (id) {
		let obj = couponList.value.find((item) => item.id == id);
		if (obj && obj.title) {
			return obj.title;
		} else {
			return "";
		}
	} else {
		return "";
	}
}

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

function back() {
	router.back();
}

// 配置信息获取
const isUse = ref(false);
async function shopRechargeGetAjax() {
	try {
		const res = await shopRechargeGet();
		res.rechargeDetailList.map((item) => {
			item.couponInfoList.map((val) => {
				val.id = val.coupon ? val.coupon.id : null;
			});
		});
		form.value = res;

		if (res.useType == 'all') {
			isUse.value = true;
		} else {
			let currentShopId = shopInfo.value.shopId;
			res.shopIdList.some((item) => {
				if (item == currentShopId) {
					isUse.value = true;
					return true;
				}
			});
		}
		console.log('isUse', isUse.value);
		console.log(form.value);
	} catch (err) {
		console.log(err);
	}
}

onMounted(async () => {
	await couponPageAjax();
	getLocalShopInfo();
	getBranchPageAjax();
	shopRechargeGetAjax();
});
</script>

<style scoped lang="scss">
.gyq_container {
	padding: 14px;

	.gyq_content {
		padding: 14px;
		background-color: #fff;
		border-radius: 8px;

		&.err {
			color: #f56c6c;
			margin-top: 14px;
			text-align: center;
		}
	}
}

.column {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8px;

	.item {
		flex: 1;
	}
}

.center {
	display: flex;
	align-items: center;
	gap: 10px;
}

.tips {
	color: #666;
}

.footer {
	display: flex;
	justify-content: center;
}

.textarea-num {
	color: #999;
	display: flex;
	justify-content: flex-end;
}
</style>
