<template>
	<view>
		<view class="status_bar"></view>
		<view class="" style="position: relative;top: 44px;">
			<view style="position: fixed;z-index: 100;">
				<uni-nav-bar @clickLeft="clickLeft" left-icon="back" left-text="返回" title="设备分配"></uni-nav-bar>
			</view>
			<view class="utabs" v-if="typeList.length">
				<view style="width: 95%;margin: 0 auto;">
					<u-tabs :list="typeList" keyName="type_name" :is-scroll="true" :current="current" @change="change"
						item-width="140" font-size="24" gutter="20" bar-width="60" active-color="#42b983"></u-tabs>
				</view>
			</view>
			<view class="bases_search">
				<view class="bases_search_text">
					<u-icon name="search" class="search" @click="searchs"></u-icon>
					<input type="text" v-model="inputdata" placeholder="请输入设备编号" @change="handleSearch"
						@confirm="handleSearch" />
				</view>
			</view>
			<view class="loading" v-if="loadingtf">
				<image src="../../static/images/ajax-loader.gif" mode="" class="img"></image>
			</view>
			<view class="loading" v-if="nonetf">
				暂无可分配设备
			</view>
			<view class="ass_list">
				<checkbox-group class="che_group" @change="checkboxchange">
					<label v-for="(items,indexs) in equipmentList" :key="items.id">
						<view class="" class="equipment">
							<view class="equipment_top">
								<image
									:src="'http://www.hnyfwlw.com:8006/bigdata_app/image/fourMoodBase/'+currentType.type_id+'.png'"
									mode="" class="equipment_top_img"></image>
								<span class="equipment_top_name">{{currentType.type_name}}</span>
								<checkbox :value="String(items.type_name)" :checked="items.check" class="ucheckbox"
									color="#42b983" />
							</view>
							<view class="equipment_bot">
								<p class="equipment_bot_id">设备ID：{{items.id}}</p>
								<p class="equipment_bot_name">设备编号：{{items.type_name}}</p>
								<view class="equipment_state">在线</view>
							</view>
						</view>
					</label>
				</checkbox-group>
			</view>
			<view class="allocbtn">
				<button @click="cancel" class="cancel">取消分配</button>
				<button @click="canfirm" class="canfirm">确定分配</button>
			</view>
		</view>
		<view class="top" v-if="isTop" @click="top">
			<image :src="'http://www.hnyfwlw.com:8006/bigdata_app'+'/image/6209a98f0cb3b5086f2ca36152c9269.png'"
				mode=""></image>
		</view>
	</view>
</template>

