<template>
	<view class="container">
		<u-navbar leftIconColor="#fff" titleStyle="color:#fff;fontSize:36rpx;" :autoBack="true" bgColor="#2C6FF3"
			:placeholder="true" title="团队成员设备授权"></u-navbar>
		<view class="content">
			<view class="search">
				<u-search animation placeholder="搜索设备" :clearabled="false" v-model="keyword" :showAction="false"
					@search="search"></u-search>
				<view class="scan-icon" @click="scan">
					<u-icon name="scan" size="22" color="#909399"></u-icon>
				</view>

				<view class="search-history flex flex-wrap flex-start">
					<view class="history-item" v-for="(item,index) in historyList" :key="index"
						@click="searchFast(item)">
						{{item}}
					</view>
				</view>
			</view>
			<view class="tab-wrap">
				<view class="tab">
					<u-tabs :list="tabList" :activeStyle="{color: '#333',fontWeight: 'bold',fontSize:'36rpx'}"
						:inactiveStyle="{fontSize:'32rpx'}" :scrollable="false" :current="current" @click="tabClick"
						lineColor="#2C6FF3">
					</u-tabs>
				</view>
			</view>

			<scroll-view class="scrollview" :scroll-with-animation="true" scroll-y lower-threshold="100"
				@scrolltolower="scrolltolower" :style="{height:fullHeight}">

				<view class="list" v-if="list&&list.length>0">
					<block v-for="(item, index) in list" :key="index">
						<view class="thumb-box" @click.stop="commItemSelect(item)">
							<view>
								<image class="select-img"
									src="https://cdn.ossfile.mxrvending.com/assets/xy_merc_mini/images/commodity/no_selected.png"
									mode="widthFix" v-show="item.noSelect"></image>
								<image class="select-img"
									src="https://cdn.ossfile.mxrvending.com/assets/xy_merc_mini/images/commodity/selected.png"
									mode="widthFix" v-show="!item.noSelect&&item.checked"></image>
								<image class="select-img"
									src="https://cdn.ossfile.mxrvending.com/assets/xy_merc_mini/images/commodity/select.png"
									mode="widthFix" v-show="!item.noSelect&&!item.checked"></image>
							</view>
							<view class="check-content">
								<view class="comm-main">
									<view>
										{{item.deviceName}}
									</view>
									<view>
										设备id：{{item.deviceId}}
									</view>
								</view>
							</view>
						</view>
					</block>
					<view class="more" style="overflow: hidden;">
						<u-loadmore :status="status" v-if="list.length>=1" />
					</view>
				</view>
				<view class="empty" v-if="list.length==0">
					<u-empty mode="list" text="没有设备!"></u-empty>
				</view>
			</scroll-view>
		</view>

		<view class="btn safe-bottom">
			<xbutton size="large" round="82rpx" @click="submit">{{current==0?'解绑':'绑定'}}</xbutton>
		</view>
	</view>
</template>

