<template>
	<view>

		<!-- <view class="list_box" @click="bindTo('/my/setting/mimi')">
			<view class="box_left">隐私政策</view>
			<u-icon name="arrow-right"></u-icon>
		</view>
		<view class="list_box" @click="bindTo('/my/setting/xieyi')">
			<view class="box_left">用户协议</view>
			<u-icon name="arrow-right"></u-icon>
		</view>
		<view class="list_box" @click="bindTo('/my/setting/logOff')">
			<view class="box_left">用户注销</view>
			<u-icon name="arrow-right"></u-icon>
		</view>

		<view class="login_btn" @click="bindOut()">退出登录</view> -->

		<view class="titls2 " style="margin-top: 25rpx;">
			隐私管理
		</view>
		<view class="boxs">
			<view class="flex align-center justify-between padding-lr">
				<view style="line-height: 40rpx;">
					<view>位置信息共享</view>
					<view style="color: #999;font-size: 24rpx;">控制是否向平台共享实时位置</view>
				</view>
				<view class="order_money">
					<switch color="#fe6b01!important" checked @change="switch1Change" />
				</view>
			</view>
			<!-- <view class="flex align-center justify-between padding-lr">
				<view style="line-height: 40rpx;">
					<view>个人信息可见范围</view>
					<view style="color: #999;font-size: 24rpx;">设置其他用户可见的信息</view>
				</view>
				<view class="order_money">
					<u-icon name="arrow-right"></u-icon>
				</view>
			</view> -->
			<view class="flex align-center justify-between padding-lr" style="margin-top: 30rpx;">
				<view style="line-height: 40rpx;">
					<view>消息推送权限</view>
					<view style="color: #999;font-size: 24rpx;">管理通知和消息接收</view>
				</view>
				<view class="order_money">
					<switch color="#fe6b01!important" checked @change="switch1Change" />
				</view>
			</view>
		</view>

		<view class="titls2 " style="margin-top: 30rpx;">
			紧急联系人
		</view>

		<view class="boxs">
			<!-- 外层容器 -->
			<view class="flex align-center padding-tb-sm" v-for="(item, index) in personList" :key="index">
				<!-- 显示头像 -->
				<view>
					<image v-if="globalImages" :src="globalImages + 'images/order/chengcheren.png'" style="width: 80rpx;height: 80rpx;" mode=""></image>
				</view>
				<!-- 显示姓名和关系、电话 -->
				<view style="margin-left: 30rpx; line-height: 40rpx;">
					<view>{{ item.name }}</view>
					<view style="color: #999;">{{ item.relationship }} · {{ item.phone }}</view>
				</view>
				<!-- 编辑图标 -->
				<view style="position: absolute; right: 130rpx;" @tap="handleEdit(item)">
					<image v-if="globalImages" :src="globalImages + 'images/order/xiugai.png'" style="width: 36rpx;height: 36rpx;" mode="">
					</image>
				</view>
				<!-- 删除图标 -->
				<view style="position: absolute; right: 60rpx;" @tap="handleDelete(item.id, index)">
					<image v-if="globalImages" :src="globalImages + 'images/order/shanchu.png'" style="width: 36rpx;height: 36rpx;" mode="">
					</image>
				</view>
			</view>
		</view>

		<view class="login_btn" v-if="personList.length < 3" @tap="handleAddContact">添加紧急联系人</view>

		<view style="color: #999; font-size: 22rpx; text-align: center;line-height: 80rpx;">
			最多可添加三位紧急联系人
		</view>
	</view>
</template>

