<template>
	<view class="settings-page">
		<custom-navbar title="订单消息设置" :showBack="true"></custom-navbar>
		<!-- 通知设置标题区域，带小图标 -->
		<view class="settings-title">
			<text>通知设置</text>
			<image class="settings-title-tip"
				src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/e65794a6-bda3-44da-b8ce-1bf3ee6c1832.png"
				@click="showGuideDialog = true">
			</image>
		</view>
		<view class="settings-cards">
			<view class="settings-card card-line flex-row-center-between">
				<view>
					<view class="card-heard flex-row-center-between">
						<view class="card-heard-left flex-row-center">
							<text class="card-heard-left-text">允许手机接收</text>
						</view>
					</view>
				</view>
				<uv-switch v-model="mainSwitch.switch" activeColor="#E8101E"
					@change="handleSwitchChange('total',mainSwitch, $event)"></uv-switch>
			</view>
		</view>
		<view class="settings-title" v-if="kindList.length">
			细分消息类型
		</view>
		<view class="settings-cards">
			<view class="settings-card card-line flex-row-center-between" v-for="(item,index) in kindList" :key="index">
				<view>
					<view class="card-heard flex-row-center-between">
						<view class="card-heard-left flex-row-center">
							<text class="card-heard-left-text">{{ item.second_kind }}</text>
						</view>
					</view>
					<view class="card-tip">{{ item.text }}</view>
				</view>
				<uv-switch v-model="item.switch" activeColor="#E8101E"
					@change="handleSwitchChange('branch',item, $event)"></uv-switch>
			</view>
		</view>

		<!-- 通知设置弹窗（移除 transition，改用 CSS 类实现动画） -->
		<view v-if="showGuideDialog" class="dialog-mask" @click="closeGuideDialog" @touchmove.prevent>
			<view class="dialog-container" :class="{ 'dialog-show': showGuideDialog, 'dialog-hide': !showGuideDialog }"
				@click.stop>
				<view class="dialog-title">通知设置</view>
				<view class="dialog-desc">
					开启后，将以手机锁屏\通知中心\横幅的系统通知方式，为你推送指定类型的消息。
				</view>
				<!-- 中间的图片区域 -->
				<image class="dialog-illustration"
					src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/94b5bb62-e90b-4e14-a89f-a44ea1504dd9.png"
					mode="widthFix">
				</image>
				<view class="dialog-btn" @click.stop="closeGuideDialog">
					<text class="dialog-btn-text">我知道了</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import $http from '@/utils/request.js'

	export default {
		data() {
			return {
				showGuideDialog: false, // 控制弹窗显示
				kindList: [],
				mainSwitch: {},
				isInitializing: true // 防止初始化时触发保存
			};
		},
		onLoad() {
			this.fetchSettings();
		},

		methods: {
			// 通知设置弹窗关闭方法（统一逻辑，增加异常处理）
			closeGuideDialog() {
				try {
					this.showGuideDialog = false;
				} catch (err) {
					console.error('关闭通知设置弹窗失败:', err);
					// 兜底：强制更新属性，避免赋值失效
					this.$set(this, 'showGuideDialog', false);
				}
			},
			// 获取设置
			async fetchSettings() {
				try {
					const stateRes = await $http.post('/sj/push/getReceiveState', {
						message_type_id: 1
					});
					console.log('用户状态', stateRes);
					if (stateRes.code == 200) {
						this.mainSwitch = stateRes.data.list[0] || {};
						this.$set(this.mainSwitch, "switch", this.mainSwitch.state == 1 ? true : false)
						this.kindList = stateRes.data.list[0].kind_list || [];
						this.kindList.forEach(item => {
							if (this.mainSwitch.switch) {
								this.$set(item, "switch", item.state == 1 ? true : false)
							} else {
								this.$set(item, "switch", false)
							}
						})

					}



					this.isInitializing = false;
				} catch (err) {
					console.error('获取设置失败', err);
					this.isInitializing = false;
				}
			},

			// 处理开关变化
			handleSwitchChange(type, obj, value) {
				console.log(11111, type, obj, value)
				if (this.isInitializing) return;

				let message_type_id, message_kind_id, state = value ? 1 : 2;

				if (type == 'total' && value == false) {
					this.kindList.forEach(item => {
						this.$set(item, "switch", false)
					})
				}
				if (type == 'total' && value == true) {
					this.kindList.forEach(item => {
						this.$set(item, "switch", item.state == 1 ? true : false)
					})
				}
				if (type == 'branch' && this.mainSwitch.switch == true) {
					this.$set(obj, "state", value ? 1 : 2)
				}
				//如果总开关关闭调用批量修改接口
				if (type == 'branch' && this.mainSwitch.switch == false) {
					let data = []
					this.kindList.forEach(item => {
						let dataObj = {
							message_type_id: item.message_type_id,
							message_kind_id: item.message_kind_id,
							state: item.message_kind_id == obj.message_kind_id ? value ? 1 : 2 : 2
						}
						data.push(dataObj)
					})
					let dataObj = {
						message_type_id: this.mainSwitch.message_type_id,
						message_kind_id: this.mainSwitch.message_kind_id,
						state: 1
					}
					data.push(dataObj)
					this.setReceiveStateBatch(data);
					this.$set(this.mainSwitch, "switch", true)
					this.$set(this.mainSwitch, "state", 1)
					return
				}

				this.setSetting(obj.message_type_id, obj.message_kind_id, value);
			},

			setReceiveStateBatch(data) {
				$http.post('/sj/push/setReceiveStateBatch', {
					data: data
				}).then(res => {
					// uni.showToast({ title: '设置成功', icon: 'none' });
				}).catch(err => {
					uni.showToast({
						title: '设置失败',
						icon: 'none'
					});
					// 失败后重新拉取最新状态，保证界面与后端一致
					this.isInitializing = true;
					this.fetchSettings();
				});
			},

			// 设置推送接收状态
			setSetting(message_type_id, message_kind_id, state) {
				$http.post('/sj/push/setReceiveState', {
					message_type_id,
					message_kind_id,
					state
				}).then(res => {
					// uni.showToast({ title: '设置成功', icon: 'none' });
				}).catch(err => {
					uni.showToast({
						title: '设置失败',
						icon: 'none'
					});
					// 失败后重新拉取最新状态，保证界面与后端一致
					this.isInitializing = true;
					this.fetchSettings();
				});
			}
		}
	};
