<template>
	<view class="device-tab">
		<!-- 设备列表 -->
		<scroll-view scroll-y @scrolltolower="handqixing" refresher-enabled @refresherrefresh="onRefresh" :refresher-triggered="isRefreshing" refresher-default-style="black" class="device-list">
			<view 
				v-for="(device, index) in deviceList" 
				:key="index"
				class="device-item"
				@click="handleDeviceClick(device)">
				<!-- 红色角标 -->
				<!-- <view class="device-badge">{{ device.badge || 3 }}</view> -->
				<!-- 灰色圆角头像 -->
				<view class="device-avatar">
					<image :src="device.productPicture" mode="aspectFill"></image>
				</view>
				<!-- 信息区 -->
				<view class="device-info">
					<text class="device-name">{{ device.name }}</text>
					<text class="device-name" style="font-weight: 400;">{{ device.productName}}</text>
					<text class="device-room" v-if="device.roomName">{{ device.roomName }}</text>
					<view class="device-status-bar">
						<image v-if="device.productType == 'HUB'" src="https://api.ccttiot.com/smartmeter/img/static/uQiIeJDApFO5xSvepE4k" mode="aspectFill"></image>
						<image src="https://api.ccttiot.com/smartmeter/img/static/uqQvPIflXlEoSaHjqc4q" mode="aspectFill"></image>
						<image style="" src="https://api.ccttiot.com/smartmeter/img/static/uQ7HTwLk1XDaV11mohr4" mode="aspectFill"></image>
						<!-- <image src="https://api.ccttiot.com/smartmeter/img/static/uJlfAizVTP6tBYDpTlab" mode=""></image>
						<image src="https://api.ccttiot.com/smartmeter/img/static/u8yd27DMbdMief7MsEaZ" mode=""></image>
						<image src="https://api.ccttiot.com/smartmeter/img/static/uCVxb1dSg0PmgDRNofWg" mode=""></image> -->
					</view>
				</view>
				<!-- 右侧箭头 -->
				<view class="device-arrow">›</view>
			</view>
			<view v-if="deviceList.length == 0" style="margin: auto;margin-top: 50rpx;width: 272rpx;height: 272rpx;border-radius: 50%;border: 1px solid #ccc;">
				<image style="width: 272rpx;height: 272rpx;" src="https://api.ccttiot.com/ad93702b02429b8adf394569460b8b2a-1758263546164.png" mode=""></image>
			</view>
			<view v-if="deviceList.length == 0" style="width: 600rpx;text-align: center;margin: auto;margin-top: 30rpx;">
				{{$i18n.t('hubwz')}}
			</view>
			<!-- 添加设备按钮 -->
			<view class="add-device-btn" @click="handleAddDevice">
				<text class="add-icon">+</text>
				<text>{{ $i18n.t('addDevice') }}</text>
			</view>
			
			<!-- <view class="add-device-btn" @click="openModal">
				<text class="add-icon">+</text>
				<text>add</text>
			</view> -->
		</scroll-view>
		
		<!-- 弹窗遮罩层 -->
		    <view v-if="showModal" class="modal-mask" @click="closeModal">
		      <!-- 弹窗内容 -->
		      <view class="modal-content" @click.stop>
		        <view class="modal-header">
		          <text class="modal-title"></text>
		          <view class="close-btn" @click="closeModal">×</view>
		        </view>
		        
		        <view class="modal-body">
		          <!-- 第一个输入框 -->
		          <view class="input-item">
		            <text class="input-label">网关mac：</text>
		            <input 
		              v-model="formData.name"
		              class="input-field"
		              placeholder="请输入网关mac"
		              placeholder-style="color: #ccc;"
		              type="text"
		            />
		          </view>
		          
		          <!-- 第二个输入框 -->
		          <view class="input-item">
		            <text class="input-label">设备mac：</text>
		            <input 
		              v-model="formData.phone"
		              class="input-field"
		              placeholder="请输入设备mac"
		              placeholder-style="color: #ccc;"
		              type="text"
		            />
		          </view>
		        </view>
		        
		        <!-- 确定按钮 -->
		        <view class="modal-footer">
		          <button 
		            class="confirm-btn" 
		            @click="handleConfirm"
		          >
		            确定
		          </button>
		        </view>
		      </view>
		    </view>
		
	</view>
