<template>
	<view>
		<!-- #ifdef MP-WEIXIN -->
		<!-- v-if="shangxian!='是'" -->
	<!-- 	<view class="list_box" @click="bindMsg">
			<view class="box_left">订阅消息</view>
			<view class="jia">
				<u-icon name="plus" color="#FFFFFF"></u-icon>
			</view>
		</view> -->

		<!-- #endif -->

		<!-- <view class="list_box" v-if="shangxian!='是'" @click="bindTo('/my/feedback/feedback')">
			<view class="box_left">意见反馈</view>
			<image src="../../static/my/icon_go.png" style="width: 11rpx;height: 20rpx;"></image>
		</view>
		<view class="list_box" @click="bindTo('/my/setting/mimi')">
			<view class="box_left">隐私政策</view>
			<image src="../../static/my/icon_go.png" style="width: 11rpx;height: 20rpx;"></image>
		</view>
		<view class="list_box" @click="bindTo('/my/setting/xieyi')">
			<view class="box_left">用户协议</view>
			<image src="../../static/my/icon_go.png" style="width: 11rpx;height: 20rpx;"></image>
		</view>
		<view class="list_box" @click="bindTo('/my/setting/logOff')">
			<view class="box_left">用户注销</view>
			<image src="../../static/my/icon_go.png" style="width: 11rpx;height: 20rpx;"></image>
		</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="#00c18a!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">
				<view style="line-height: 40rpx;">
					<view>消息推送权限</view>
					<view style="color: #999;font-size: 24rpx;">管理通知和消息接收</view>
				</view>
				<view class="order_money">
					<switch color="#00c18a!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 + 'imgs/renshu.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 + 'imgs/update.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 + 'imgs/delete.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 {
				shangxian: '是',
				arr: [],
				// 定义人员列表数据
				personList: [],
				maxContact: 3, // 最大联系人数量
				// 添加/编辑时的临时数据
				tempContact: {
					name: '',
					relationship: '',
					phone: '',
					remark: '',
					// userId: null,
				},
				globalImages: ''
			}
		},
		onShow() {
		  uni.$on('updateContact', (contact) => {
		    this.receiveContact(contact); // 调用之前定义的接收方法
		  });
		},
		onLoad() {
			this.$Request.getT('/app/common/type/428').then(res => { //师傅端订单状态通知 428

				if (res.code == 0) {
					if (res.data && res.data.value) {
						this.arr.push(res.data.value)
					}
				}
			})
			this.$Request.getT('/app/common/type/429').then(res => { //师傅新订单通知 429
				if (res.code == 0) {
					if (res.data && res.data.value) {
						this.arr.push(res.data.value)
					}
				}
			})
			
			this.parson()
			this.shangxian = uni.getStorageSync('shangxian')
			waitForGlobalImages().then((path) => {
			    console.log('✅ 全局图片路径:', path)
			    this.globalImages = path
			  })
		},
		onUnload() {
		  uni.$off('updateContact'); // 移除监听避免内存泄漏
		},
		methods: {
			bindMsg() {
				// #ifdef MP-WEIXIN
				if (uni.getStorageSync('sendMsg')) {
					uni.requestSubscribeMessage({
						tmplIds: this.arr,
						success(re) {
							// console.log(re,'**********')
							var datas = JSON.stringify(re);
							if (datas.indexOf("accept") != -1) {
								console.log(re)
								uni.showToast({
									title: '订阅成功',
									icon: 'none'
								})
							}
						},
						fail: (res) => {
							console.log(res)
						}
					})
				}
				// #endif
			},
			bindTo(name) {
				let token = this.$queue.getData("token");
				if (token) {
					uni.navigateTo({
						url: name
					})
				}

			},
			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)
			},
			// 跳转添加页面
			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.clearStorage();
							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('用户点击取消');
							uni.showToast({
								title: '取消退出登录',
								icon: 'none'
							})
						}
					}
				});
			}
		}
	}
</script>

<style>
	.jia {
		background: #346EF6;
		border-radius: 50%;
		width: 55rpx;
		height: 55rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}


	page {
		background: #f0f0f0;
	}

	.list_box {
		display: flex;
		align-items: center;
		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: #00c18a;
		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>