<template>
	<page-meta>
		<navigation-bar :title="$tt('navBar.deviceList')" background-color="#F1F3F9" front-color="#000000" />
	</page-meta>

	<view class="scene-device-wrap">
		<u-sticky>
			<view class="nav-bar">
				<view class="left-wrap">
					<view v-if="!isSearch" style="margin-right: 20rpx;">
						<u-icon name="search" size="27" @click="isSearch = true"></u-icon>
					</view>
					<view v-else style="width: 100%;">
						<!-- #ifndef APP-NVUE -->
						<u-input :customStyle="{ padding: '17rpx 36rpx', background: '#FFFFFF' }"
							v-model="queryParams.deviceName" :placeholder="$tt('group.inputContent')" shape="circle"
							@clear="handleClearSearch" clearable>
						<!-- #endif -->
							<!-- #ifdef APP-NVUE -->
							<u--input :customStyle="{ padding: '17rpx 36rpx', background: '#FFFFFF' }"
								v-model="queryParams.deviceName" :placeholder="$tt('group.inputContent')" shape="circle"
								@clear="handleClearSearch" clearable>
							<!-- #endif -->
								<template slot="prefix">
									<u-icon name="search" color="rgb(192, 196, 204)" size="26"
										@click="isSearch = false"></u-icon>
								</template>
								<template slot="suffix">
									<view style="display: flex; flex-direction: row; align-items: center;">
										<span
											style="width: 0px; height: 14px; border: 1px solid #000000; opacity: 0.1;"></span>
										<span
											style="font-size: 14px; font-weight: 400; color: #3378FE; margin-left: 24rpx;"
											@click="handleSearch">{{$tt('common.search')}}</span>
									</view>
								</template>
						<!-- #ifndef APP-NVUE -->
						</u-input>
						<!-- #endif -->
						<!-- #ifdef APP-NVUE -->
						</u--input>
						<!-- #endif -->
					</view>
				</view>

			</view>
			<view class="tab-wrap">

				<view class="tab-flex">
					<u-tabs :list="statusGroup" :scrollable="true" lineWidth="40" lineHeight="2" lineColor="transparent"
						:duration="100" :activeStyle="{ fontSize: '36rpx', color: '#3378FE', fontWeight: 'bold' }"
						@change="handleStatusChange">
					</u-tabs>
					<view class="right-wrap" @click="handleNextStep">{{$tt('product.next')}}</view>
				</view>

			</view>


			<view class="group" @click="gotoGroup(type)">
				<view class="group-title">
					<span class="text">{{ $tt('group.equipment') }}</span>
					<view class="icon">
						<u-icon color="#3378FE" name="arrow-down-fill" size="10"></u-icon>
					</view>

				</view>

				<span class="groupName"> {{ groupName === "" ? "全部": groupName }}</span>
			</view>

		</u-sticky>
		<view class="container-wrap">
			<u-checkbox-group v-model="devices" :key="checkboxKey">
				<view class="group-wrap">
					<u-cell-group :border="false">
						<view class="cell-wrap" v-for="(item,index) in list" :key="index">
							<u-cell :border="false">
								<view slot="title" class="slot-title">
									<u--image :src="getImageUrl(item)" radius="4" width="28" height="28"></u--image>
									<view>
										<text class="cell-text">{{item.deviceName}}</text>
										<view class="cell-flex">
											<view class="cell-text">
												<u--text v-if="item.status == 3 && item.rssi >= '-55'" lines="1"
													prefixIcon="/static/common/wifi_4.png"
													iconStyle="margin-right:6rpx;" size="12"
													:text="statusTxt(item.status)"></u--text>
												<u--text
													v-else-if="item.status == 3 && item.rssi >= '-70' && item.rssi < '-55'"
													lines="1" prefixIcon="/static/common/wifi_3.png"
													iconStyle="margin-right:6rpx;" size="12"
													:text="statusTxt(item.status)"></u--text>
												<u--text
													v-else-if="item.status == 3 && item.rssi >= '-85' && item.rssi < '-70'"
													lines="1" prefixIcon="/static/common/wifi_2.png"
													iconStyle="margin-right:6rpx;" size="12"
													:text="statusTxt(item.status)"></u--text>
												<u--text
													v-else-if="item.status == 3 && item.rssi >= '-100' && item.rssi < '-85'"
													lines="1" prefixIcon="/static/common/wifi_1.png"
													iconStyle="margin-right:6rpx;" size="12"
													:text="statusTxt(item.status)"></u--text>
												<u--text v-else lines="1" prefixIcon="/static/common/wifi_0.png"
													iconStyle="margin-right:6rpx;" size="12"
													:text="statusTxt(item.status)">
												</u--text>
											</view>
											<view class="cell-text">
												<u--text lines="1" prefixIcon="/static/common/shadow_active.png"
													iconStyle="margin-right:6rpx;" size="12" v-if="item.isShadow == 1"
													:text="$tt('home.shadow')">
												</u--text>
												<u--text lines="1" prefixIcon="/static/common/shadow_disable.png"
													iconStyle="margin-right:6rpx;" size="12" v-else
													:text="$tt('home.shadow')"></u--text>
											</view>
										</view>

									</view>

								</view>
								<view slot="value">
									<u-checkbox :name="item.serialNumber" iconSize="16"></u-checkbox>
								</view>
							</u-cell>
						</view>
					</u-cell-group>
				</view>
			</u-checkbox-group>
			<u-loadmore :status="loadmoreStatus" v-if="total > queryParams.pageSize"
				:loading-text="$tt('scene.tryingToLoad')" :loadmoreText="$tt('scene.gentlyPullUp')"
				:nomoreText="$tt('scene.nothingLeft')" marginTop="20" />
		</view>
		<view class="other">
			<u-empty mode="data" :show="total === 0" marginTop="60" :text="$tt('scene.emptyData')"></u-empty>

			<u-popup :show="isModel" :round="5" mode="bottom" bgColor="#eef3f7" :closeOnClickOverlay="true"
				@close="isModel = false">
				<view class="model-popup-wrap">
					<view class="title">{{$tt('product.selectThingModel')}}</view>
					<u-radio-group v-model="modelType">
						<view class="cell-group-wrap">
							<u-cell-group :border="false">
								<view class="cell-wrap">
									<u-cell :title="$tt('product.attribute')" :name="1" :border="false" isLink
										@click="goToModelList"></u-cell>
								</view>
								<view class="cell-wrap">
									<u-cell :title="$tt('product.function')" :name="2" :border="false" isLink
										@click="goToModelList"></u-cell>
								</view>
								<view v-if="type === 'trigger'" class="cell-wrap">
									<u-cell :title="$tt('product.event')" :name="3" :border="false" isLink
										@click="goToModelList"></u-cell>
								</view>
								<view v-if="type === 'trigger'" class="cell-wrap">
									<u-cell :title="$tt('sceneDetail.deviceOnline')" :border="false">
										<view slot="value" class="u-slot-value">
											<u-radio shape="circle" :name="5"></u-radio>
										</view>
									</u-cell>
								</view>
								<view v-if="type === 'trigger'" class="cell-wrap">
									<u-cell :title="$tt('sceneDetail.Equipment')" :border="false">
										<view slot="value" class="u-slot-value">
											<u-radio shape="circle" :name="6"></u-radio>
										</view>
									</u-cell>
								</view>
							</u-cell-group>
						</view>
					</u-radio-group>
					<view v-if="type === 'trigger'" class="btn">
						<u-button type="primary" :customStyle="{ height: '96rpx' }"
							@click="handleConfirmMore">{{$tt('sceneDetail.complete')}}</u-button>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	import {
		listDeviceShort
	} from '@/apis/modules/device.js';
	import {
		navigateBackTo
	} from '@/utils/common.js';

	export default {
		data() {
			return {
				type: 'trigger',
				editIndex: null, // null 代表新增
				isSearch: true,
				isModel: false,
				modelType: null, // 物模类型
				// 状态列表
				statusGroup: [{
						id: null,
						name: this.$tt('home.all')
					},
					{
						id: 3,
						name: this.$tt('home.onLine')
					},
					{
						id: 2,
						name: this.$tt('home.disabled')
					},
					{
						id: 4,
						name: this.$tt('home.offline')
					},
					{
						id: 1,
						name: this.$tt('home.notActive')
					}
				],
				queryParams: {
					productId: null,
					groupId: null,
					pageNum: 1,
					pageSize: 11,
					deviceName: '',
					status: null
				},
				list: [], // 产品列表
				total: 0,
				loadmoreStatus: 'loadmore', // 刷新和加载相关
				devices: [], // 选中设备
				checkboxKey: 0,
				productName: '',
				//选中的分组
				groupName: ''
			};
		},
		watch: {
			devices(newVal, oldVal) {
				const action = uni.getStorageSync(this.type);

				if (newVal.length === 0) {
					//不存在开始筛选
					this.queryParams.productId = "";
					this.productName = "";
					this.queryParams.pageNum = 1
					this.list = []
					this.getDeviceDatas();
					//刷新列表并且确保再次选择时候及逆行监听筛选
					this.checkboxKey++
				}
				if (newVal.length === 1) {
					if (!Number.isNaN(this.editIndex) && this.editIndex != null && this.editIndex !== "" && this
						.checkboxKey === 1) {
						// 不进行多次筛选
						return
					}

					const row = this.list.find(item => {
						return item.serialNumber === newVal[0]
					});
					if (row) {
						//存在开始筛选
						this.queryParams.productId = row.productId ? row.productId : this.queryParams.productId;
						this.queryParams.pageNum = 1

						this.productName = row.productName ? row.productName : this.productName;
						this.list = []
						this.getDeviceDatas();

					}
				}
				// }

			},
		},
		onLoad(option) {
			this.type = option.type;
			this.editIndex = option.editIndex ? Number(option.editIndex) : null
			const trigger = uni.getStorageSync('trigger');
			const action = uni.getStorageSync('action');
			// 触发
			if (this.type === 'trigger' && trigger.source === 1) {
				if (trigger.groupId && trigger.groupId !== '') {
					this.queryParams.groupId = trigger.groupId
					this.groupName = trigger.groupName

				}
				this.fetchExist(trigger)
			}
			//动作
			if (this.type !== 'trigger' && action.source === 1) {
				if (action.groupId && action.groupId !== '') {
					this.queryParams.groupId = action.groupId
					this.groupName = action.groupName
					this.productName = trigger.productName
				}
				this.fetchExist(action)
			}

		},

		methods: {
			//查询赋值
			async fetchExist(trigger) {
				// 赋值productId
				this.queryParams.productId = trigger.productId;
				this.productName = trigger.productName
				this.list = [];
				await this.getDeviceDatas();
				if (!Number.isNaN(this.editIndex) && this.editIndex != null && this.editIndex !== "") {

					// 赋值devices保证回显
					this.devices = [...trigger.deviceNums];
					//确保列表刷新
					this.checkboxKey++

				}

			},
			// 获取区设备列表
			async getDeviceDatas() {
				try {
					const res = await listDeviceShort(this.queryParams);
					const {
						rows,
						total
					} = res;

					// 数据合并前增加空值保护
					if (Array.isArray(rows)) {
						this.list = [...this.list, ...rows];
					}

					this.total = total;
					return res;
				} catch (err) {
					console.error('数据加载失败:', err);
					throw err;
				}
			},

			handleSearch() {
				this.list = [];
				this.queryParams.pageNum = 1;
				this.getDeviceDatas();
			},
			handleClearSearch() {
				this.handleSearch();
			},
			// 状态改变事件
			handleStatusChange(item) {
				this.list = [];
				this.queryParams.status = item.id;
				this.queryParams.pageNum = 1;
				this.getDeviceDatas();
			},
			// 获取设备图片
			getImageUrl(item) {
				if (item.imgUrl) {
					return item.imgUrl;
				} else {
					if (item.deviceType === 1) {
						return '/static/common/device.png';
					} else if (item.deviceType === 2) {
						return '/static/common/gateway.png';
					} else if (item.deviceType === 3) {
						return '/static/common/video.png';
					} else {
						return '';
					}
				}
			},
			// 设备状态
			statusTxt(status) {
				let txt = '';
				switch (status) {
					case 1:
						txt = this.$tt('home.notActive');
						break;
					case 2:
						txt = this.$tt('home.disabled');
						break;
					case 3:
						txt = this.$tt('home.onLine');
						break;
					case 4:
						txt = this.$tt('home.offline');
						break;
				}
				return txt;
			},
			// 下拉刷新
			onPullDownRefresh() {
				this.list = [];
				this.queryParams.pageNum = 1;
				// 模拟网络请求
				setTimeout(x => {
					this.getDeviceDatas();
					uni.stopPullDownRefresh();
				}, 1000);
			},

			// 上拉加载
			onReachBottom() {
				this.loadmoreStatus = 'loading';
				this.queryParams.pageNum = ++this.queryParams.pageNum;
				// 模拟网络请求
				setTimeout(() => {
					if ((this.queryParams.pageNum - 1) * this.queryParams.pageSize >= this.total) {
						this.loadmoreStatus = 'nomore';
					} else {
						this.loadmoreStatus = 'loading';
						this.getDeviceDatas();
					}
				}, 1000);
			},
			//前往分组页面
			gotoGroup(type) {
				let action = uni.getStorageSync(this.type);
			

				if (type === "trigger") {
				

					uni.$u.route('/pagesA/scene/group/groupList', {
						type: type,
						editIndex: action.groupId === "" ? null : 1,
						editDevice: this.editIndex || this.editIndex === 0 ? this.editIndex : null
					});
				}
				if (type === "action") {
					uni.$u.route('/pagesA/scene/group/groupList', {
						type: type,
						editIndex: action.groupId === "" ? null : 1,
						editDevice: this.editIndex || this.editIndex === 0 ? this.editIndex : null
					});
				}


			},
			// 下一步
			handleNextStep() {
				if (this.devices.length !== 0) {
					this.isModel = true;
					let action = uni.getStorageSync(this.type);
					action = {
						...action,
						deviceCount: this.devices.length,
						deviceNums: this.devices,
						productId: this.queryParams.productId,
						productName: this.productName
					};

					uni.setStorageSync(this.type, action);

				} else {
					uni.showToast({
						icon: 'none',
						title: this.$tt('product.selectDevice')
					});
				}
			},
			// 物模跳转
			goToModelList({
				name
			}) {
				let action = uni.getStorageSync(this.type);
				action = {
					...action,
					type: name,
					arrayIndex: '',
					parentId: ''
				};
				uni.setStorageSync(this.type, action);
				uni.$u.route('/pagesA/scene/product/model', {
					type: this.type,
					editIndex: this.editIndex || this.editIndex === 0 ? this.editIndex : null
				});
			},
			// 选择物模
			handleConfirmMore() {
				if (!this.modelType) {
					uni.showToast({
						icon: 'none',
						title: this.$tt('product.selectThingsModels')
					});
					return
				}
				let action = uni.getStorageSync(this.type);
				//action = [...action,id:]
				action = {
					...action,
					type: this.modelType,
					id: '',
					name: '',
					operator: '',
					value: '',
					parentId: '', // 父类id
					parentName: '', // 父类名称
				};
				uni.setStorageSync(this.type, action);
				// 更新或者插入新的触发或者执行
				let {
					triggers,
					actions,
					...res
				} = uni.getStorageSync('sceneData');
				if (Number.isNaN(this.editIndex) || this.editIndex === null) {
					if (this.type === 'trigger') {
						triggers.push(action);
					} else {
						actions.push(action);
					}
					uni.setStorageSync('sceneData', {
						triggers,
						actions,
						...res
					});
				} else {
					if (this.type === 'trigger') {
						let list = triggers.map((item, i) => {
							if (i == this.editIndex) {
								return action
							} else {
								return item
							}
						});
						uni.setStorageSync('sceneData', {
							triggers: [...list],
							actions,
							...res
						});
					} else {
						let list = actions.map((item, i) => {
							if (i == this.editIndex) {
								return action
							} else {
								return item
							}
						});
						uni.setStorageSync('sceneData', {
							triggers,
							actions: [...list],
							...res
						});
					}
				}
				this.isModel = false;
				uni.setStorageSync('callback', true);
				navigateBackTo('/pagesA/scene/detail');
			}
		}
	};
