<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="flex align-center justify-around margintop">
			<view class="">共关联({{comList.length}})件商品 </view>
			<view class="color">点击图片可以移除</view>
			<view class="">
				<xbutton size="size" @tap='save'>保存</xbutton>
			</view>
		</view>
		<view class="margintop">
			<view style="height: 230rpx;overflow: hidden;" v-if="comList&&comList.length>0">
				<u-scroll-list :indicator="indicator" indicatorColor="#fff0f0" indicatorActiveColor="#f56c6c">
					<view class="flex justify-around">
						<view class="" v-for="(item,index) in comList" :key="item.id">
							<view class="flex flex-direction align-center justify-center image-dele-container"
								@tap="clean(item)">
								<view class="image">
									<u--image radius="4" width="120rpx" height="120rpx" :src="item.img"
										mode="aspectFit" :lazy-lord="true"></u--image>
								</view>
								<view class="">{{item.name}}</view>
							</view>
						</view>
					</view>
				</u-scroll-list>
			</view>
			<view class="no-com" v-else  style="height: 230rpx;overflow: hidden;">
				请添加商品
			</view>
		</view>
		<view class="search" @click="searchComm">
			<view class="search-input">
				<u-search placeholder="商品搜索" actionText="取消" :actionStyle="{color:'#2C6FF3'}" :showAction="!leftShow"
					:clearabled="false" v-model="keyword" @search="search" @custom="cancle"></u-search>
				<view @click="scan" :class="[leftShow?'scan-icon scan-left-show':'scan-icon scan-left-hidden']">
					<u-icon name="scan" size="22" color="#909399"></u-icon>
				</view>
			</view>

			<view class="search-history flex flex-wrap flex-start" v-if="!leftShow">
				<view class="history-item" v-for="(item,index) in historyList" :key="index" @click="searchFast(item)">
					{{item}}
				</view>
			</view>
		</view>
		<view class="content">
			<view class="swiperitem-content">
				<view class="classify-wrap">
					<Classify :tabList="perTabList" :status="perStatus"
						:commList="perCommList" @switchMenu="perSwitchMenu" @lowerBottom="perLowerBottom"
						:isModal="true" :height="fullHeight" @comClick="comClick" :leftShow="leftShow" />
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import Classify from "@/components/classify/index.vue"
	import {
		goodsCategory as perGoodsCategory,
		ownerGoodsList as pageByGoodsMerc
	} from "@/api/commodity/mercGoods.js"
	import {
		goodsCategory as pubGoodsCategory,
		ownerGoodsList as pageByGoods
	} from "@/api/commodity/goods.js"
	import {
		saveListingGoods,
		refGoods
	} from "@/api/commoditylist/commoditylist.js"
	export default {
		components: {
			Classify
		},
		data() {
			return {
				modelId: '', //清单id

				goodsId: [], //商品id列表

				fullHeight: "0",

				// 私库
				perTabList: [], //商品类目
				perCommList: [], //商品列表
				perPage: 1, //商品分页
				perSize: 10,
				perStatus: 'loadmore', //加载更多

				id: null, //设备id
				categoryCode: null,

				leftShow: true,
				historyList: [],
				keyword: '',
				
				oldList:[],
				newList:[],
				
				title:null,
				deviceId:null,
			}
		},
		async onLoad(o) {
			let _this = this;
			const query = uni.createSelectorQuery().in(this);
			query.select(".classify-wrap").boundingClientRect((data) => {
				_this.top = data.top;
				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 - _this.top - 34 + 'px';
						} else {
							_this.fullHeight = res.windowHeight - _this.top + 'px';
						}
					},
				});
			}).exec();

			this.title = o.title
			this.modelId = o.modelId
			this.deviceId=o.deviceId
			if (uni.getStorageSync('goods')) {
				this.historyList = JSON.parse(uni.getStorageSync('goods'))
			}

			await this.getrefGoods()
			this.getPerCategory()
		},

		async onShow() {
			this.perReset()
			await this.getPerCommList()
		},
		
		computed:{
			comList(){
				let list=[]
				list=[...this.oldList,...this.newList]
				return list
			},
		},

		methods: {
			searchComm() {
				this.leftShow = false
			},

			search(val) {
				this.saveKeyWord('goods', this.keyword)
				this.perReset();
				this.getPerCommList()
			},

			cancle(val) {
				this.keyword = ''
				this.leftShow = true
				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) {
							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.search()
					}
				});
			},

			//获取类目列表
			getPerCategory() {
				return new Promise((resolve, reject) => {
					perGoodsCategory().then(res => {
						if (res.data && res.data.length > 0) {
							this.perTabList = res.data.map(i => {
								if (i.categoryCode == null) {
									i.categoryName = '未定义'
									return i
								} else {
									return i
								}
							});
							if (this.perTabList && this.perTabList.length > 0) {
								this.categoryCode = this.perTabList[0].categoryCode
							}
						}
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},

			//商品类目切换
			perSwitchMenu(item) {
				this.categoryCode = item.categoryCode
				this.perReset()
				this.getPerCommList()
			},

			//根据类目获取商品列表
			getPerCommList() {
				let params = {}
				if (this.leftShow) { //搜索
					params = {
						categoryCode: this.categoryCode,
						page: {
							current: this.perPage,
							size: this.perSize
						},
					}
				} else { //非搜索
					params = {
						page: {
							current: this.perPage,
							size: this.perSize
						},
						keyword: this.keyword
					}
				}
				return new Promise((resolve, reject) => {
					pageByGoodsMerc(params).then(res => {
						let data = res.data.records;
						if (data && data.length > 0) {
							data = data.map(i => {
								i.name = i.goodsName;
								i.barcode = i.goodsBarcode;
								i.cover = i.goodsCover;
								i.price = i.price != null ? Number(i.price) / 100 : null;
								i.categoryName = i.categoryCodeName;
								i.noSelect = i.isBind;
								return i
							})
						}
						if (data.length < 10) {
							this.perStatus = "nomore"
						} else {
							this.perStatus = "loadmore"
						}
						this.perCommList = this.perCommList.concat(data)

						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},

			//触底加载更多
			perLowerBottom() {
				if (this.perStatus == 'nomore') return
				this.perPage++
				this.getPerCommList()
			},

			//重置
			perReset() {
				this.perStatus == 'loadmore'
				this.perPage = 1;
				this.perSize = 10;
				this.perCommList = [];
			},
			
			//反显清单图片
			getrefGoods() {
				return new Promise((resolve, reject) => {
					refGoods({
						modelId: this.modelId
					}).then(res => {
						res.data.forEach(item => {
							this.oldList.push({
								name: item.goodsName,
								id: item.goodsId,
								img:item.goodsImgUrl
							})
						})
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},
			
			//点击商品
			comClick(e) {
				if(e.price==null){
					uni.showModal({
						title: '提示',
						content: '当前商品为新商品需先设置商品价格,是否前往设置?',
						success: res => {
							if (res.confirm) {
								this.$tab.navigateTo('/pages/commodity/comEdit?id=' + e.id)
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}else{
					this.addToList(e)
				}
			},
			
			//添加商品至关联
			addToList(e){
				if(this.comList.some(i=>i.id==e.goodsId)){
					this.$modal.msg('该商品已存在~')
					return
				}
				this.newList.push({
					name: e.goodsName,
					id: e.goodsId,
					img:e.imgUrls
				})
			},
			
			clean(e){
				if(e.name=='未知商品'||e.name=='非友好购物商品'){
					this.$modal.msg('预设商品不能删除!!!')
					return
				}
				
				for (let i = 0; i < this.oldList.length; i++) {
					let item=this.oldList[i]
					if(item.id==e.id){
						this.oldList.splice(i,1)
						return
					}
				}
				
				for (let i = 0; i < this.newList.length; i++) {
					let item=this.newList[i]
					if(item.id==e.id){
						this.newList.splice(i,1)
						return
					}
				}
				
			},
			
			save() {
				if (!this.comList.length) {
					uni.$u.toast('请选择商品')
					return;
				}
				var comList = []
				this.comList.forEach(item => {
					comList.push(item.id)
				})
				saveListingGoods({
					modelId: this.modelId, //清单ID
					goodsId: comList //关联的商品id，不传则表示清空
				}).then(res => {
					if (res.code == 200) {
						uni.$u.toast(res.msg)
						setTimeout(() => {
							this.$tab.navigateBack()
						}, 1000)
					}
				})
			},
		}
	}
</script>
<style lang="scss" scoped>
	.container {
		.margin {
			margin: 10rpx 20rpx;
		}

		.margintop {
			margin-top: 10rpx;
		}

		.marginleft {
			margin-left: 10rpx;
		}

		.active {
			background-color: #ffffff;
		}

		.un-active {
			background-color: #e5e5e5;
		}

		.color {
			color: red;
		}

		.image-dele-container {
			position: relative;
			width: 200rpx;
			height: 200rpx;
			margin-left: 10rpx;
			background-color: #f6f6f6;
			border-radius: 15rpx;

			view {
				text-overflow: ellipsis;
				overflow: hidden;
				white-space: nowrap;
				width: 120rpx;
			}

			.image {
				width: 120rpx;
				height: 120rpx;
			}
		}

		.image-container {
			width: 150rpx;
			height: 200rpx;
			background-color: #d9d9d9;

			image {
				width: 90rpx;
				height: 100rpx;
			}
		}
		
		.no-com{
			height:228rpx;
			text-align: center;
			line-height: 228rpx;
		}

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

			.search-input {
				position: relative;

				.scan-icon {
					position: absolute;
					top: 50%;
					transform: translateY(-50%);
					z-index: 2;

					&.scan-left-show {
						right: 36rpx;
					}

					&.scan-left-hidden {
						right: 100rpx;
					}
				}
			}

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

		.btn {
			width: 724rpx;
			position: fixed;
			left: 13rpx;
			bottom: calc(24rpx + env(safe-area-inset-bottom) / 2);
			border-radius: 88rpx;
			overflow: hidden;
		}
	}
</style>