<template>
	<view class="container home clearfix" :style="{paddingTop:CustomBar+'px'}">
		<customer ref="customer" :navbar-data='nvabarData'></customer>
		<!-- 主页内容 -->
		<tui-skeleton v-if="skeletonShow" backgroundColor="#fafafa" borderRadius="10rpx" :isLoading	="true" :loadingType="5"></tui-skeleton>
		<view class="container-home tui-skeleton">
			<!-- 轮播 -->
			<banner :list="bannerImageList" v-if="isRequest"></banner>
			<!-- 金刚区菜单 -->
			<navbars :list="navBarsList" v-if="isRequest"></navbars>
		</view>	
		<view class="container-section tui-skeleton">
			<!-- 推荐专区 -->
			<hot-product :list="RecommendList" :userIdentity="userIdentity" v-if="isRequest"></hot-product>
			<!-- 楼层 -->
			<pages-product :list="pagesList" v-if="isRequest"></pages-product>
			<!-- 商品专题 -->
			<special-product :list="specialList" :listB="specialProList" v-if="isRequest"></special-product>
			<!-- 供应商专题 -->
			<supplier-list :list="supplierList" v-if="isRequest"></supplier-list>
		</view>
		<!-- 侧边 -->
		<scroll-top v-if="isScrollTop"></scroll-top>
	</view>
</template>