<script>
	import { waitForGlobalImages } from '@/utils/globalImageLoader'
	export default {
		data() {
			return {
				// 定义人员列表数据
				personList: [],
				maxContact: 3, // 最大联系人数量
				// 添加/编辑时的临时数据
				tempContact: {
					name: '',
					relationship: '',
					phone: '',
					remark: '',
					// userId: null,
				},
				globalImages: ''
			}
		},
		onShow() {
		  uni.$on('updateContact', (contact) => {
		    this.receiveContact(contact); // 调用之前定义的接收方法
		  });
		},
		onLoad() {
			this.parson()
			waitForGlobalImages().then((path) => {
			    console.log('✅ 全局图片路径:', path)
			    this.globalImages = path
			  })
		},
		onUnload() {
		  uni.$off('updateContact'); // 移除监听避免内存泄漏
		},
		methods: {
			parson () {
				this.$Request.getT('/app/emergency/selectDriverList').then(res => {
					if (res.code === 0) {
						this.personList = res.data;
					}
				  });
			},
			switch1Change: function(e) {
				console.log('switch1 发生 change 事件，携带值为', e.detail.value)
			},
			bindTo(name) {
				let token = this.$queue.getData("token");
				if (token) {
					uni.navigateTo({
						url: name
					})
				}

			},
			// 跳转添加页面
			handleAddContact() {
				if (this.personList.length >= this.maxContact) {
					uni.showToast({
						title: '最多添加3位联系人',
						icon: 'none'
					});
					return;
				}
				// 重置临时数据（避免编辑后残留）
				this.tempContact = {
					name: '',
					relationship: '',
					phone: '',
					avatarImg: ''
				};
				// 跳转添加页面（携带type=add标识）
				let token = this.$queue.getData("token");
				if (token) {
					uni.navigateTo({
						url: '/my/setting/addemergencycontact?type=add'
					});
				}
			},

			// 接收添加/编辑后的回调数据（假设通过全局事件或页面传参）
			receiveContact(contact) {
				console.log(contact, 'contactcontact');
				const index = this.personList.findIndex(item => item.id === contact.id);
				this.parson()
			},
			handleEdit(contact) {
			    // 填充临时数据（用于编辑页面回显）
			    this.tempContact = { ...contact };
			    // 跳转编辑页面（携带type=edit和id）
				let token = this.$queue.getData("token");
				if (token) {
					uni.navigateTo({ url: `/my/setting/addemergencycontact?type=edit&id=${contact.id}` });
				}
			},
			handleDelete(ids, index) {
			    uni.showModal({
			      title: '确认删除',
			      content: '是否删除该紧急联系人？',
			      success: (res) => {
			        if (res.confirm) {
						let data = {
							id: ids
						}
			           this.$Request.postT('/app/emergency/deleteEmergency', data)
						.then(res => {
						  if (res.code === 0) {
							uni.showToast({ title: '删除成功', icon: 'success' });
							this.parson()
						  } else {
							uni.showToast({ title: res.msg || '删除失败', icon: 'none' });
						  }
						})
						.catch(err => {
						  console.error('删除失败:', err);
						  uni.showToast({ title: '网络错误', icon: 'none' });
						});
			        }
			      }
			    });
			},
			bindOut() {
				uni.showModal({
					title: '退出登录',
					content: '是否退出登录',
					success: function(res) {
						if (res.confirm) {
							uni.setStorageSync('weixinPhone', false)
							uni.removeStorageSync('sendDataList')
							uni.removeStorageSync('sessionkey')
							uni.removeStorageSync("image_url")
							uni.removeStorageSync("userId")
							uni.removeStorageSync("status")
							uni.removeStorageSync("nickName")
							uni.removeStorageSync("token")
							uni.removeStorageSync("mobile")
							// uni.showModal({
							// 	showCancel: false,
							// 	title: '退出登录',
							// 	content: res.msg,
							// });
							uni.navigateBack()
							// uni.navigateBack({
							// 	success: () => {
							// 		let page = getCurrentPages().pop(); //跳转页面成功之后
							// 		if (page) {
							// 			let e = {};
							// 			page.onShow(); //执行上个页面的方法
							// 		};
							// 	}
							// })
							// console.log('用户点击确定');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			}
		}
	}
</script>

<style>
	page {
		background: #f0f0f0;
	}

	.list_box {
		display: flex;
		height: 110rpx;
		margin: 0 30rpx;
	}

	.box_left {
		flex: 1;
		display: flex;
		justify-content: left;
		align-items: center;
	}


	.use_image image {
		width: 60rpx;
		height: 60rpx;
	}

	.login_btn {
		width: 90%;
		margin: 0 auto;
		text-align: center;
		background: #fe6b01;
		height: 80rpx;
		border-radius: 16rpx;
		color: #ffffff;
		line-height: 80rpx;
		margin-top: 60rpx;
	}

	.titls2 {
		font-size: 32rpx;
		font-family: PingFang SC;
		color: #333333;
		padding: 0 30rpx;
	}

	.sj_name {
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 24rpx;
		color: #999999;
	}

	.boxs {
		background: #FFFFFF;
		border-radius: 24rpx;
		margin: 30rpx;
		padding: 30rpx;
	}
</style>