<template>
	<view class="pages">
		<!-- head -->
		<sklineHeader :title="title"></sklineHeader>
		<!-- body -->
		<scroll-view 
		class="scrollPage-body" 
		:style="{height: (screenHeight - statusBarHeight - safeAreaBottom - 40) + 'px'}" 
		scroll-y="true" 
		type="custom" 
		:bounces="false"
		@scrolltolower="reachBottom">
			<!-- 搜索，吸顶 -->
			<sticky-header>
				<view class="search-head">
					<uni-search-bar v-model="queryWord" :focus="focus" radius="100" placeholder="请输入商品名称/产品编码/原厂编码" textColor="#666" clearButton="auto" cancelButton="none" @input="searchChange" @confirm="searchList" @clear="clearList" />
				</view>
			</sticky-header>
			<!-- 产品列表 -->
			<chooseProductItem
			v-for="(item, index) in list"
			:key="item.id"  
			:index="index"
			:list="item" 
			:isLogin="hasLogin"
			@toDetail="viewDetail"
			>
			</chooseProductItem>
			<!-- loading -->
			<view class="loading-bar" v-if="loading||loadEnd">{{loadText}}</view>
			<!-- <view class="empty-bar" v-if="total==0&&!loading">
				<image mode="aspectFit" :src="empty.imgUrl"></image>
				<view>{{empty.tip}}</view>
			</view> -->
			<!-- 搜索记录 -->
			<view class="search-history" v-if="historyList.length&&list.length==0&&queryWord==''&&clzId==''">
				<view class="search-history-title">
					<text>搜索记录</text>
					<view class="search-history-right">
						<view class="search-history-expend" v-if="searchHistoryList.length>10" @click="expend=!expend">
							{{expend?'收起':'展开'}}
							<uni-icons :type="expend?'arrowup':'arrowdown'" size="14"></uni-icons>
						</view>
						<uni-icons type="trash" size="18" @click="clearHistory" color="#eb0000"></uni-icons>
					</view>
				</view>
				<view class="search-history-body">
					<view class="item" v-for="item in historyList" :key="item.id" @click="toSearch(item)">
						<text class="ellipsis-one" max-lines="1" overflow="ellipsis">{{item.text}}</text>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
	    mapState,
	    mapMutations,
	} from 'vuex'
	import sklineHeader from '@/components/skline/sklineHeader.vue'
	import chooseProductItem from '@/pagesB/components/chooseProductItemSkline.vue'
	import { getShopProductList } from '@/api/shop.js'
	export default {
		components:{
			chooseProductItem,
			sklineHeader
		},
		data() {
			return {
				title: '',
				loadText: '加载中...',
				empty: {
					tip: '暂无商品',
					imgUrl: '/static/nodata.png'
				},
				queryWord:'',
				screenWidth: 325,
				screenHeight: 0,
				statusBarHeight: 44,
				safeAreaBottom: 0,
				pageSize: 10,
				pageNo:1,
				total:0,
				list: [],
				loading:false,
				loadEnd: false,
				searchHistoryList: [],
				focus: false,
				expend: false,
				clzId: null, // 一级分类
				categorySn: null ,// 当前分类sn
			};
		},
		computed: {
			...mapState(['hasLogin']),
			historyList() {
				return this.searchHistoryList.filter(item=>!!item.text).reverse().slice(0,this.expend?20:10)
			},
			// 登录用户信息
			userInfo(){
				return this.$store.state.vuex_userInfo
			},
		},
		onLoad(opts) {
			// 计算区域高度
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight
			this.screenWidth = uni.getSystemInfoSync().windowWidth
			this.screenHeight = uni.getSystemInfoSync().windowHeight
			this.safeAreaBottom = uni.getSystemInfoSync().safeAreaInsets.bottom
			// 一级分类id
			this.clzId = opts.clzId
			// 搜索商品
			if(opts.clzId==''){
				this.title = '商品搜索'
				this.focus = true
			} 
			// 搜索历史
			this.searchHistoryList = uni.getStorageSync('searchHistoryList') || []
		},
		onUnload() {
			// 历史记录最多存30条
			if(this.searchHistoryList.length>30){
				this.searchHistoryList = this.searchHistoryList.slice(this.searchHistoryList.length-30,this.searchHistoryList.length)
				uni.setStorageSync('searchHistoryList', this.searchHistoryList)
			}
		},
		methods: {
			// 返回
			goBack(){
				uni.navigateBack()
			},
			// 清空历史记录
			clearHistory(){
				const _this = this
				uni.showModal({
					title: '提示',
					content: '确定清空搜索历史？',
					confirmText: '确定',
					success(res) {
						if(res.confirm){
							_this.searchHistoryList = []
							uni.setStorageSync('searchHistoryList', _this.searchHistoryList)
						}
					}
				})
			},
			// 清空搜索
			clearList(){
				this.queryWord = ''
				this.list = []
				this.total = 0
				this.pageNo = 1
				this.loadEnd = false
				this.loadText = '没有找到相关产品'
			},
			// 失去焦点
			searchChange(){
				if(this.queryWord == ''){
					this.clearList()
				}
			},
			// 选择搜索记录
			toSearch(item){
				this.queryWord = item.text
				this.searchList()
			},
			// 搜索列表
			searchList(event) {
				 //  存储搜索记录
				 const has = this.searchHistoryList.some(k => k.text == this.queryWord)
				 if(!has && this.queryWord!=''){
					 this.searchHistoryList.push({
						 id: new Date().getTime(),
						 text: this.queryWord
					 })
					 uni.setStorageSync('searchHistoryList', this.searchHistoryList)
				 }
				 if(this.queryWord != ''){
					 this.loadEnd = false
					 this.loadText = '加载中...'
					 this.list = []
					 this.pageNo = 1
					 this.getList()
				 }
			},
			// 滚动到底部
			reachBottom() {
				console.log(11)
				if(!this.loading && !this.loadEnd){
					this.pageNo++
					this.getList()
				}
			},
			// 列表查询
			getList(){
				this.loading = true
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				const storeShelf = this.$store.state.vuex_storeShelf
				const dealerSn = this.hasLogin && this.userInfo && this.userInfo.sysUserFlag == '1'&&storeShelf ? storeShelf.dealerSn : ''
				getShopProductList({
					pageNo: this.pageNo,
					pageSize: this.pageSize,
					productCode: this.queryWord,
					categorySn: this.categorySn,
					dealerSn: dealerSn,
					status: 1
				}).then(res => {
					if(res.status == 200){
						this.total = Number(res.data.count)
						if(this.total){
							const list = res.data.list || []
							const ret = list.map(k => {
								const a = k.shopPromoProduct
								if(a){
								  k.promoType = a.promoType
								  k.resultValue = a.resultValue
								  k.conditionValue = a.conditionValue
								  k.discountType = a.discountType
								  k.promoProductSn = a.promoProductSn
								  k.promoSn = a.promoSn
								  k.orginPrice = k.price
								  // 特价
								  if(k.promoType=='PROMO_PROD'){
									 k.price = k.conditionValue
								  }
								}
								return {
								  id: k.id,
								  price: k.price,
								  orginPrice: k.orginPrice,
								  priceStr: Number(k.price).toFixed(2).toString().split('.'),
								  productCode: k.productCode,
								  productSn: k.productSn,
								  productImage: k.productMsg,
								  productName: k.productName,
								  productOrigCode: k.productOrigCode,
								  categorySn: k.categorySn,
								  hotFlag: k.hotFlag,
								  productSn: k.productSn,
								  priceType: k.priceType,
								  shopProductSn: k.shopProductSn,
								  status: k.status,
								  statusDictValue: k.statusDictValue,
								  dealerScopeFlag: k.dealerScopeFlag,
								  promoType: k.promoType,
								  resultValue: k.resultValue,
								  conditionValue: k.conditionValue,
								  discountType: k.discountType,
								  promoProductSn: k.promoProductSn,
								  promoSn: k.promoSn
							  }
							})
							// 追加数据
							this.list.push(ret)
							// 判断是否最后一页
							const maxPages = Math.ceil(this.total / this.pageSize)
							if(this.pageNo >= maxPages){
								this.loadEnd = true
								this.loadText = '没有更多了'
							}
						}else{
							this.loadEnd = false
							this.loadText = '没有找到相关产品'
						}
					}else{
						this.loadEnd = false
						this.loadText = res.message
					}
					uni.hideLoading()
					this.loading = false
				}).catch(err => {
					this.loading = false
				})
			},
			// 产品详情查看
			viewDetail(item){
				uni.navigateTo({
					url:'/pagesB/shopiing/productDetail?sn='+item.shopProductSn
				})
			}
		}
	}