<script>
	import {
		mercDeviceList,
		addDevice,
		userDeviceList,
		delDevice
	} from "@/api/device/device.js"

	export default {
		data() {
			return {
				keyword: '',
				list: [], //商品列表

				page: 1, //商品分页
				size: 10,

				status: 'loadmore', //加载更多
				type: null,
				storeName: null,
				title: '私有商品库',
				btnName: '添加到商品私库',
				selectList: [],
				id: null,
				historyList: [],

				tabList: [{
						name: '已授权'
					},
					{
						name: '未授权'
					}
				],
				current: 0,
				fullHeight: 0,
				userId: null,
			}
		},

		onLoad(o) {
			let _this = this;
			const query = uni.createSelectorQuery().in(this);
			query.select(".scrollview").boundingClientRect((data) => {
				uni.getSystemInfo({
					success(res) {
						// 针对iPhone X等机型底部安全距离做适配
						const model = res.model;
						const modelInclude = [
							"iPhone X",
							'iPhone XR',
							"iPhone XS",
							"iPhone XS MAX",
							"iPhone 12/13 mini",
							"iPhone 12/13 (Pro)",
							"iPhone 12/13 Pro Max",
							"iPhone 14 Pro Max"
						];
						let safeDistance = modelInclude.includes(model)
						//动态设置商品区域高度
						if (safeDistance) {
							_this.fullHeight = res.windowHeight - data.top - 34 + 'px';
						} else {
							_this.fullHeight = res.windowHeight - data.top + 'px';
						}
					},
				});
			}).exec();

			this.userId = o.id;

			this.getList()
		},

		computed: {
			deviceIdList() {
				let list = [];
				this.list.forEach(i => {
					if (i.checked) {
						list.push(i.deviceId)
					}
				})
				return list
			}
		},
		methods: {
			search(val) {
				this.saveKeyWord('goods', this.keyword)
				this.reset();
				this.getList()
			},

			tabClick(e) {
				this.current = e.index
				this.search()
			},

			saveKeyWord(type, val) {
				if (val) {
					let arr = []
					if (uni.getStorageSync(type)) {
						let arr = JSON.parse(uni.getStorageSync(type))
						if (arr.indexOf(val) != -1) {
							arr.splice(arr.indexOf(val), 1)
						}
						arr.unshift(val)
						if (arr.length > 6) {
							arr.pop()
						}
						this.historyList = JSON.parse(JSON.stringify(arr))
						uni.setStorageSync(type, JSON.stringify(arr))
					} else {
						arr.unshift(val)
						this.historyList = JSON.parse(JSON.stringify(arr))
						uni.setStorageSync(type, JSON.stringify(arr))
					}
				} else {
					return
				}
			},

			searchFast(e) {
				this.keyword = e
				this.search()
			},

			//扫码
			scan() {
				uni.scanCode({
					success: (res) => {
						this.keyword = res.result;
						this.getList()
					}
				});
			},

			//根据类目获取商品列表
			getList(id) {
				if (this.current == 0) {
					userDeviceList({
						page: {
							current: this.page,
							size: this.size
						},
						keyword: this.keyword,
						userInfoId: this.userId,
					}).then(res => {
						let newData = res.data.records;
						newData.forEach(i => {
							i.checked = false
						})
						if (newData.length < 10) {
							this.status = "nomore"
						} else {
							this.status = "loadmore"
						}
						this.list = this.list.concat(newData)
						console.log(this.list)
					})
				}
				if (this.current == 1) {
					mercDeviceList({
						page: {
							current: this.page,
							size: this.size
						},
						keyword: this.keyword,
						userInfoId: this.userId,
					}).then(res => {
						let newData = res.data;
						newData.forEach(i => {
							i.checked = false
						})
						if (newData.length < 10) {
							this.status = "nomore"
						} else {
							this.status = "loadmore"
						}
						this.list = this.list.concat(newData)
					})
				}
			},

			//触底加载更多
			scrolltolower() {
				if (this.status == 'nomore') return
				this.page++
				this.getList()
			},

			reset() {
				this.status == 'loadmore'
				this.page = 1;
				this.size = 10;
				this.list = [];
			},

			// 商品选中状态改变
			commItemSelect(e) {
				e.checked = !e.checked
			},

			submit() {

				uni.showModal({
					title: '提示',
					content: `是否确认${this.current==0?'解绑':'绑定'}`,
					success: res => {
						if (res.confirm) {
							if (this.current == 0) {
								delDevice({
									"userInfoId": this.userId,
									"deviceIdList": this.deviceIdList
								}).then(res => {
									this.$modal.msg('解绑成功')
									this.search()
								})
							} else {
								addDevice({
									"userInfoId": this.userId,
									"deviceIdList": this.deviceIdList
								}).then(res => {
									this.$modal.msg('绑定成功')
									this.search()
								})
							}
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		.content {
			padding-bottom: 88rpx;

			.search {
				padding: 24rpx 24rpx 12rpx;
				background-color: #fff;
				position: relative;

				.scan-icon {
					position: absolute;
					right: 36rpx;
					top: 38rpx;
					z-index: 2;
				}

				.search-history {

					.history-item {
						margin-right: 24rpx;
						padding: 0 12rpx;
						background-color: #f2f2f2;
						color: #333;
						font-size: 24rpx;
						line-height: 40rpx;
						border-radius: 40rpx;
						margin-top: 24rpx;
					}
				}
			}

			.tab-wrap {
				background-color: #fff;
				.tab{
					width:50%;
				}
			}

			.list {
				width: 100%;
				padding: 0rpx 13rpx 12rpx;
				padding-bottom: calc(110rpx + env(safe-area-inset-bottom) / 2);
				overflow: hidden;

				.thumb-box {
					border-bottom: 1rpx solid #f4f4f4;
					display: flex;
					flex-flow: row nowrap;
					padding: 20rpx;
					background-color: #fff;
					border-radius: 12rpx;
					margin-top: 12rpx;
				}

				.select-img {
					width: 40rpx;
					height: 40rpx;
					margin-top: 14rpx;
				}

				.check-content {
					display: flex;
					flex-direction: row;
					align-items: center;
					padding-left: 12rpx;

					.comm-img {
						width: 130rpx;
						height: 130rpx;
						display: flex;
						flex-direction: row;
						align-items: center;
						justify-content: space-around;

						image {
							width: 100%;
						}
					}

					.comm-main {
						box-sizing: border-box;
						padding-left: 18rpx;
						color: #999;
						line-height: 60rpx;

						>view {
							padding: 4rpx 0;
						}

						>view:nth-child(1) {
							font-size: 30rpx;
							font-weight: bold;
							color: #333;
						}

						>view:nth-child(2) {
							font-size: 28rpx;
						}
					}
				}
			}
		}

		.btn {
			width: 100%;
			position: fixed;
			left: 0;
			padding: 0 24rpx;
		}

		.empty {
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
		}
	}
</style>