<template>
	<view class="pages index">
		<view class="search-wrap">
			<view class="search">
				<view class="searchTxt">
					<!-- <uni-search-bar @confirm="search" @input="search" ></uni-search-bar> -->
					<uni-search-bar @confirm="search" ></uni-search-bar>
				</view>
			</view>	
		</view>
		<!-- 搜索 结束 -->
		<view class="appAdv nomal-bottom">
			<swiper class="swiper" @change="swiperchange" :indicator-dots="swiper.indicatorDots" :previous-margin="swiper.previousmargin" :next-margin="swiper.nextmargin" :autoplay="swiper.autoplay" :interval="swiper.interval" :duration="swiper.duration">
				<swiper-item v-for="(item,index) in advertiseList" :key="index">
					<view class="adv-item" :class="{active:index==currentswiper}" @click="jumLink(item.url)">
						<image :src="$getimg+item.pic|miniImg(75)+'/thumbnail/600x300'" class="pic" mode="scaleToFill"></image>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<!-- 轮播结束 -->
		<view class="quick-links wrap write-radius nomal-bottom">
			<navigator class="quick-links-item" url="/pages/supplier/supplier">
				<view class="quick-links-item-til">供应商</view>
				<view class="quick-links-item-subtil">保供稳价</view>
				<view class="quick-links-item-img"><image src="/static/img/quick-links-04.png" mode="scaleToFill"></image></view>				
			</navigator>
			
			<navigator class="quick-links-item" url="/pages/inbuild/inbuild">
				<view class="quick-links-item-til">产品溯源</view>
				<view class="quick-links-item-subtil">低价货源</view>
				<view class="quick-links-item-img"><image src="/static/img/quick-links-02.png" mode="scaleToFill"></image></view>				
			</navigator>
			
			<navigator class="quick-links-item" url="/pages/inbuild/inbuild">
				<view class="quick-links-item-til">基地展示</view>
				<view class="quick-links-item-subtil">轻松卖货</view>
				<view class="quick-links-item-img"><image src="/static/img/quick-links-03.png" mode="scaleToFill"></image></view>				
			</navigator>
			
			<navigator class="quick-links-item" url="/pages/inbuild/inbuild">
				<view class="quick-links-item-til">价格行情</view>
				<view class="quick-links-item-subtil">全国走货</view>
				<view class="quick-links-item-img"><image src="/static/img/quick-links-01.png" mode="scaleToFill"></image></view>				
			</navigator>
		</view>
		<!-- 快速导航 结束 -->
		<view class="category nomal-bottom">
			<view class="category-item category-item-all" @click="category()" :class="{active:categoryall==true}">全部</view>
			<scroll-view scroll-x="true" class="scroll-X category-scroll-view">
				<view v-for="(item,index) in categorylink" :key="index" @click="categoryclick(index)" :class="{active:index==ins && notall==true}" class="category-item">{{item.name}}</view>
			</scroll-view>			
			<navigator class="category-item category-item-more" url="/pages/productcategory/productcategory">更多</navigator>
			<!-- <navigator v-for="(item,index) in categorylink" :key="index" class="category-item" :url="'pages/searchresults/searchresults?type=' + item">{{item}}</navigator> -->
		</view>
		<!-- 分类链接结束 -->	
		<mescroll-body class="wrap" ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption" :up="upOption">
			<view class="indexproduct">
				 <view class="item-wrap" v-for="(item,index) in mescrollList" :key="index">
					<view class="item" :data-id="item.id" @click="jumpDetails(item.id)">
						<view class="item-img-wrap">
							<image :src="$getimg+item.pic|miniImg(60)+'/thumbnail/358x354'||'/static/img/inbuild.png'" class="item-img" mode="aspectFit"></image>
						</view>
						<view class="item-text-wrap">
							<view class="merchant f-ellipsis">
								{{item.brandName}}
								<!-- <text v-if="item.postage" class="postage">包邮</text> -->
							</view>
							<view class="item-til f-ellipsis">{{item.name}}</view>							
							<view class="item-addr f-ellipsis">{{item.umsCompanyInfo}}</view>
							<view class="item-price-info">
								<text class="rmb" v-if="item.price">¥</text>
								<text class="price" :class="!item.price?'noprice':''">{{item.price||"暂无价格"}}</text>
								<text class="unit" v-if="item.unit">/{{item.unit}}</text>
								</view>
						</view>						
					</view> 
				 </view>
			 	
			</view>			 
		</mescroll-body>
		<!-- 商品展示结束 -->
		
		
		
	</view>
</template>