<script>
	import {
		map,
		assign,
		concat,
		zipObject,
		groupBy,
		uniqBy,
		values,
		keys
	} from 'lodash-es';

	export default {
		data() {
			return {
				search: '',
				checken: false,
				assignment: [],
				assignments: [],
				list: [],
				current: 0,
				assignment_items: [],
				src: '',
				obj: {},
				isTop: false,
				base_id: "",
				baseidarr: "",
				inputdata: "",
				loadingtf: false, //loading
				nonetf: false, //设备列表为空判断
				currentTypeID: 3,
				pageSize: 10,
				page: 1,
				equipmentList: [],
				typeList: [{
					"type_name": "测报灯",
					"type_id": 3
				}],
				selectedDataSource: {},
				selectedGroupByNameIDs: {}
			}
		},
		computed: {
			currentType() {
				return this.typeList[this.current]
			},
			currentEquipmentIDList(){
				return map(this.selectedGroupByNameIDs[this.currentType.type_name],'device_id') 
			}
		},
		methods: {
			async ybase() { //获取基地已绑定设备
				const res = await this.$myRequest({
					url: '/api/api_gateway?method=base.bases.base_map_list',
					data: {
						base_id: this.base_id
					}
				})
				this.baseidarr = res;
				this.selectedDataSource = zipObject(map(res, 'device_id'), res);
				this.selectedGroupByNameIDs = groupBy(res, item => item.type_name);



				console.log(res, this.selectedDataSource)
				var arr = []
				for (var i = 0; i < res.length; i++) {
					if (arr.indexOf(res[i].type_name) === -1) {
						arr.push(res[i].type_name)
					}
				}
				var obj = {}
				for (var i = 0; i < arr.length; i++) {
					obj[arr[i]] = []
				}
				for (var i = 0; i < res.length; i++) {
					for (var key in obj) {
						if (res[i].type_name == key) {
							obj[key].push(res[i].device_id)
						}
					}
				}
				console.log(obj)
				this.obj = obj
				this.getFourbase()
			},
			async getFourbase() { //全部设备列表
				this.loadingtf = true
				const res = await this.$myRequest({
					url: '/api/api_gateway?method=base.bases.base_equip',
					data: {
						base_id: this.base_id,
						type_id: this.currentTypeID,
						device_id: this.inputdata,
						page_size: this.pageSize,
						page: this.page
					}
				})
				this.typeList = res.type_info_list.map(item => {
					return {
						name: item.type_name,
						type_name: item.type_name,
						type_id: item.type_id
					}
				});
				console.log(res, 'get four base', this.typeList)
				this.loadingtf = false
				this.assignment = res.data
				for (var i = 0; i < this.assignment.length; i++) {
					let obj = {}
					obj.name = this.assignment[i].type_name
					this.list.push(obj)
				}
				if (this.list.length == 0) {
					let obj = {}
					obj.name = "全部"
					this.list.push(obj)
					this.nonetf = true
				}
				console.warn(this.assignment, '--------------- equipment list', this.page)
				this.assignments = this.assignment[0]
				const dataList = res.data[0] && map(res.data[0].children, item => {
					return assign({}, item, {
						check: this.currentEquipmentIDList.includes(item.type_name)
					})
				});
				this.equipmentList = this.page === 1 ? dataList : concat(this.equipmentList, dataList);

				console.warn(this.equipmentList, 'get equip list ', this.equipmentList.length)


				// for (let i = 0; i < this.assignments.children.length; i++) {
				// 	this.assignments.children[i].check = false
				// 	for (let j = 0; j < this.baseidarr.length; j++) {
				// 		if (this.assignments.children[i].type_name == this.baseidarr[j].device_id) {
				// 			this.assignments.children[i].check = true
				// 			console.log(this.assignments.children[i].check)
				// 		}
				// 	}
				// }
			},
			forchange(obj) {
				for (let i = 0; i < this.assignments.children.length; i++) {
					this.assignments.children[i].check = false
					for (let key in obj) {
						if (key == this.list[this.current].name) {
							for (let j = 0; j < obj[key].length; j++) {
								if (this.assignments.children[i].type_name == obj[key][j]) {
									this.assignments.children[i].check = true
								}
							}
						}
					}
				}
			},
			change(index, item) {
				this.current = index
				this.page = 1;
				this.equipmentList = []
				this.currentTypeID = this.typeList[index] && this.typeList[index].type_id || ''
				this.getFourbase();
				console.log(this.obj)
				// this.forchange(this.obj)
			},
			checkboxchange(e, items) {
				console.log(e.detail, 'checkbox ', typeof e.detail.value,items)
				this.obj[this.assignments.type_name] = JSON.parse(JSON.stringify(e.detail.value))
				const originCurrentTypeIDList = this.selectedGroupByNameIDs[this.currentType.type_name] || []
				this.selectedGroupByNameIDs[this.currentType.type_name] = map(e
					.detail.value, id => ({
						device_id: id
					}))
			},
			clickLeft() {
				uni.navigateBack({
					delta: 1
				})
			},
			cancel() {
				this.clickLeft()
			},
			canfirm() {
				const data = zipObject(keys(this.selectedGroupByNameIDs), map(values(this.selectedGroupByNameIDs),
					items => map(items, 'device_id')))

				console.log(data, 'confrim ')
				uni.setStorage({
					key: "typeid",
					data: JSON.stringify(data),
					success: () => {
						uni.navigateBack({
							delta: 1
						})
					}
				})
			},
			top() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 500
				})
			},
			searchs() {
				console.log(this.inputdata.search("好"))
			},
			handleSearch() {
				console.log('handle search 00000000000000')
				this.page = 1;
				this.equipmentList = [];
				this.getFourbase();
			},
			initEquipmentList() {
				const result = map(this.bindEquipmentList, item => {
					return {
						device_id: item[1],
						type_name: item[0]
					};
				});

				this.selectedDataSource = zipObject(map(result, 'device_id'), result);
				this.selectedGroupByNameIDs = groupBy(result, item => item.type_name);

				this.getEquipmentList();
			},
		},
		onLoad(option) {
			this.base_id = option.base_id
			console.log(this.base_id,'onload ----- equipment list')
			if (this.base_id) {
				this.ybase()
			} else {
				this.getFourbase()
			}
		},
		onPageScroll(e) { //nvue暂不支持滚动监听，可用bindingx代替
			if (e.scrollTop > 200) { //距离大于200时显示
				this.isTop = true
			} else { //距离小于200时隐藏
				this.isTop = false
			}
		},
		onShow() {
			console.warn('onshow ---------------------- 123')
			uni.getStorage({
				key: 'typeid',
				success: (res) => {
					var arr = []
					// for(var key in JSON.parse(res.data)){
					// 	console.log(key)
					// 	for(var i=0;i<JSON.parse(res.data)[key].length;i++){
					// 		var obj={
					// 			name:key,
					// 			arr:JSON.parse(res.data)[key][i]
					// 		}
					// 		arr.push(obj)
					// 	}
					// }
					console.warn(JSON.parse(res.data), 'get storage typeid  1 all location')
					// this.baseobj = arr
				},
				fail(){
					console.log('fail')
				}
			});
		},
		onReachBottom() {
			this.page++;
			this.getFourbase();
		}
	}
