<template>
	<page-meta>
		<navigation-bar :title="$tt('navBar.productList')" background-color="#F1F3F9" front-color="#000000" />
	</page-meta>
	<view class="scene-product-wrap">
		<u-sticky zIndex="98" bgColor="#F1F3F9">
			<view class="nav-bar">
				<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.productName" :placeholder="$tt('group.inputContent')" shape="circle"
						@clear="handleClearSearch" clearable>
					<!-- #endif -->
						<!-- #ifdef APP-NVUE -->
						<u--input :customStyle="{ padding: '17rpx 36rpx', background: '#FFFFFF' }"
							v-model="queryParams.productName" :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 v-if="type === 'trigger' ? trigger.source === 3 : action.source === 3" class="right-wrap"
					@click="handleNextStep" style="font-size: 28rpx; width: 104rpx; font-weight: 400; color: #3378FE">
					{{$tt('product.next')}}
				</view>

			</view>
		</u-sticky>

		<view class="container-wrap">
			<u-radio-group v-model="productId">
				<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" @click="goToDeviceList(item)">
								<view slot="title" class="slot-title">
									<u--image :src="getImageUrl(item)" radius="4" width="28" height="28"></u--image>
									<text class="cell-text">{{item.productName}}</text>
								</view>
								<view slot="value">
									<u-radio v-if="type === 'trigger' ? trigger.source === 3 : action.source === 3"
										shape="circle" :name="item.productId" iconSize="16"></u-radio>
									<u-icon v-else name="arrow-right" color="#909399" size="16"></u-icon>
								</view>
							</u-cell>
						</view>
					</u-cell-group>
				</view>
			</u-radio-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" @click="handleConfirmMore">{{$tt('sceneDetail.complete')}}</u-button>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

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

	export default {
		data() {
			return {
				type: 'trigger',
				editIndex: null, // null 代表新增
				isSearch: true,
				queryParams: {
					pageNum: 1,
					pageSize: 12,
					productName: ''
				},
				list: [], // 产品列表
				total: 0,
				loadmoreStatus: 'loadmore', // 刷新和加载相关
				productId: null, // 选择产品
				isModel: false, // 物模选择
				modelType: null, // 物模类型
				trigger: {},
				action: {}
			};
		},
		onLoad(option) {
			const { type, editIndex } = option;
			this.type = type;
			this.editIndex = Number(editIndex);
			this.trigger = uni.getStorageSync('trigger');
			this.action = uni.getStorageSync('action');
			this.getProductDatas();
			if(this.type === "trigger"){
				if (!Number.isNaN(this.editIndex) && this.editIndex != null && this.editIndex !== "") {
				console.log("修改")
			
				this.productId = this.trigger.productId
				//确保列表刷新
				//this.checkboxKey++
			
			}
			}else {
				if (!Number.isNaN(this.editIndex) && this.editIndex != null && this.editIndex !== "") {
					console.log("修改")
				
					this.productId = this.action.productId
					//确保列表刷新
					//this.checkboxKey++
				
				}
			}
			
		},
		methods: {
			// 获取区设备列表
			getProductDatas() {
				getProductList(this.queryParams)
					.then(res => {
						const { rows, total } = res;
						this.list = this.list.concat(rows);
						this.total = total;
					})
					.catch(err => {
						console.log(err);
					});
			},
			handleSearch() {
				this.list = [];
				this.queryParams.pageNum = 1;
				this.getProductDatas();
			},

			handleClearSearch() {
				this.handleSearch();
			},
			// 获取设备图片
			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 '';
					}
				}
			},
			// 下拉刷新
			onPullDownRefresh() {
				this.list = [];
				this.queryParams.pageNum = 1;
				// 模拟网络请求
				setTimeout(x => {
					this.getProductDatas();
					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.getProductDatas();
					}
				}, 1000);
			},
			// 设备跳转
			goToDeviceList(item) {
				if (this.type === 'trigger') {
					if (this.trigger.source === 1) {
						let trigger = uni.getStorageSync('trigger');
						trigger = { ...trigger, productId: item.productId, productName: item.productName };
						uni.setStorageSync('trigger', trigger);
						uni.$u.route('/pagesA/scene/product/device', { type: this.type });
					}
				} else {
					if (this.action.source === 1) {
						let action = uni.getStorageSync('action');
						action = { ...action, productId: item.productId, productName: item.productName };
						uni.setStorageSync('action', action);
						uni.$u.route('/pagesA/scene/product/device', { type: this.type });
					}
				}
			},
			// 下一步
			handleNextStep() {
				if (this.productId) {
					this.isModel = true;
					const { productId, productName } = this.list.find(item => item.productId === this.productId);
					let action = uni.getStorageSync(this.type);
					action = { ...action, productId, productName };
					uni.setStorageSync(this.type, action);
				} else {
					uni.showToast({
						icon: 'none',
						title: this.$tt('product.selectProducts')
					});
				}
			},
			// 物模跳转
			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 });
			},
			// 选择物模
			handleConfirmMore() {
				if (!this.modelType) {
					uni.showToast({
						icon: 'none',
						title: this.$tt('product.selectThingsModels')
					});
					return
				}
				let action = uni.getStorageSync(this.type);
				action = { ...action, type: this.modelType };
				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-product-wrap {
		.nav-bar {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			padding: 24rpx 30rpx 28rpx;

			.left-wrap {
				flex: 1;
			}

			.right-wrap {
				margin-left: 30rpx;

				::v-deep .u-icon__icon {
					top: -0.5px !important;
					margin-right: 0 !important;
				}
			}
		}

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

			.group-wrap {
				width: 100%;
				margin: 0 30rpx 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
						}
					}
				}
			}
		}

		.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>