<template>
	<view class="container">
		<u-navbar leftIconColor="#fff" titleStyle="color:#fff;fontSize:36rpx;" :autoBack="true" bgColor="#2C6FF3"
			:placeholder="true" title="增加商品"></u-navbar>
		<!-- <view class="search" @click.native="searchClick">
			<u-search animation placeholder="商品搜索" disabled v-model="keyword" :showAction="false" search="search">
			</u-search>
		</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="xy-card tab-list" style="padding:0 0 24rpx;">
			<view class="tab-left">
				<u-tabs :list="tabList" :scrollable="false" :current="current" @click="tabClick" lineColor="#2C6FF3">
				</u-tabs>
			</view>
			<view class="use-list" @click="$tab.navigateTo(`/pages/commodity/commoditylist?id=${id}`)">
				常用商品清单
			</view>
		</view>
		<view class="content">
			<view class="swiperitem-content" v-if="current==0">
				<view class="classify-wrap">
					<Classify storeName="perStor" :selectShow="true" :tabList="perTabList" :status="perStatus"
						:commList="perCommList" @switchMenu="perSwitchMenu" @lowerBottom="perLowerBottom"
						:isModal="true" :height="fullHeight" @comClick="comClick" :leftShow="leftShow" />
				</view>
				<view class="btn safe-bottom">
					<xbutton size="large" @click="addCom">添加到设备</xbutton>
				</view>
			</view>
			<view class="swiperitem-content" v-if="current==1">
				<view class="classify-wrap">
					<Classify storeName="pubStor" :selectShow="true" :tabList="pubTabList" :status="pubStatus"
						:commList="pubCommList" @switchMenu="pubSwitchMenu" @lowerBottom="pubLowerBottom"
						:height="fullHeight" :leftShow="leftShow" />
				</view>
				<view class="btn">
					<xbutton size="large" @click="addCom">添加到设备</xbutton>
				</view>
			</view>
			<!-- 选项卡内容轮播滑动显示，current为当前第几个swiper子项 -->
			<!-- <swiper @change="change" :current="current" class="swiper-content" :style="{height:height}">
				<swiper-item class="swiperitem-content">
					<view class="search">
						<u-search animation placeholder="商品搜索" v-model="keyword" :showAction="false" search="search">
						</u-search>
					</view>
					<view class="classify-wrap">
						<Classify storeName="perStor1" :height="fullHeight" :selectShow="true"
							v-model="commodityList" />

					</view>
					<view class="btn">
						<xbutton size="large" @click="addCom">已选中(21)样商品</xbutton>
					</view>
				</swiper-item>
				<swiper-item class="swiperitem-content">
					<view class="search">
						<u-search animation placeholder="商品搜索" v-model="keyword" :showAction="false" search="search">
						</u-search>
					</view>
					<view class="classify-wrap">
						<Classify storeName="perStor2" :height="fullHeight" :selectShow="true"
							v-model="commodityList" />
					</view>
					<view class="btn">
						<xbutton size="large" @click="addCom">已选中(21)样商品</xbutton>
					</view>
				</swiper-item>
			</swiper> -->
		</view>
	</view>
</template>