</script>

<style lang="less">
.pages{
	height: 100vh;
	display: flex;
	flex-direction: column;
	.scrollPage-body{
		width:100%;
		.uni-searchbar{
			background-color: #FFFFFF;
		}
		/deep/ .choose-product-item{
			background-color: #FFFFFF;
			margin: 6px 10px;
			border-radius: 6px;
		}
		.loading-bar{
			text-align: center;
			padding: 10px 0;
			color: #999999;
		}
		.empty-bar{
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 20px 0;
			image{
				width: 100px;
				height: 100px;
			}
			view{
				font-size: 12px;
				color: #999999;
			}
		}
		.search-history{
			padding: 0 1.5rem;
			.search-history-title{
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 6px 0;
				font-size: 14px;
				color: #333333;
				border-bottom: 1px solid #E6E6E6;
			}
			.search-history-right{
				display: flex;
				align-items: center;
			}
			.search-history-expend{
				display: flex;
				align-items: center;
				font-size: 12px;
				margin-right: 15px;
			}
			.search-history-body{
				display: flex;
				flex-wrap: wrap;
				align-items: center;
				justify-content: space-between;
				padding: 10px 10px;
				.item{
					padding: 6px 0;
					background-color: #f8f8f8;
					border-radius: 20px;
					font-size: 12px;
					color: #333333;
					width: 46%;
				}
			}
		}
	}
}
</style>