</template>

<script>
	export default {
		name: 'DeviceTab',
		data() {
			return {
				deviceList: [],
				isRefreshing:false,
				kjid:'', // 添加空间ID
				pageNum:1,
				pageSize:10,
				total:0,
				hasMore:true,
				requestInProgress:false,
				
				showModal: false,
				      formData: {
				        name: '',
				        phone: ''
				      }
			}
		},
		computed: {
			// 计算当前语言，用于触发更新
			currentLanguage() {
				return this.$i18n.getCurrentLanguage()
			}
		},
		created() {
			this.updateDeviceList()
		},
		watch: {
			// 监听语言变化
			currentLanguage() {
				console.log('设备页面语言变化:', this.currentLanguage)
				this.updateDeviceList()
			}
		},
		mounted() {
			// 监听语言变化事件
			uni.$on('languageChanged', this.handleLanguageChange)
			// 监听空间切换事件
			uni.$on('spaceChanged', this.handleSpaceChanged)
			// 初始化空间ID并首次拉取列表
			if(uni.getStorageSync('kjid')){
				this.kjid = uni.getStorageSync('kjid')
				this.getDeviceList()
			}else{
				this.$http.get('/bst/space/list').then(res =>{
					if(res.code == 200 && res.rows.length > 0){
						this.kjid = res.rows[0].id
						uni.setStorageSync('kjid',this.kjid)
						this.getDeviceList()
					}
				})
			}
		},
		beforeDestroy() {
			// 移除事件监听
			uni.$off('languageChanged', this.handleLanguageChange)
			uni.$off('spaceChanged', this.handleSpaceChanged)
		},
		methods: {
			// 打开弹窗
			    openModal() {
			      this.showModal = true
			    },
			    
			    // 关闭弹窗
			    closeModal() {
			      this.showModal = false
			      this.resetForm()
			    },
			    
			    // 重置表单
			    resetForm() {
			      this.formData = {
			        name: '',
			        phone: ''
			      }
			    },
			    
			    // 确定按钮点击事件
			    handleConfirm() {
				  uni.setStorageSync('mac1',this.formData.name)
				  uni.setStorageSync('mac2',this.formData.phone)
			      this.closeModal()
			    },
			
			
			
			btnan(){
				uni.openAppAuthorizeSetting()
			},
			// 请求设备列表
			getDeviceList(){
				if(this.requestInProgress) return
				this.requestInProgress = true
				this.$http.get(`/bst/device/list?spaceId=${this.kjid}&pageNum=${this.pageNum}&pageSize=${this.pageSize}`).then((res) => {
					if (res.code == 200) {
						this.total = Number(res.total || 0)
						const rows = Array.isArray(res.rows) ? res.rows : []
						if(this.pageNum == 1){
							this.deviceList = rows
						}else{
							this.deviceList = this.deviceList.concat(rows)
						}
						this.hasMore = this.deviceList.length < this.total
					}
				}).catch(() => {
					// 如果请求失败，使用模拟数据
					this.updateDeviceList()
				}).finally(()=>{
					this.requestInProgress = false
					if(this.isRefreshing){
						this.isRefreshing = false
					}
				})
			},
			// 处理空间变化
			handleSpaceChanged(payload){
				try{
					this.kjid = (payload && payload.kjid) || uni.getStorageSync('kjid')
					this.pageNum = 1
					this.getDeviceList()
				}catch(e){
					console.warn('处理空间切换失败:', e)
				}
			},
			// 上拉加载更多
			handqixing() {
				if(!this.hasMore) return
				this.pageNum += 1
				this.getDeviceList()
			},
			// 下拉刷新
			onRefresh() {
				if(this.isRefreshing || this.requestInProgress) return
				this.isRefreshing = true
				this.pageNum = 1
				this.getDeviceList()
			},
			
			handleLanguageChange(lang) {
				console.log('设备页面语言切换事件:', lang)
				this.updateDeviceList()
			},
			updateDeviceList() {
				console.log('更新设备列表')
				// 强制更新组件
				this.$forceUpdate()
			},
			// 点击设备跳转到详情
			handleDeviceClick(device) {
				console.log(device);
				if(device.productType == 'HUB'){ //hub
					uni.navigateTo({
						url: '/subpackage/device/devicexq?id=' + device.id + '&mac=' + device.mac
					})
				}else if(device.productType == 'FIRE'){ //烟感
					uni.navigateTo({
						url: '/pages/device/yangan?id=' + device.id + '&mac=' + device.mac
					})
				}else if(device.productType == 'DOOR'){ //门磁
					uni.navigateTo({
						url:'/pages/device/mcgydevice?id=' + device.id
					})
				}else if(device.productType == 'INFRARED'){//人体红外传感器
					uni.navigateTo({
						url:'/subpackage/device/rentiredwai/index?id=' + device.id
					})
				}else if(device.productType == 'CONTROL'){//遥控器
					uni.navigateTo({
						url:'/subpackage/device/yaokongqi/index?id=' + device.id + '&mac=' + device.mac
					})
				}else if(device.productType == 'GLASS'){//玻璃破碎传感器
					uni.navigateTo({
						url:'/subpackage/device/boligan/index?id=' + device.id
					})
				}else if(device.productType == 'WATER'){//水浸传感器
					uni.navigateTo({
						url:'/subpackage/device/shuiqinganying/index?id=' + device.id
					})
				}
			},
			// 点击添加设备
			handleAddDevice() {
				this.$http.get(`/bst/room/list?spaceId=${this.kjid}&pageNum=${this.pageNum}&pageSize=${this.pageSize}`).then((res) => {
					if (res.code == 200) {
						if(res.total > 0){
							this.$http.get(`/bst/device/list?spaceId=${this.kjid}&pageNum=${this.pageNum}&pageSize=${this.pageSize}`).then(res =>{
								if(res.code == 200){
									if(res.rows.length == 0){
										uni.navigateTo({
											url:'/pages/device/addhub'
										})
									}else{
										uni.navigateTo({
											url:'/subpackage/device/adddevice'
										})
									}
								}else{
									uni.showToast({
										title: res.msg,
										icon: 'none',
										duration:3000
									})
								}
							})
						}else{
							uni.navigateTo({
								url:'/pages/room/addroom'
							})
						}
					}
				})
				// 先判断是否有无HUB设备，没有则必须先添加HUB设备才能进行下一步
				// this.$http.get(`/bst/device/list?spaceId=${this.kjid}&pageNum=${this.pageNum}&pageSize=${this.pageSize}`).then(res =>{
				// 	if(res.code == 200){
				// 		if(res.rows.length == 0){
				// 			uni.navigateTo({
				// 				url:'/pages/device/addhub'
				// 			})
				// 		}else{
				// 			// 判断有无房间没有房间先添加房间才能添加设备
				// 			this.$http.get(`/bst/room/list?spaceId=${this.kjid}&pageNum=${this.pageNum}&pageSize=${this.pageSize}`).then((res) => {
				// 				if (res.code == 200) {
				// 					if(res.total > 0){
				// 						uni.navigateTo({
				// 							url:'/subpackage/device/adddevice'
				// 						})
				// 					}else{
				// 						uni.navigateTo({
				// 							url:'/pages/room/addroom'
				// 						})
				// 					}
				// 				}
				// 			})
				// 		}
				// 	}else{
				// 		uni.showToast({
				// 			title: res.msg,
				// 			icon: 'none',
				// 			duration:3000
				// 		})
				// 	}
				// })
			}
		}
	}