</script>

<style lang="scss">
	.utabs {
		width: 100%;
		position: fixed;
		top: 88px;
		z-index: 100;
	}

	.bases_search {
		width: 100%;
		position: fixed;
		top: 128px;
		z-index: 100;
		background-color: #FFFFFF;

		.bases_search_text {
			width: 90%;
			margin: 0 auto;
			background-color: #F8F8F8;
			height: 60rpx;
			border-radius: 30rpx;
			display: flex;
			line-height: 60rpx;

			.search {
				padding: 0 20rpx;
				font-size: 34rpx;
			}

			input {
				width: 80%;
				margin-top: 10rpx;
				font-size: 28rpx;
			}
		}
	}

	.loading {
		position: fixed;
		top: 440px;
		width: 95%;
		left: 2.5%;
		text-align: center;

		.img {
			width: 300rpx;
			height: 40rpx;
		}
	}

	.ass_list {
		position: absolute;
		top: 115px;
		width: 100%;
		margin-bottom: 40px;

		.che_group {
			display: flex;
			flex-direction: column;
			width: 90%;
			margin: 0 auto;
		}

		.equipment {
			width: 90%;
			margin: 20rpx auto;
			box-shadow: 0 0 10rpx #bcb9ca;
			padding: 20rpx 30rpx;

			.equipment_top {
				height: 60rpx;
				width: 100%;
				border-bottom: 1px solid #dfe5ec;
				position: relative;

				.equipment_top_img {
					width: 40rpx;
					height: 40rpx;
					position: absolute;
				}

				.equipment_top_name {
					font-size: 24rpx;
					margin-left: 60rpx;
				}

				.ucheckbox {
					float: right;
					margin: 0rpx -4rpx;
					transform: scale(0.7);
				}
			}

			.equipment_bot {
				padding: 30rpx 0;
				position: relative;

				.equipment_bot_id {
					font-weight: 700;
					font-size: 15px;
					margin-bottom: 16rpx;
				}

				.equipment_bot_name {
					font-size: 24rpx;
				}

				.equipment_state {
					position: absolute;
					top: 20rpx;
					right: 0;
					width: 100rpx;
					height: 100rpx;
					text-align: center;
					line-height: 100rpx;
					color: #42b983;

				}
			}
		}
	}

	.allocbtn {
		width: 100%;
		position: fixed;
		bottom: 0;
		z-index: 100;
		display: flex;

		button {
			width: 50%;
			font-size: 24rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 0;
		}

		.cancel {
			background-color: #C8C7CC;
			color: #555555;
		}

		.canfirm {
			color: white;
			background-color: #42b983;
		}
	}

	.top {
		position: fixed;
		right: 30px;
		bottom: 100px;
		z-index: 100;

		image {
			width: 100rpx;
			height: 100rpx;
		}
	}
</style>