<script>
	import Classify from "@/components/classify/index.vue"
	import {
		goodsCategory as perGoodsCategory,
	} from "@/api/commodity/mercGoods.js"
	import {
		goodsCategory as pubGoodsCategory,
		pageByGoods,
		pageByGoodsMerc,
		bindDeviceByMercGoods
	} from "@/api/commodity/goods.js"
	export default {
		components: {
			Classify
		},
		data() {
			return {
				tabList: [{
						name: '私有商品库'
					},
					{
						name: '官方商品库'
					}
				],
				current: 0,
				fullHeight: "0",

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

				// 公库
				pubTabList: [], //商品类目
				pubCommList: [], //商品列表
				pubPage: 1, //商品分页
				pubSize: 10,
				pubStatus: 'loadmore', //加载更多

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

				leftShow: true,
				historyList: [],
				keyword: ''
			}
		},

		onLoad(o) {
			if (o.id) {
				this.id = o.id;
			}
			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 - 84 + 'px';
						} else {
							_this.fullHeight = res.windowHeight - _this.top - 54 + 'px';
						}
					},
				});
			}).exec();

			if (uni.getStorageSync('goods')) {
				this.historyList = JSON.parse(uni.getStorageSync('goods'))
			}
			this.getPerCategory()
			this.getPubCategory()
		},

		async onShow() {
			this.perReset()
			this.pubReset()
			await this.getPerCommList()
			await this.getPubCommList()
		},

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

			search(val) {
				this.saveKeyWord('goods', this.keyword)
				if (this.current == 0) { //私库
					this.perReset();
					this.getPerCommList()
				} else { //公库
					this.pubReset();
					this.getPubCommList()
				}
			},

			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()
					}
				});
			},

			/************************ 私库方法 ********************************/
			// 搜索商品
			searchClick() {
				let storeName = this.current == 0 ? 'perStor' : 'pubStor'
				this.$tab.navigateTo('/pages/commodity/allGoodsSearch?type=' + this.current + '&storeName=' + storeName +
					'&id=' +
					this.id)
			},

			//获取类目列表
			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
						},
						deviceId: this.id
					}
				} else { //非搜索
					params = {
						page: {
							current: this.perPage,
							size: this.perSize
						},
						deviceId: this.id,
						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 = [];
			},

			//新建模块商品先需要设置价格
			comClick(e) {
				uni.showModal({
					title: '提示',
					content: '当前商品为新商品需先设置商品价格,是否前往设置?',
					success: res => {
						if (res.confirm) {
							this.$tab.navigateTo('/pages/commodity/comEdit?id=' + e.id)
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},


			/********************** 公库方法 *************************/
			//获取类目列表
			getPubCategory() {
				return new Promise((resolve, reject) => {
					pubGoodsCategory({
						deviceId:this.id
					}).then(res => {
						if (res.data && res.data.length > 0) {
							this.pubTabList = res.data.map(i => {
								if (i.categoryCode == null) {
									i.categoryName = '未定义'
									return i
								} else {
									return i
								}
							});
							if (this.pubTabList && this.pubTabList.length > 0) {
								this.categoryCode = this.pubTabList[0].categoryCode
							}
						}
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},

			//商品类目切换
			pubSwitchMenu(item) {
				this.categoryCode = item.categoryCode
				this.pubReset()
				this.getPubCommList()
			},

			//根据类目获取商品列表
			getPubCommList() {
				let params = {}
				if (this.leftShow) { //搜索
					params = {
						categoryCodeLevel1: this.categoryCode,
						page: {
							current: this.pubPage,
							size: this.pubSize
						},
						deviceId: this.id
					}
				} else { //非搜索
					params = {
						page: {
							current: this.pubPage,
							size: this.pubSize
						},
						deviceId: this.id,
						keyword: this.keyword
					}
				}
				return new Promise((resolve, reject) => {
					pageByGoods(params).then(res => {
						let data = res.data.records;
						let newData = data.map(i => {
							i.categoryCode = i.categoryCodeLevel1;
							i.noSelect = i.isBind;
							return i
						})
						if (data.length < 10) {
							this.pubStatus = "nomore"
						} else {
							this.pubStatus = "loadmore"
						}
						this.pubCommList = this.pubCommList.concat(newData)
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},

			//触底加载更多
			pubLowerBottom() {
				if (this.pubStatus == 'nomore') return
				this.pubPage++
				this.getPubCommList()
			},

			//重置
			pubReset() {
				this.pubStatus == 'loadmore'
				this.pubPage = 1;
				this.pubSize = 10;
				this.pubCommList = [];
			},

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

			change(e) {
				this.current = e.detail.current
			},

			/**
			 * 添加商品
			 * 私库添加到设备,不需要设置参数
			 */
			addCom() {
				let storeName = this.current == 0 ? 'perStor' : 'pubStor';
				if (uni.getStorageSync(storeName) && JSON.parse(uni.getStorageSync(
						storeName)).length > 0) {
					if (this.current == 0) { //私库
						let commList = JSON.parse(uni.getStorageSync(storeName))
						let goodsIdList = commList.map(i => {
							return i.goodsId
						})
						bindDeviceByMercGoods({
							deviceIds: [this.id],
							goodsIdList: goodsIdList
						}).then(res => {
							if (res.code == 200) {
								this.$modal.msg('添加成功~')
								uni.setStorageSync(storeName, '') //清空购物车
								setTimeout(() => {
									// this.$tab.redirectTo(`/pages/equipment/comManage?id=${this.id}`)
									uni.navigateBack({
										delta: 1
									})
								}, 1000)
							}
						})
					}
					if (this.current == 1) { //公库
						let url = '';
						let type = this.current == 0 ? 1 : 2;
						url = `/pages/equipment/addComList?type=${type}&storeName=${storeName}&id=${this.id}`
						this.$tab.navigateTo(url)
					}
				} else {
					uni.$u.toast('请先选择商品！')
					return
				}
			},

			//私库添加至设备
			perToDev() {
				uni.showModal({
					title: '提示',
					content: '是否确认添加商品',
					success: res => {
						if (res.confirm) {

						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		height: calc(100vh);
		/* #ifdef H5 */
		height: calc(100vh - var(--window-top));
		/* #endif */
		display: flex;
		flex-direction: column;

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

		.tab-list {
			display: flex;
			flex-flow: row nowrap;
			justify-content: space-around;

			.tab-left {
				width: 60%;
			}

			.use-list {
				font-size: 30rpx;
				color: #606266;
				line-height: 88rpx;
				padding-right: 24rpx;
			}
		}

		.content {}
	}

	.swiperitem-content {
		// position: relative;
	}

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