</script>s

<style lang="scss" scoped>
	.container {
	  padding: 100rpx 30rpx;
	}
	
	/* 遮罩层 */
	.modal-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: 999;
	}
	
	/* 弹窗内容 */
	.modal-content {
	  width: 600rpx;
	  background-color: #fff;
	  border-radius: 20rpx;
	  overflow: hidden;
	  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
	}
	
	/* 弹窗头部 */
	.modal-header {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  padding: 30rpx;
	  border-bottom: 2rpx solid #f5f5f5;
	  
	  .modal-title {
	    font-size: 32rpx;
	    font-weight: bold;
	    color: #333;
	  }
	  
	  .close-btn {
	    width: 40rpx;
	    height: 40rpx;
	    font-size: 40rpx;
	    color: #999;
	    display: flex;
	    align-items: center;
	    justify-content: center;
	    cursor: pointer;
	    
	    &:active {
	      opacity: 0.7;
	    }
	  }
	}
	
	/* 弹窗主体 */
	.modal-body {
	  padding: 40rpx 30rpx;
	  
	  .input-item {
	    display: flex;
	    align-items: center;
	    margin-bottom: 40rpx;
	    
	    &:last-child {
	      margin-bottom: 0;
	    }
	    
	    .input-label {
	      width: 120rpx;
	      font-size: 28rpx;
	      color: #333;
	      flex-shrink: 0;
	    }
	    
	    .input-field {
	      flex: 1;
	      height: 80rpx;
	      border: 2rpx solid #e0e0e0;
	      border-radius: 10rpx;
	      padding: 0 20rpx;
	      font-size: 28rpx;
	      color: #333;
	      background-color: #fff;
	      
	      &:focus {
	        border-color: #000;
	      }
	    }
	  }
	}
	
	/* 弹窗底部 */
	.modal-footer {
	  padding: 0 30rpx 40rpx;
	  
	  .confirm-btn {
	    width: 100%;
	    height: 80rpx;
	    background-color: #000;
	    color: #fff;
	    border-radius: 10rpx;
	    font-size: 32rpx;
	    border: none;
	    display: flex;
	    align-items: center;
	    justify-content: center;
	    
	    &:disabled {
	      background-color: #c0c0c0;
	      color: #fff;
	    }
	    
	    &:active:not(:disabled) {
	      opacity: 0.9;
	    }
	  }
	}
	
	
	
	
	.device-tab {
		// padding: 20rpx;
		// background: #f5f5f5;
	}
	.device-list {
		margin-bottom: 30rpx;
		height: 76vh;
		overflow: scroll;
	}
	.device-item {
		position: relative;
		display: flex;
		align-items: center;
		margin: auto;
		box-sizing: border-box;
		margin-top: 20rpx;
		background: #fff;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		padding: 30rpx 40rpx;
		box-shadow: -2rpx 2rpx 6rpx rgba(0, 0, 0, 0.08);
		transition: all 0.2s ease;
		width: 700rpx;
	}
	.device-item:active {
		transform: scale(0.98);
		background: #f8f8f8;
		box-shadow: 0 1rpx 5rpx rgba(0,0,0,0.1);
	}
	.device-badge {
		position: absolute;
		top: 30rpx;
		left: 0;
		background: #ff4444;
		color: #fff;
		font-size: 22rpx;
		border-radius:0 8rpx 8rpx 0;
		padding: 4rpx 12rpx;
		z-index: 1;
	}
	.device-avatar {
		width: 128rpx;
		height: 128rpx;
		background: #e0e0e0;
		border-radius: 20rpx;
		overflow: hidden;
		margin-right: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 10rpx;
		image{
			width: 128rpx;
			height: 128rpx;
		}
	}
	.device-icon {
		font-size: 40rpx;
	}
	.device-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}
	.device-name {
		font-size: 30rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 8rpx;
	}
	.device-room {
		font-size: 26rpx;
		color: #999;
		margin-bottom: 12rpx;
	}
	.device-status-bar {
		display: flex;
		align-items: center;
		image{
			width: 44rpx;
			height: 44rpx;
		}
	}
	.status-icon {
		font-size: 28rpx;
		color: #666;
		margin-right: 16rpx;
	}
	.device-arrow {
		font-size: 66rpx;
		color: #bbb;
		margin-left: 20rpx;
	}
	.add-device-btn {
		margin: 40rpx auto 0 auto;
		width: 700rpx;
		height: 80rpx;
		border: 2rpx solid #bbb;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		color: #333;
		background: #fff;
		transition: all 0.2s ease;
		.add-icon {
			font-size: 38rpx;
			margin-right: 16rpx;
		}
	}
	.add-device-btn:active {
		transform: scale(0.95);
		background: #f0f0f0;
		border-color: #999;
	}
</style> 