<script>
	import tuiSkeleton from "@/components/tui-skeleton/tui-skeleton"
	import authorize from '@/common/config/authorize.js'
	import customer from '@/components/cm-module/homeIndex/customer.vue'
	import banner from '@/components/cm-module/homeIndex/banner.vue'
	import navbars from '@/components/cm-module/homeIndex/navbars.vue'
	import hotProduct from '@/components/cm-module/homeIndex/hotProduct.vue'
	import pagesProduct from '@/components/cm-module/homeIndex/pagesProduct.vue'
	import specialProduct from '@/components/cm-module/homeIndex/specialProduct.vue'
	import supplierList from '@/components/cm-module/homeIndex/supplierList.vue'
	import { userInfoLogin } from "@/api/use.js"
	import { mapState,mapMutations} from 'vuex';
	export default {
		components:{
			tuiSkeleton,
			customer,
			hotProduct,
			banner,
			navbars,
			pagesProduct,
			specialProduct,
			supplierList
		},
		data() {
			return {
				webviewStyles: {
					progress: {
						color: '#FF3333'
					}
				},
				nvabarData: {//顶部自定义导航
					showCapsule: 1, // 是否显示左上角图标  1表示显示  0表示不显示,
					showSearch: 0,
					title: '采美采购商城', // 导航栏 中间的标题
					haveBack:false,
					textLeft:this.$store.state.isIphone,
					textColor:'#FFFFFF'
				},
				CustomBar:this.CustomBar,// 顶部导航栏高度
				userID:0,
				clubStatus:'',
				current:0,
				mode:'round',
				modallayer:false,
				isLogin:false,
				skeletonShow: true,
				userIdentity:'',
				bannerImageList:[],//轮播
				navBarsList:[],//导航分类
				pagesList:[],//楼层
				RecommendList:[],//热门推荐
				specialList:[],//商品专题轮播
				specialProList:[],//商品专题商品
				supplierList:[],//供应商列表
				organizeProducts:[],//常用商品
				productsClassifyList:[
					{classifyImage:'https://admin-b.caimei365.com/userfiles/1/images/photo/2020/04/%E7%BB%84%201238.png',classifyName:'采美'},
					{classifyImage:'https://admin-b.caimei365.com/userfiles/1/images/photo/2020/04/%E7%BB%84%201238.png',classifyName:'采美'},
					{classifyImage:'https://admin-b.caimei365.com/userfiles/1/images/photo/2020/04/%E7%BB%84%201238.png',classifyName:'采美'},
					{classifyImage:'https://admin-b.caimei365.com/userfiles/1/images/photo/2020/04/%E7%BB%84%201238.png',classifyName:'采美'},
					{classifyImage:'https://admin-b.caimei365.com/userfiles/1/images/photo/2020/04/%E7%BB%84%201238.png',classifyName:'采美'}
				],//分类导航
				firstModulesName:'https://img.caimei365.com/group1/M00/03/8C/Cmis215XHXSAAZU0AACaPrfbB8I435.png', //优惠模块1
				secondModulesName:'', //优惠模块2
				firstModulesImage:'https://img.caimei365.com/group1/M00/03/8C/Cmis215XHXSAAZU0AACaPrfbB8I435.png',//优惠模块icon1
				secondModulesImage:'',//优惠模块icon2
				thirdModulesName:'', //优惠模块3
				navInforList:[
					{text:'会员中心',icon:'https://img.caimei365.com/group1/M00/03/B0/Cmis217Z9LCABdf_AAAfdMmM_xY655.png'},
					{text:'在线客服',icon:'https://img.caimei365.com/group1/M00/03/B0/Cmis217Z9BSAXPobAAApo6I0Tlo684.png'}
				],
				navServerList:[
					{text:'会员优惠',icon:'../../../static/temp/server1@2x.png',path:'/pages/service/member'},
					{text:'售后无忧',icon:'../../../static/temp/server2@2x.png',path:'/pages/service/aftersale'},
					{text:'购物须知',icon:'../../../static/temp/server3@2x.png',path:'/pages/service/shoppingnotice'},
					{text:'联系我们',icon:'../../../static/temp/server4@2x.png',path:''},
				],
				isScrollTop:false,
				isRequest:false
			}
		},
		onLoad() {
			
		},
		computed: {
			...mapState(['hasLogin','userInfo','isActivity'])
		},
		methods: {
			...mapMutations(['login','logout']),
			getWxAuthorize(){
				authorize.getCode('weixin').then(wechatcode =>{// 根据微信的code获取用户登录状态:1已登录过 -1未登录过
					authorize.getUserInfo('weixin').then(wxResponse =>{
						userInfoLogin({code:wechatcode,encryptedData:wxResponse.encryptedData,iv:wxResponse.iv}).then(response =>{
							this.isLogin = true;
							this.userID = response.data.userID;						
							this.userIdentity = response.data.userIdentity;						
							this.clubStatus = response.data.clubStatus;						
							this.$store.commit('updateStatus',response.data)
							this.login(response.data);
							uni.setStorageSync('token',response.data.token)
							uni.removeStorageSync('sessionid')
							uni.setStorageSync('sessionid','JSESSIONID='+response.data.sessionId)
							if(response.data.userIdentity ==1){
								this.$api.navigateTo('/seller/pages/index/index')
							}else if(response.data.userIdentity === 3){
								this.$api.navigateTo('/supplier/pages/index/index')
							}
							this.GetHomeFloorInfo()
							this.getHomeInformation()
						}).catch(error =>{
							this.isLogin = false;
							this.logout()
							uni.removeStorageSync('sessionid')
							uni.setStorageSync('sessionid','JSESSIONID='+error.data)
							this.$store.commit('updateStatus',error.data)
							this.GetHomeFloorInfo()
							this.getHomeInformation()
							
						})
					})
				})
			},		
			GetHomeInit(){//金刚区分类
				this.CommonService.GetHomeInit({}).then(response =>{
					let data = response.data
					this.navBarsList = data.topMenuList
				}).catch(error =>{
					this.$util.msg(error.msg,2000)
				})
			},
			GetHomeFloorInfo(){//初始化首页楼层数据
				this.CommonService.GetHomeFloorInfo({}).then(response =>{
					let data = response.data
					data.forEach((item,index) => {
						switch(item.type){
							case 3:
								this.supplierList = item.floorData
								break;	
							case 4:
								this.specialList = item.floorData
								break;	
							case 5:
								this.specialProList = item.floorData
								break;	
							case 6:
								this.pagesList = item.subFloors
								break;
						}
					})
				}).catch(error =>{
					this.$util.msg(error.msg,2000)
				})
			},
			getHomeInformation(){//初始化首页数据	
				this.CommonService.GetHomeModulesDataInfo({ userId:this.userID }).then(res =>{
					let data = res.data;
					this.bannerImageList = data.bannerImageList
					this.mallPageModules = data.mallPageModules
					this.firstModulesName= data.firstModulesName
					this.secondModulesName= data.secondModulesName
					this.firstModulesImage= data.firstModulesImage
					this.secondModulesImage= data.secondModulesImage
					this.thirdModulesName= data.thirdModulesName
					this.productsClassifyList = data.productsClassifyList
					this.$store.commit('updateAllNum',data.shoppingCartCount)
					this.GetHomeInit();
					this.GetHomeRecommendInfo()
				}).catch(error =>{
					this.$util.msg(error.msg,2000)
				})
			},
			GetHomeRecommendInfo(){//首页热门推荐
				this.CommonService.GetHomeRecommendInfo().then(response =>{
					this.RecommendList = response.data
					this.GetProductPrice()
				})
			},
			GetProductPrice(){//获取商品或者活动价格
				let productIdArr = [];
				let productIds ='';
				this.RecommendList.map(item=>{// 0公开价格 1不公开价格 2仅对会员机构公开
					productIdArr.push(item.id)
				})
				productIds = productIdArr.join(",");
				this.ProductService.querySearchProductPrice({userId: this.userID,productIds:productIds}).then(response =>{
					this.RecommendList = this.ReturnNewProducts(this.RecommendList,response.data);
					this.skeletonShow = false;
					this.isRequest = true
				}).catch(error =>{
					this.$util.msg(error.msg,2000)
				})
			},
			ReturnNewProducts(Array,list){
				let NewArray = []
				Array.map(item=>{
					for (let i = 0; i < list.length; i++) {
						if( item.id == list[i].productId ){
							NewArray.push(Object.assign(item,list[i])) 
						}
					}
				});
				return NewArray
			},
			PromotionsFormat(promo){//促销活动类型数据处理
				if(promo!=null){
					if(promo.type == 1 && promo.mode == 1){
						return true
					}else{
						return false
					}
				}
				return false
			},
			//轮播图切换修改背景色
			swiperChange(e) {
				const index = e.detail.current;
				this.current = index;
			},
			formatMoney(num){
				return num.toString().replace(/\d+/, function (n) { // 先提取整数部分
					return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) { // 对整数部分添加分隔符
						return $1 + ",";
					});
				});
			},
			handleBannerActivity(item,index){
				switch(index){
					case 0:
						this.$api.navigateTo(`/h5/pages/activity/activity_mid`)
						break;
				}
			},
			handleClick(data){
				this.$api.navigateTo(`/h5/pages/activity/activity_mid`)
				this.$store.commit('setActivity',data)
			},
			handleCancelClick(data){
				this.$store.commit('setActivity',data)
			},
			navToListPage(nav){//三个分类模块跳转
				let self = this;
				uni.setStorage({
					key: 'commodity_id',
					data: nav.id,
					success: function () {
						self.$api.navToListPage({type:'0',value:nav.classifyName,id:nav.id});
					}
				})
			},
			navigateToGoods(nav){//分类导航跳转
				let self = this;
				uni.setStorage({
					key: 'commodity_id',
					data: nav.id,
					success: function () {
						self.$api.navigateToGoods({type:'0',value:nav.classifyName,id:nav.id});
					}
				})
			},
			navToDetailPage(id) {//跳转商品详情页
				this.modallayer = true;
				this.$api.navigateTo(`/pages/goods/product?id=${id}`)
			},
			handleContact(e){
				console.log(e.detail.path)
				console.log(e.detail.query)
			},
			showTost(){
				this.$util.msg("功能开发中，敬请期待~",2000)
				// this.$api.navigateTo(`/seller/pages/login/login`)
				// uni.navigateToMiniProgram({
				// 	appId: 'wx5a5cda32926f55ac',
				// 	path: '/pages/tabBar/home/index',
				// 	extraData: {
				// 		'data1': 'test'
				// 	},
				// 	envVersion: 'develop',
				// 	success(res) {
				// 		console.log(res)
				// 		// 打开成功
				// 	}
				// })
			},
			navto(url){
				this.$api.navigateTo(url)
			},
			swiperNavtopage(link){
				this.$api.navigateTo(`/h5/pages/activity/activity?productID=4204&path=${link}`)
			},
			telPhoneTo(){
				let self = this;
				this.$api.get('/home/afterSale',{organizeID:this.userOrganizeID}, 
					response => {
						console.log(response.data.contactNumber)
						uni.makePhoneCall({
							phoneNumber:response.data.contactNumber //仅为示例
						});
					}
				)	
			}
		},
		onPageScroll(e){//实时获取到滚动的值
			if(e.scrollTop>50){
				this.inputActive = 'fixed'
			}else{
				this.inputActive = 'float'
			}	
			if(e.scrollTop>400){
				this.isScrollTop = true
			}else{
				this.isScrollTop = false
			}	
		},
		onPullDownRefresh() {//下拉刷新
			this.getHomeInformation()
			uni.stopPullDownRefresh()
		},
		onShareAppMessage(res){//分享转发
			if (res.from === 'button') {
		      // 来自页面内转发按钮
		    }
			return {
			  title: '采美采购商城-生美/医美采购服务平台',
			  path: 'pages/tabBar/home/home',
			  imageUrl:'https://img.caimei365.com/group1/M00/03/8C/Cmis215XHXSAWWkhAAXDP4-6m_c397.png'
			}
		},
		onShow(){
			this.modallayer = false;
			authorize.getSetting().then(res =>{// console.log('是否已授权',res);//0:为取消授权 1:为已授权 2:为未操作
				if(res == 1){
					this.getWxAuthorize()
				}else{
					this.$api.getComStorage('userInfo').then((resolve) =>{
						this.userID = resolve.userID ? resolve.userID :0;
						this.getHomeInformation()
					}).catch(error =>{
						this.getHomeInformation()
					})
				}
			})		
		}
	}
</script>

<style lang="scss">
	page{
		background-color: #FFFFFF;
	}
	.container-section{
		width: 100%;
		height: auto;
		background-color: #F7F7F7;
	}
</style>