<script>
	// #ifdef H5
	import { mapMutations } from 'vuex';
	// #endif
	import uniSearchBar from '@/components/uni-search-bar/uni-search-bar.vue'
	// 引入mescroll-mixins.js
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";	
	// 引入mescroll-body组件 (如已在main.js注册全局组件,则省略此步骤)
	import MescrollBody from "@/components/mescroll-uni/mescroll-body.vue"; // 注意.vue后缀不能省
	export default {
		mixins: [MescrollMixin], // 使用mixin
		components: {
			MescrollBody,
			uniSearchBar,
		},
		data() {
			return {
				params:{
					token:'',
					tokenhead:'',
					keyword:'',
					productCategoryId:'',
					// productCategoryName:'',
				},
				//轮播数据
				advertiseList:[],
				swiper: {
					indicatorDots: true,
					autoplay: false,
					interval: 9000,
					duration: 500,
					previousmargin:'55rpx',
					nextmargin:'55rpx'
				},
				currentswiper:0,
				categorylink:[],
				mescroll: null, // mescroll实例对象 (此行可删,mixins已默认)
				// 下拉刷新的配置(可选, 绝大部分情况无需配置)
				downOption: { 
					// ...
				},
				// 上拉加载的配置(可选, 绝大部分情况无需配置)
				upOption: {
					page: {
						size: 10 // 每页数据的数量,默认10
					},
					noMoreSize: 5, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
					empty: {
						tip: '暂无相关数据'
					}
				},
				// 列表数据
				mescrollList:[],
				//category active
				ins:null,
				//category all
				categoryall:true,
				notall:false,
				thispage:'',
				
			}
		},
		onLoad() {
			let serf = this;
			//检查登录,获取token
			// let loginRes = this.checkLogin('/pages/index/index', '2');
			// if(!loginRes){return false;}
			// serf.params.token=loginRes[0];
			let locationLocaturl = window.location.search;
			function getUrlParams(url) {
				if (decodeURIComponent(url).indexOf('?') > -1) {
					var result = [];
					var urlParamsArr = decodeURIComponent(url).split('?');
					urlParamsArr.shift();
					let newUrlParamsArr = urlParamsArr.join('&').split('&');
					for (var i = 0; i < newUrlParamsArr.length; i++) {
						var paramKey = newUrlParamsArr[i].split('=')[0];
						var paramValue = newUrlParamsArr[i].split('=')[1];
						result.push({
							key: paramKey,
							value: paramValue
						});
					}
					return result;
				} else {
					console.log('该URL中不含参数');
				}
			};
			this.thispage = `/pages/index/index`;
			let locationArr = getUrlParams(locationLocaturl);
			if(!locationArr){
				window.location.replace(this.config.loginUrl);
				return
			};
			let itemtoken = locationArr.find(function(locationArr) {
				return locationArr.key === 'token';
			});
			let itemtokenHead = locationArr.find(function(locationArr) {
				return locationArr.key === 'tokenHead';
			});
			if (itemtoken) {
				this.params.token = itemtoken.value;				
			}
			if (itemtokenHead) {
				this.params.tokenhead = itemtokenHead.value;				
			}
			if(this.params.tokenhead&&this.params.token){
				let thetoken = this.params.tokenhead+this.params.token;
				this.$api.http.get(this.config.apiBaseurl+'/wechat/h5/info', {header: {Authorization:thetoken}}).then(res => {					
					let userInfo = res.data;
					userInfo.accessToken = this.params.token;
					userInfo.tokenhead = this.params.tokenhead;
					this.setLogin(userInfo);
				}).catch(err => {
					if(err.data.message =='暂未登录或token已经过期'){
						let loginurl = `${this.config.apiBaseurl}/wechat/h5/authorize?returnUrl=${this.thispage}`
						console.log('loginurl',loginurl);
						window.location.replace(loginurl);
						return
					}
					console.log(err)
				});
			};
			//首页内容页信息展示
			this.$api.http.get(this.config.apiBaseurl+'/home/content', {header: {Authorization:this.params.tokenhead+this.params.token}}).then(res => {
				console.log('content',res)
				this.advertiseList = res.data.data.advertiseList;
			}).catch(err => {
				console.log(err)
			});
			//获取产品分类
			this.$api.http.get(this.config.apiBaseurl+'/product/categorySearch', {header: {Authorization:this.params.tokenhead+this.params.token}}).then(res => {
				console.log('产品分类',res)
				this.categorylink = res.data.data;
			}).catch(err => {
				console.log(err)
			});
		
		},
		onShow() {
			
			
			
		},		
		methods: {
			// #ifdef H5
			...mapMutations(['setLogin']),
			// #endif
			
			//搜索
			search(e) {
				console.log(e);
				// url:`/pages/searchresults/searchresults?id=${e}`,
				uni.navigateTo({					
					url:`/pages/searchresults/searchresults?keyword=${e.value}`
				})
			},
			
			/*mescroll组件初始化的回调,可获取到mescroll对象 (此处可删,mixins已默认)*/
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
			},
			/*下拉刷新的回调, 有三种处理方式:*/
			downCallback(){
			
				// 第2种: 下拉刷新和上拉加载调同样的接口, 那么不用第1种方式, 直接mescroll.resetUpScroll()即可
				this.mescroll.resetUpScroll(); // 重置列表为第一页 (自动执行 page.num=1, 再触发upCallback方法 )
			},
			/*上拉加载的回调*/
			upCallback(page) {
				let pageNum = page.num; // 页码, 默认从1开始
				let pageSize = page.size; // 页长, 默认每页10条				
				this.params = Object.assign(this.params,{pageNum:pageNum,pageSize:pageSize});
				this.$api.http.get(this.config.apiBaseurl+'/product/search',{params: this.params}).then(data => {
					if(data.data.code=='1001'){
						// uni.redirectTo({
						// 	url:'/pages/login/login?backpage=/pages/index/index'+'&backtype='+2,
						// });							
					};
					console.log(data);
					// 接口返回的当前页数据列表 (数组)
					let curPageData = data.data.data.list; 
					// console.log('curPageData',curPageData);
					// 接口返回的当前页数据长度 (如列表有26个数据,当前页返回8个,则curPageLen=8)
					let curPageLen = curPageData.length; 
					// 接口返回的总页数 (如列表有26个数据,每页10条,共3页; 则totalPage=3)
					let totalPage =  data.data.data.totalPage; 
					// 接口返回的总数据量(如列表有26个数据,每页10条,共3页; 则totalSize=26)
					let totalSize = data.data.data.total; 
					// this.mescrollList = curPageData;
					// 接口返回的是否有下一页 (true/false)
					// let hasNext = data.xxx; 
					
					//设置列表数据
					if(page.num == 1) this.mescrollList = []; //如果是第一页需手动置空列表
					this.mescrollList = this.mescrollList.concat(curPageData); //追加新数据
					// console.log('page.num',page.num);
					console.log('this.mescrollList',JSON.parse(JSON.stringify(this.mescrollList)));
					// 请求成功,隐藏加载状态
					//方法一(推荐): 后台接口有返回列表的总页数 totalPage
					// this.mescroll.endByPage(curPageLen, totalPage); 
					//方法二(推荐): 后台接口有返回列表的总数据量 totalSize
					this.mescroll.endBySize(curPageLen, totalSize); 
					console.log('pageSize',pageSize,'curPageLen',curPageLen,'totalSize',totalSize);
			
					// setTimeout(()=>{
					// 	this.mescroll.endSuccess(curPageLen)
					// },20)
				
				}).catch(err => {
					this.mescroll.endErr()
					console.log(err)
				
				});
				
			},
			//分类点击
			categoryclick(num){
				this.categoryall = false;
				this.notall = true;
				this.ins=num;
				this.nowtype = this.categorylink[num].name;
				// console.log(this.categorylink[this.ins]);
				this.params.productCategoryId = this.categorylink[this.ins].id;
				// this.params.productCategoryName = this.categorylink[this.ins].productCategoryName;
				console.log('this.params',this.params);
				this.downCallback();
			},
			//全部分类点击
			category(){
				this.categoryall = true;
				this.notall = false;
				this.params.productCategoryId = '';
				this.downCallback();
			},
			
			//轮播链接跳转
			jumLink(url){
				function handleBrowsingItemLink(link){
				  const browsingItemLinkHttp = link.substr(0, 7).toLowerCase();
				  const browsingItemLinkHttps = link.substr(0, 8).toLowerCase();				
				  if (browsingItemLinkHttp === "http://" || browsingItemLinkHttps === "https://") {
				    return link
				  }				
				  return `http://${link}`
				}
				url = handleBrowsingItemLink(url);
				if(!url){uni.showToast({
					title:'地址无效'
				})}
				window.location.assign(url);
				// uni.navigateTo({
				// 	url:`/pages/product/product?id=${id}`,
				// 	fail(err) {
				// 		console.log(err)
				// 	}
				// })
			},
			//产品跳转链接
			jumpDetails(id){
				uni.navigateTo({
					url:`/pages/product/product?id=${id}`,
					fail(err) {
						console.log(err)
					}
				})				
			},
			//swiperchange
			swiperchange(e){
				this.currentswiper = e.detail.current;
			}

		}
	}
</script>

<style scoped>
@import url("./index.css");

</style>
