<template>
	<view class="device-detail">
		<app-top-push-notice />
		<!-- 顶部导航 -->
            <view class="tabback">
            <view class="rtjt" @click="btnback" style="font-size: 50rpx;">←</view>
			<view class="name">{{$i18n.t('userSettingsTitle')}}</view>
			<view style="width: 36rpx;"></view>
		</view>
		<view class="guanli">
			<view class="hezi" style="border-bottom: 1px solid #D8D8D8;">
				<view class="lt">
					{{$i18n.t('admin')}}
				</view>
				<switch :checked="permissionStates.admin" color="#3D3D3D" @change="onPermissionChange('admin', $event.detail.value)" />
			</view>
			<!-- <view class="hezi">
				<view class="lt">
					{{$i18n.t('notificationSettings')}}
				</view>
				<image style="width: 48rpx;height: 48rpx;" src="https://api.ccttiot.com/smartmeter/img/static/uGFlq3Y6VPGsCUv6lfid" mode=""></image>
			</view> -->
		</view>
		<!-- <view class="guanli">
			<view class="hezi">
				<view class="lt">
					{{$i18n.t('notifyServerDisconnectNoAlarm')}}
				</view>
				<switch checked="true" color="#3D3D3D" />
			</view>
		</view>
		<view class="" style="width: 100%;font-size: 26rpx;color: #727272;margin-top: 16rpx;padding-left: 32rpx;">
		{{$i18n.t('privacyManagerDesc')}}
		</view> -->
         <view class="" style="text-align: left;font-size: 26rpx;color: #727272;margin-top: 36rpx;padding-left: 32rpx;">
	        	{{$i18n.t('permissions')}}
         </view> 
		 <view class="guanli">
		 	<view class="hezi" style="border-bottom: 1px solid #D8D8D8;">
		 		<view class="lt">
					{{$i18n.t('securityStatusChange')}}
		 		</view>
					<switch :checked="permissionStates.securityStateChange" color="#3D3D3D" @change="onPermissionChange('securityStateChange', $event.detail.value)" />
		 	</view>
		 	<view class="hezi" style="border-bottom: 1px solid #D8D8D8;">
		 		<view class="lt">
					{{$i18n.t('emergencyMode')}}
		 		</view>
					<switch :checked="permissionStates.panic" color="#3D3D3D" @change="onPermissionChange('panic', $event.detail.value)" />
		 	</view>
			<view class="hezi" style="border-bottom: 1px solid #D8D8D8;">
				<view class="lt">
					{{$i18n.t('homeAutomationControl')}}
				</view>
				<switch :checked="permissionStates.automationControl" color="#3D3D3D" @change="onPermissionChange('automationControl', $event.detail.value)" />
			</view>
			<view class="hezi" style="border-bottom: 1px solid #D8D8D8;">
				<view class="lt">
					{{$i18n.t('viewRoomsAndDevices')}}
				</view>
				<switch :checked="permissionStates.viewDeviceAndRooms" color="#3D3D3D" @change="onPermissionChange('viewDeviceAndRooms', $event.detail.value)" />
			</view>
			<view class="hezi">
				<view class="lt">
					{{$i18n.t('soundPromptActivation')}}
				</view>
				<switch :checked="permissionStates.chimeActivation" color="#3D3D3D" @change="onPermissionChange('chimeActivation', $event.detail.value)" />
			</view>
		 </view>
		 	<view class="delyh" @click="btndel">
		 		{{$i18n.t('deleteUser')}}
		 	</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				id:'',
				xqobj:{},
			// 权限开关状态
			permissionStates: {
				admin: false,                   // admin
				securityStateChange: false,    // security_state_change
				panic: false,                   // panic  
				automationControl: false,       // automation_control
				viewDeviceAndRooms: false,      // view_device_and_rooms
				chimeActivation: false          // chime_activation
			},
			// 当前用户的权限数组
			currentPermissions: [],
			role:false
			}
		},
		onLoad(option) {
			this.id = option.id
			this.getxq()
		},
		methods: {
			// 处理权限数据，设置开关状态
			processPermissions(permissions) {
				// 权限映射关系
				const permissionMap = {
					'admin': 'admin',
					'security_state_change': 'securityStateChange',
					'panic': 'panic',
					'automation_control': 'automationControl', 
					'view_device_and_rooms': 'viewDeviceAndRooms',
					'chime_activation': 'chimeActivation'
				}
				// 保存当前权限数组
				this.currentPermissions = permissions ? [...permissions] : [];
				// 重置所有权限状态为false
				Object.keys(this.permissionStates).forEach(key => {
					this.permissionStates[key] = false;
				});
				// 根据传入的权限数组设置对应状态为true
				if (permissions && Array.isArray(permissions)) {
					permissions.forEach(permission => {
						if (permissionMap[permission]) {
							this.permissionStates[permissionMap[permission]] = true;
						}
					});
				}
			},
			// 处理开关点击事件
			onPermissionChange(permissionKey, checked) {
				const permissionMap = {
					'admin': 'admin',
					'securityStateChange': 'security_state_change',
					'panic': 'panic',
					'automationControl': 'automation_control',
					'viewDeviceAndRooms': 'view_device_and_rooms',
					'chimeActivation': 'chime_activation'
				};
				const apiPermissionKey = permissionMap[permissionKey];
				if (!apiPermissionKey) return;
				// 更新本地状态
				this.permissionStates[permissionKey] = checked;
				// 更新权限数组
				if (checked) {
					// 开启：添加到权限数组
					if (!this.currentPermissions.includes(apiPermissionKey)) {
						this.currentPermissions.push(apiPermissionKey);
					}
				} else {
					// 关闭：从权限数组中移除
					const index = this.currentPermissions.indexOf(apiPermissionKey);
					if (index > -1) {
						this.currentPermissions.splice(index, 1);
					}
				}
				// 发送更新请求
				this.updateUserPermissions();
			},
			// 更新用户权限
			updateUserPermissions() {
				// 根据admin权限状态确定role
				const hasAdminPermission = this.currentPermissions.includes('admin');
				const userRole = hasAdminPermission ? 'admin' : 'user';
				console.log('权限数组:', this.currentPermissions);
				console.log('用户角色:', userRole);
				const updateData = {
					id: this.id,
					spaceId: this.xqobj.spaceId,
					userId: this.xqobj.userId,
					role: userRole,
					permissions: [...this.currentPermissions]
				};
				this.$http.put(`/bst/spaceUser`, updateData).then(res => {
					if (res.code == 200) {
						// uni.showToast({
						// 	title: res.msg,
						// 	icon: 'success',
						// 	duration: 2000
						// });
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 3000
						});
						// 失败时重新获取数据恢复状态
						this.getxq();
					}
				}).catch(err => {
					uni.showToast({
						title: '网络错误',
						icon: 'none',
						duration: 3000
					});
					// 错误时重新获取数据恢复状态
					this.getxq();
				});
			},
			// 点击删除成员
			btndel(){
				uni.showModal({
					title: this.$i18n.t('deleteUserConfirmTitle'),
					content: this.$i18n.t('deleteUserConfirmContent'),
					cancelText: this.$i18n.t('modalCancel'),
					confirmText: this.$i18n.t('modalConfirm'),
					success: (res) => {
						if(res.confirm){
							this.$http.delete(`/bst/spaceUser/${this.id}`).then(res =>{
								if(res.code == 200){
									uni.showToast({
										title: res.msg,
										icon: 'success',
										duration:3000	
									})
									setTimeout(()=>{
										uni.navigateBack()
									},1500)
								}else{
									uni.showToast({
										title: res.msg,
										icon: 'none',
										duration:3000
									})
								}
							})
						}
					}
				})
			},
			// 请求详细信息
			getxq(){
				this.$http.get(`/bst/spaceUser/${this.id}`).then(res =>{
					if(res.code == 200){
						this.xqobj = res.data
						// 处理权限数据，设置开关状态
						if(res.data.permissions) {
							this.processPermissions(res.data.permissions)
						}
						// 根据admin权限设置role状态
						this.role = this.permissionStates.admin;
					}
				})
			},
			// 点击返回上一级
			btnback(){
				uni.navigateBack()
			}
		}
	}