</script>

<style lang="less">
	.settings-page {
		padding: 20rpx;

		.settings-title {
			font-weight: 500;
			font-size: 22rpx;
			color: #979797;
			text-align: left;
			font-style: normal;
			margin-bottom: 20rpx;
			gap: 10rpx;
			display: flex;
			align-items: center;

			.settings-title-tip {
				width: 26rpx;
				height: 26rpx;
			}
		}

		.settings-cards {
			box-sizing: border-box;
			width: 710rpx;
			padding: 0rpx 20rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			margin-bottom: 40rpx;

			.settings-card {
				padding: 30rpx 0rpx 36rpx 0rpx;

				.card-heard {
					.card-heard-left {
						display: flex;
						align-items: center;
						gap: 8rpx;

						.card-heard-left-icon {
							height: 32rpx;
						}

						.card-heard-left-text {
							font-weight: 500;
							font-size: 28rpx;
							color: #333333;
							text-align: left;
							font-style: normal;
						}
					}

					.card-heard-right {
						gap: 10rpx;

						.card-heard-right-text {
							font-weight: 400;
							font-size: 24rpx;
							color: #333333;
							text-align: left;
							font-style: normal;
						}

						.arrow-right {
							width: 8rpx;
							height: 16rpx;
						}
					}

				}

				.card-tip {
					margin-top: 20rpx;
					font-weight: 400;
					font-size: 22rpx;
					color: #979797;
					line-height: 30rpx;
					text-align: left;
					font-style: normal;
				}
			}

			.card-line {
				border-bottom: 1rpx solid #F5F5F5;
			}
		}

		.color-red {
			color: #E8101E !important;
		}

		/* 弹窗样式 */
		.dialog-mask {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(0, 0, 0, 0.5);
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1000;
		}

		.dialog-container {
			width: 556rpx;
			height: 711rpx;
			background-color: #FFFFFF;
			border-radius: 24rpx;
			padding: 40rpx 37rpx;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			align-items: center;
		}

		.dialog-title {
			font-weight: 500;
			font-size: 40rpx;
			color: #333333;
			line-height: 56rpx;
			text-align: left;
			font-style: normal;
			margin-bottom: 36rpx;
		}

		.dialog-desc {
			font-size: 28rpx;
			color: #666666;
			line-height: 1.5;
			text-align: left;
			margin-bottom: 40rpx;
		}

		.dialog-illustration {
			width: 377rpx;
			height: 241rpx;
			height: auto;
			margin-bottom: 40rpx;
		}

		.dialog-btn {
			width: 476rpx;
			height: 86rpx;
			background: #E8101E;
			border-radius: 44rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			transition: opacity 0.1s;
		}

		.dialog-btn-text {
			font-size: 32rpx;
			font-weight: 500;
			color: #FFFFFF;
			letter-spacing: 2rpx;
		}

		/* 平滑淡入缩放动画 */
		.fade-scale-enter-active,
		.fade-scale-leave-active {
			transition: all 0.25s ease;
		}

		.fade-scale-enter,
		.fade-scale-leave-to {
			opacity: 0;
			transform: scale(0.9);
		}
	}

	// 弹窗基础样式（保留原有样式，新增动画相关属性）
	.dialog-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.dialog-container {
		// 保留你原有 dialog-container 的样式（如宽高、内边距等），新增动画基础属性
		transition: all 0.3s ease; // 和原 transition 动画时长一致
		opacity: 0;
		transform: scale(0.9); // 原 fade-scale 的缩放效果
		// 以下是你原有样式（根据实际情况调整）
		padding: 40rpx;
		background: #fff;
		border-radius: 20rpx;
		text-align: center;
	}

	// 弹窗显示动画
	.dialog-show {
		opacity: 1;
		transform: scale(1);
	}

	// 弹窗隐藏动画（和原 leave-to 效果一致）
	.dialog-hide {
		opacity: 0;
		transform: scale(0.9);
	}

	// 保留你原有其他弹窗样式
	.dialog-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 20rpx;
	}

	.dialog-desc {
		font-size: 26rpx;
		color: #666;
		line-height: 40rpx;
		margin-bottom: 30rpx;
	}

	.dialog-illustration {
		width: 100%;
		max-width: 500rpx;
		margin-bottom: 40rpx;
	}

	.dialog-btn {
		width: 300rpx;
		height: 80rpx;
		line-height: 80rpx;
		background: #E8101E;
		border-radius: 40rpx;
		margin: 0 auto;
	}

	.dialog-btn-text {
		font-size: 30rpx;
		color: #fff;
	}
</style>