<template>
	<view class="container">
		<u-navbar leftIconColor="#fff" titleStyle="color:#fff;fontSize:36rpx;" :autoBack="true" bgColor="#2C6FF3"
			:placeholder="true" :title="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="list" v-if="newCommList&&newCommList.length>0">
				<view class="thumb-box" v-for="(item, index) in newCommList" :key="index"
					@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-img">
							<u--image width="130rpx" height="130rpx" :src="item.cover" mode="widthFix"
								:lazy-lord="true"></u--image>
						</view>
						<view class="comm-main">
							<view>
								{{item.name}}
							</view>
							<view>
								条形码：{{item.barcode}}
							</view>
							<view>
								商品类型：{{item.categoryName}}
							</view>
							<view v-if="type==1">
								价格：<text>￥{{item.price}}</text>
							</view>
						</view>
					</view>
				</view>
				<u-loadmore :status="status" v-if="newCommList.length>=1" />
			</view>

			<view class="empty" v-if="newCommList.length==0">
				<u-empty mode="car" text="没有商品!"></u-empty>
			</view>
		</view>

		<view class="btn safe-bottom">
			<xbutton size="large" @click="submit">{{btnName}}({{selectList.length}})</xbutton>
		</view>
	</view>
</template>

<script>
	import {
		ownerGoodsList as perOwnerGoodsList
	} from "@/api/commodity/mercGoods.js"
	import {
		ownerGoodsList as pubOwnerGoodsList,
		pageByGoods,
		pageByGoodsMerc
	} from "@/api/commodity/goods.js"
	export default {
		data() {
			return {
				keyword: '',
				commList: [], //商品列表

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

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

		computed: {
			newCommList() {
				let newCommList = [];
				if (this.selectList && this.selectList.length > 0) {
					let selectList = this.selectList
					const idMapping = selectList.reduce((acc, el, i) => {
						acc[el.id] = i;
						return acc;
					}, {});
					this.commList.forEach(i => {
						if (idMapping[i.id] != undefined) { //重复值
							i.checked = true
						} else {
							i.checked = false
						}
						newCommList.push(i)
					})
				} else {
					newCommList = this.commList.map(i => {
						i.checked = false;
						return i
					})
				}
				console.log('newCommList', newCommList)
				return newCommList
			},
		},

		onLoad(o) {
			if (uni.getStorageSync('goods')) {
				this.historyList = JSON.parse(uni.getStorageSync('goods'))
			}
			if (o.type) {
				this.id = o.type != 0 ? o.id : null;
				this.type = o.type; //0公库到私库、1私库到设备、2公库到设备
				this.title = o.type == 1 ? '私有商品库' : '官方商品库';
				this.btnName = o.storeName == 'pubToPerStor' ? '添加到商品私库' : '添加到设备';
				this.storeName = o.storeName;

				if (uni.getStorageSync(this.storeName) && JSON.parse(uni.getStorageSync(
						this.storeName)).length > 0) {
					let commStor = JSON.parse(uni.getStorageSync(this.storeName))
					this.selectList = commStor;
				}

				this.getCommList();
			}
		},
		methods: {
			search(val) {
				this.saveKeyWord('goods', this.keyword)
				this.reset();
				this.getCommList()
			},

			saveKeyWord(type, val) {
				if (val) {
					let arr = []
					if (uni.getStorageSync(type)) {
						let arr = JSON.parse(uni.getStorageSync(type))
						if (arr.indexOf(val) != -1) {
							console.log('arr.indexOf(val)', arr.indexOf(val))
							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.getCommList()
					}
				});
			},

			//根据类目获取商品列表
			getCommList(id) {
				if (this.type == 0) { //公库到私库
					pubOwnerGoodsList({
						page: {
							current: this.page,
							size: this.size
						},
						keyword: this.keyword
					}).then(res => {
						let data = res.data.records;
						let newData = data.map(i => {
							i.noSelect = i.mercGoodsId != null ? true : false;
							i.categoryCode = i.categoryCodeLevel1;
							return i
						})
						if (newData.length < 10) {
							this.status = "nomore"
						} else {
							this.status = "loadmore"
						}
						this.commList = this.commList.concat(newData)
					})
				}
				if (this.type == 1) { //私库到设备
					pageByGoodsMerc({
						page: {
							current: this.page,
							size: this.size
						},
						keyword: this.keyword,
						deviceId: this.id
					}).then(res => {
						let data = res.data.records;
						if (data && data.length > 0) {
							data = data.map(i => {
								i.noSelect = i.isBind;
								i.name = i.goodsName;
								i.barcode = i.goodsBarcode;
								i.cover = i.goodsCover;
								i.price = Number(i.price) / 100;
								i.categoryName = i.capacity == null ? '未分类' : i.capacity;
								return i
							})
						}
						if (data.length < 10) {
							this.status = "nomore"
						} else {
							this.status = "loadmore"
						}
						this.commList = this.commList.concat(data)
					})
				}

				if (this.type == 2) { //公库设备
					pageByGoods({
						page: {
							current: this.page,
							size: this.size
						},
						keyword: this.keyword,
						deviceId: this.id
					}).then(res => {
						let data = res.data.records;
						let newData = data.map(i => {
							i.noSelect = i.isBind;
							i.categoryCode = i.categoryCodeLevel1;
							return i
						})
						if (newData.length < 10) {
							this.status = "nomore"
						} else {
							this.status = "loadmore"
						}
						this.commList = this.commList.concat(newData)
					})
				}
			},

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

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

			// 商品选中状态改变
			commItemSelect(e) {
				if (e.noSelect) {
					this.$modal.msg('当前商品已存在!')
					return
				}
				e.checked = !e.checked
				//选中商品存储到内存中，以便取用
				let commStor = []
				if (e.checked) { //选中添加到存储中
					if (uni.getStorageSync(this.storeName)) {
						commStor = JSON.parse(uni.getStorageSync(this.storeName));
					}
					commStor.push(e);
				} else { //取消选中删除,并且从存储中删除
					commStor = JSON.parse(uni.getStorageSync(this.storeName));
					for (let i = 0; i < commStor.length; i++) {
						let item = commStor[i]
						if (item.id == e.id) {
							commStor.splice(i, 1);
							break
						}
					}
				}
				//收集选中商品，更新存储
				this.selectList = commStor;
				commStor.length > 0 ? uni.setStorageSync(this.storeName, JSON.stringify(commStor)) : uni
					.setStorageSync(
						this.storeName, '')
				if (commStor.length > 0) {
					uni.setStorageSync(this.storeName, JSON.stringify(commStor))
				}
			},

			submit() {
				if (uni.getStorageSync(this.storeName) && JSON.parse(uni.getStorageSync(this.storeName)).length > 0) {
					this.$tab.navigateTo(
						`/pages/equipment/addComList?storeName=${this.storeName}&type=${this.type}&id=${this.id}`)

				} else {
					uni.$u.toast('请先选择商品！')
				}
			}
		}
	}
</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;
					}
				}
			}

			.list {
				width: 100%;
				padding: 12rpx 24rpx;

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

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

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

						>view {
							padding: 4rpx 0;
						}

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

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

						>view:nth-child(3) {
							font-size: 26rpx;
						}

						>view:nth-child(4) {
							font-size: 26rpx;

							text {
								font-weight: bold;
								color: red;
							}
						}
					}
				}
			}
		}

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

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