</script>

<style scoped lang="less">
	.delyh{
		width: 750rpx;
		height: 118rpx;
		background: #FFFFFF;
		border-radius: 0rpx 0rpx 0rpx 0rpx;
		text-align: center;
		line-height: 118rpx;
		font-size: 36rpx;
		color: #FF5353;
		position: fixed;
		left: 0;
		bottom: 0;
	}
	.guanli{
		background-color: #fff;
		margin-top: 32rpx;
		.hezi{
			display: flex;
			justify-content: space-between;
			height: 122rpx;
			align-items: center;
			padding: 0 32rpx;
			.lt{
				font-size: 30rpx;
				color: #3D3D3D;
			}
		}
	}
	.device-detail{
		background-color: #F3F5F6;
	}
	.tabback {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		height: 126rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
		background-color: #fff;
		margin-top: 80rpx;
		.rtjt {
			font-size: 36rpx;
			color: #333;
		}
		.name {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
	}

	.device-detail {
		height: 93vh;
	}
	// 顶部导航样式（贴近系统样式）
	.tabback {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 98rpx;
		padding: 0 24rpx;
		background: #fff;

		.name {
			font-size: 32rpx;
			color: #333;
		}

		.rtjt {
			font-size: 36rpx;
			color: #333;
		}
	}

</style>