</script>

<style lang="scss">
	page {
		height: 100%;
		background: $uni-bg-color-grey;
	}
</style>
<style lang="scss" scoped>
	.scene-device-wrap {
		.nav-bar {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			padding: 24rpx 30rpx 28rpx;
			height: 74rpx;
			background: $uni-bg-color-grey;

			.left-wrap {
				flex: 1;
			}


		}

		.tab-wrap {
			padding: 0rpx 30rpx 28rpx;
			background: $uni-bg-color-grey;

			.right-wrap {
				color: $uni-color-primary;
				font-size: 28rpx;

			}

			.tab-flex {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
		}

		.group {
			padding: 0rpx 30rpx 28rpx 52rpx;
			background: $uni-bg-color-grey;
			font-size: 28rpx;
			display: flex;
			align-items: center;
			//justify-content: space-between;

			.group-title {
				display: flex;
				color: $uni-color-primary;
				align-items: center;
				margin-right: 40rpx;

				.icon {
					margin-left: 10rpx;
					rotate: -90deg;
				}
			}


		}

		.container-wrap {
			padding-bottom: 54rpx;

			.group-wrap {
				width: 100%;
				margin: 20rpx 30rpx;

				.cell-wrap {
					background-color: #fff;
					border-radius: 10rpx;
					padding: 2rpx 0;

					&:not(:first-child) {
						margin-top: 20rpx;
					}

					.slot-title {
						display: flex;
						flex-direction: row;
						align-items: center;

						.cell-text {
							font-size: 28rpx;
							margin-left: 20rpx
						}

						.cell-flex {
							display: flex;
							margin-top: 15rpx;
						}
					}
				}
			}
		}

		.other {
			.model-popup-wrap {
				padding: 30rpx;

				.title {
					font-size: 32rpx;
					text-align: center;
					margin-bottom: 34rpx;
				}

				.cell-group-wrap {
					width: 100%;
					background: #fff;
					border-radius: 10rpx;

					.cell-wrap {
						padding: 6rpx 0;
						border-bottom: 1rpx solid #F1F2F5;
					}
				}

				.btn {
					margin-top: 30rpx;
				}
			}
		}
	}
</style>