<template>
  	<view class="shop-index" >
		<!-- #ifdef APP-PLUS || APP -->
		  <!-- <wrap-version-update
				  id="wxf3657c94aa01a3f0"
				  btnBgColor="#66be4d"
		  ></wrap-version-update> -->
		<!-- #endif -->
		
	  	<img src="https://image.jxc4.com/image/0ffc1e09eca6e88cdad5ac43427ce4c4.jpg?imageView2/1/w/750/h/750" class="shop-background" alt="">
	  	<view class="top-address" @tap="toDressPick"  v-if="!isMaterial " :style="{'background':rgba}">
			<view class="position-address">
				<view class="cur-address" v-if="!queryStoreID">
					<span class="icon-position"></span>
					<text class="address">{{address}}</text>
				</view>
				<!-- <div class="cur-shop" @click.stop="switchShop" v-if="storeMap && storeMap[storeID[0]]">{{storeMap[storeID[0]].name}}</div> -->
			</view>
	  	</view>
	  
	  <!-- #ifdef MP-WEIXIN -->
	  <!-- 物料申请说明 -->
	  <view class="material-title"  v-if="(isMaterial && !isPurchase)">
		<text class="text">物料申请说明</text>
	  </view>
	  <!-- 物料申请说明 -->
	  <!-- #endif -->
	  <view class="index-content" :class="{'no-padding': isMaterial  }">
		<!-- 查询按钮 -->
		<view class="top-search-btn"  v-if="!isMaterial ">
		  <SearchBtn @click="handleClickSearch" :isShowBtn="true" ></SearchBtn>
		</view>
		
		<!-- 轮播图 -->
		<!-- previous-margin -->
		<swiper
		  class="index-swiper"
		  indicator-dots
		  indicator-color="rgba(0,0,0, .1)"
		  indicator-active-color="#4EB331"
		  autoplay
		  interval="4000"
		  circular
		  v-if="!isMaterial"
		>
		  <swiper-item
			v-for="item in bannerArr"
			:key="item.id"
			class="index-item"
			@click="jumpToBanner(item)"
		  >
			<img :src="$filters.urlToHttps(item.content.imgSrc)" alt="加载中..." class="index-item-img">
		  </swiper-item>
		</swiper>
  
		<!-- 介绍  -->
		<view class="introduce" v-if="!isMaterial">
		  <text class="itc-item itc-first">最快29分钟送达</text>
		  <text class="itc-item itc-second">满免运费</text>
		  <text class="itc-item itc-last">优鲜赔</text>
		</view>
		
		<!-- 推荐分类 -->
		<view id="RecommendCategory" class="top-cat" v-if="!isMaterial" style="align-items: center;">
		  <view class="cat-item" v-for="cat in topCats" :key="cat.id" @tap="toGoodsByID(cat)" style="text-align: center;">
			<view class="cat-img">
				<image :src="cat.img" alt="" class="cat-img_size" />
			</view>
			<text class="cat-name">{{cat.name}}</text>
		  </view>
		</view>
		<!-- 分类 -->
		
		<!-- #ifdef MP-WEIXIN -->
		<!-- 物料说明 -->
		<view class="material-desc-status" v-if="(isMaterial && !isPurchase)">
		  <view class="material-border">
			<view class="material-desc">
			  <view class="desc-item" v-for="(item, index) in materialDesc" :key="index">{{item}}</view>
			</view>
			<view class="material-status">
			  <view>
				已完成订单的1.1倍：
				<span class="strong">{{preSaleCount}}</span>
			  </view>
			  <view>
				当前袋子申请状态：
				<span class="strong">{{canBuy ? '可申请' : '无法申请'}}</span>
			  </view>
			  <view>已选袋子件数/数量: {{totalBag.unitCount}}件/{{totalBag.totalCount}}个</view>
			  <view :class="{danger: bagOverload !== '未超出购买限制'}">{{bagOverload}}</view>
			</view>
		  </view>
		</view>

		<!-- 猜你喜欢 -->
		<view class="top-goods" ref="top-goods" v-if="isMaterial || queryStoreID">
		  <view class="top-title">
			<span class="icon-border"></span>
			<text class="title">推荐商品</text>
		  </view>
		  <!-- <div > -->
			<!-- 瀑布流 -->
			<!-- <waterfall 
				:value="topGoods" 
				:imageKey="'img'"
				@clickPlus="handleSkuNamePlus"
				@clickMinus="handleSkuNameMinus"
				@countChange="handleSkuNameChange"
			></waterfall> -->
		  <!-- </div> -->

		  <view class="top-goods-list">
			<view
			  class="goods-item"
			  v-for="(skuName, index) in topGoods"
			  :key="skuName.id"
			>
			  <good-cell-big
				ref="goodCellBig"
				:skuName="skuName"
				:index="index"
				@handleSkuNamePlus="handleSkuNamePlus"
				@handleSkuNameMinus="handleSkuNameMinus"
				@handleSkuNameChange="handleSkuNameChange"
			  ></good-cell-big>
			</view>
		  </view>
		</view>
		<!-- #endif -->
  
		<!-- 推荐商家 v-if="!(isMaterial || queryStoreID)" -->
		<view class="top-goods" v-if="!isMaterial">
			<nearStoreCom :storeList="nearlyStores"></nearStoreCom>	
		</view>
  
	  </view>

	  <!-- loading -->
	  <ZyLoading></ZyLoading>

	  <!-- 骨架屏 -->
	  <Bone v-if="showBone"></Bone>
	  
	  <!-- #ifdef MP-TOUTIAO || APP-PLUS -->
	  <!-- 购物车图标 -->
	  <shopCarIcon v-if="isShowShop"></shopCarIcon>
	  <!-- #endif -->
  
	</view>
</template>

<script>
import ZyLoading from "@/components/Loading/loading";
import Bone from "@/components/Loading/bone";
import reComputedCarCount from "@/mixins/reComputedCarCount.js";
import { errToast,jumpPage,queryEleInfo,setTabBarBadge } from "@/utils/uniapi.js"; 
import { mapGetters, mapActions } from "vuex";
import {store} from "@/store";
// import ImgLazyLoad from "@/components/commonCmp/img-lazy/img-lazy";
import goodCellBig from "@/components/goodCmp/good-cell-index/good-cell-big.vue";
// import waterfall from '@/components/waterfall/index.vue'

// import { msgData } from "@/config";
import SearchBtn from "@/components/goodCmp/Search/search-btn";

// #ifdef MP-TOUTIAO || APP-PLUS
import shopCarIcon from '@/components/shopCarIcon/index'
// #endif

import apiStore from '@/apis/apiStore';
import nearStoreCom from '@/components/nearlyStoreCom/index.vue'
// import goodPage from '@/apis/goodPage';

// import {debounce} from '@/utils'
export default {
  name: "ShopIndex",
  mixins: [reComputedCarCount],
  components: {
		ZyLoading,
		Bone,
		goodCellBig,
		SearchBtn,
		// #ifdef MP-TOUTIAO || APP-PLUS
		shopCarIcon,
		// #endif
		nearStoreCom
		// waterfall,
		// waterfallNew,
		// PlusMinus
	},
  data() {
    return {
      		jxBanner: [], //京西banner数组
			bannerID: null,
			showBone: true,
			// showBone: false,
			address: "加载中...",
			topCats: [],
			isOnLoad: false,
			bannerArr: [],
			materialDesc: [],
			brandList: [],
			topToGoods:0,
			rgba: 'rgba(255,255,255,0.5)',
			nearlyStores: [],   // 附近的门店信息  推荐附近的门店
    	}
  },
  mounted() {
		// 获取推荐分类在页面中的信息
		if (!this.isMaterial && !this.storeID.includes(666666)) {
			queryEleInfo(this, '#RecommendCategory').then((res) => {
				if (res !== undefined && res && res.top) {
					this.topToGoods = res.top
				}
			})
		}
	},
	// 监听页面滚动的距离
	onPageScroll: function (Object) {
		let opacity=0
		opacity=Object.scrollTop/this.topToGoods+0.5
		this.rgba=opacity?'rgba(255,255,255,'+opacity+')':"rgba(255,255,255,0.5)"
	},
	computed: {
		...mapGetters({
			loading: "loading",
			confirmCheckShow: "confirmCheckShow",
			isShowShop: 'isShowShop',
			isLogin: "login/isLogin",
			selfInfo: "login/selfInfo",
			myLocation:"indexPage/myLocation",
			reLocation: "indexPage/reLocation",
			indexNeedReload: "indexPage/indexNeedReload",
			pois:"indexPage/pois",
			storeMap:"indexPage/storeMap",
			storeID: "indexPage/storeID",
			isMaterial: "indexPage/isMaterial",
			isPurchase: 'indexPage/isPurchase',
			preSaleCount: "indexPage/preSaleCount",
			totalBag: "indexPage/totalBag",
			canBuy: "indexPage/canBuy",
			topGoods:"indexPage/topGoods",
			storeType:'indexPage/storeType',
			bagOverload: "indexPage/bagOverload",
			brandID:'indexPage/brandID',
			queryStoreID: "indexPage/queryStoreID",
			materialInfo: "indexPage/materialInfo",
		})
	},
	async onLoad(query) {
		if(query.scene && query.scene.includes('orderID')) return
		// 门店
		this.showLoad()
		// #ifdef MP
		if (JSON.stringify(query) !== '{}') {
			await this.sceneValue(query)
		} else {
			if (uni.getStorageSync('materialInfo')) store.commit('indexPage/saveMaterialInfo', uni.getStorageSync('materialInfo'))
			else if (uni.getStorageSync('queryStoreID')) {
				store.commit('indexPage/saveQueryStoreID', uni.getStorageSync('queryStoreID'))
				store.commit('indexPage/changeStoreType',uni.getStorageSync('storeType') === 'gy')
			}
			else if(uni.getStorageSync('brandID')) await store.dispatch('indexPage/getBrandInfo',{brandID:uni.getStorageSync('brandID')})	 // 公众号进入
		}
		// #endif
		await this.pageInit();	// 初始化门店信息

		store.commit('indexPage/indexNeedReload',false)	// 去掉首页的重载标识
		this.hideLoad()
	},
	async onShow() {
		store.commit('indexPage/changeStoreType',false) // 更换域名
		
		if (this.indexNeedReload && !this.isMaterial) {
			this.showLoad()
			
			if (this.reLocation) this.pageInit()	// 切换坐标地址
			
			if(this.isLogin) await store.dispatch('cartPage/getCarList')
			store.commit('indexPage/indexNeedReload',false)	// 去掉首页的重载标识
			this.hideLoad()
		}
		// if(this.carCount) setTabBarBadge('set',this.carCount)
	},
	//  分享
	onShareAppMessage (res) {
		return {
			withShareTicket: true,
			path: '/pages/index/index?storeID=' + this.storeID,
		}
	},
	// 下拉刷新
	async onPullDownRefresh() {
		try {
			this.showLoad();
			if (!this.isMaterial) {
				store.commit('indexPage/saveReLocation',null)	// 清除重定位信息
				this.pageInit()
			} else {
				this.refreshStockAndGetMaterStore()
			}
		// 	this.showBone=this.showBone?false:this.showBone
		} catch (e) {
			console.error(e);
			this.showBone= false
			errToast(e);
		} finally {
			uni.stopPullDownRefresh();
			this.showBone= false
			this.hideLoad();
		}
	},
	methods: {
		...mapActions({
			getAddressList: "addressVue/getList",
			getCarList: "cartPage/getCarList",
			getPosition: "indexPage/getPosition",
			storeListByLocation: "indexPage/storeListByLocation",
  			changeCar: "cartPage/changeCar"
		}),
		jumpToBanner(row){
			// console.log('点击轮播图返回的数据2',row)
		},
		// 切换门店
		switchShop() {
			if (this.queryStoreID) return false;
			jumpPage('navigateTo','/pagesAddress/pick-store/index')
		},

		/**
		 * init
		 */
		async pageInit() {
			try {
				this.hideLoad()
				this.showBone = true
				if (!this.isMaterial) {
					if (!this.queryStoreID) {
						// 获取定位
						if(!(this.reLocation && this.reLocation.lat && this.reLocation.lng)) await this.getPosition()

						this.address = this.reLocation && this.reLocation.address ? this.reLocation.address : this.pois[0] ? this.pois[0].name : "加载中...";

						// 按当前位置匹配门店
						// await this.storeListByLocation({
						// 	isMaterial: false,
						// 	data: {
						// 		lat: this.reLocation && this.reLocation.lat ? this.reLocation.lat : this.myLocation.lat,
						// 		lng: this.reLocation && this.reLocation.lng? this.reLocation.lng : this.myLocation.lng,
						// 		brandID: this.brandID
						// 	}
						// })

					}
					
					// 加载轮播图
					const banner = await apiStore.getConfigInfo('banner')
					this.bannerArr = banner;
					this.jxBanner = banner;
					store.commit('indexPage/saveBannerList',banner)

					
				} else {
					// 1.登录
					await this.globalLogin()

					// 2.热销商品
					await store.dispatch('indexPage/getTopGoods', this.storeID)

					// 3.物料信息
					if(!this.isPurchase) this.materialDesc = await apiStore.getConfigInfo('materialDesc')

					// 4.计算袋子是否是原价
					// if(!this.isPurchase) this.computedBagsPrice(this.topGoods)

				}
				
				await this.loadTop();	// 加载商品推荐

				uni.showTabBar()
			} catch (e) {
				this.showBone = false
				throw e;
			} finally {
				this.showBone = false
				this.hideLoad()
			}
		},

		/**
		 * 场景值
		 */
		async sceneValue(query) {
			// const {  storeID, fromStoreID, toStoreID, brandID,storeType,scene } = query;
			if (query.scene) {
				const promoteStr = decodeURIComponent(query.scene);
				let newPromoteStr = promoteStr.split('-')
				const key = newPromoteStr[0].split("=")[0];
				const val = newPromoteStr[0].split("=")[1];

				// console.log(newPromoteStr,'promoteStr',promoteStr,'key',key,'val',val)
				
				if (key === "brandID" && val) {
					await store.dispatch('indexPage/getBrandInfo',{brandID:val})	 // 公众号进入
				}else if (key === "promote" && val) {
					store.commit('indexPage/savePromote',val)	// 推广码
				} else if (key === "storeID" && val) {
					store.commit('indexPage/saveQueryStoreID',val)	 // 扫码进入
					if(newPromoteStr[1]){
						let storeType = newPromoteStr[1].split('=')
						console.log('storeType[1]',storeType[1])
						store.commit('indexPage/changeStoreType',storeType[1] === 'gy')
					}
				}
			} else {
				if(query.brandID) await store.dispatch('indexPage/getBrandInfo',{brandID:query.brandID})	 // 公众号进入
				else if(query.storeID && !query.storeType) {
					await store.commit('indexPage/saveQueryStoreID',query.storeID)
				}
				else store.commit('indexPage/saveMaterialInfo',query)
			}
		},

		// 加载推荐分类和商品
		async loadTop() {
			try {
				// 获取当前门店的信息storeMap
				if (!this.storeMap) {
					// await store.dispatch('indexPage/getStoreInfo', { storeID: this.storeID[0] })	// 获取当前门店的信息
				} else if (!(this.storeMap && this.storeID && this.storeMap[this.storeID[0]])) await store.dispatch('indexPage/getStoreInfo', { storeID: this.storeID[0] })	// 获取当前门店的信息
				
				if (this.isMaterial) {
					// 加载来自哪个门店的的数据
					await store.dispatch('indexPage/getStoreInfo',{storeID:this.materialInfo.fromStoreID,type:'fromStoreID'})

					// this.showBone = false
					uni.showTabBar()		// 显示tabbar

					this.refreshStockAndGetMaterStore()	// 刷新物料库存
				} else {
					// 获取推荐分类
					this.topCats = [ 
						{
							img:'https://image.jxc4.com/jxapp/jxc4.png',
							name:'京西菜市',
							id:[1]
						},
						{
							img:'https://image.jxc4.com/jxapp/jxgy.png',
							name:'京西果园',
							dnsType:'wxGy'
						},
						{
							img:'https://image.jxc4.com/jxapp/jxToHome.png',
							name:'京西到家',
							id:[7]
						},
						{
							img:'https://image.jxc4.com/jxapp/starfish.png',
							name:'海星超市',
							id:[29]
						},
						{
							img:'https://image.jxc4.com/jxapp/dogCat.png',
							name:'狗不理猫',
							dnsType:'wxJxpet'
						},
						{
							img:'https://image.jxc4.com/jxapp/jadeButterfly.png',
							name:'玉蝴蝶',
							id:[35]
						}
					]

					this.showBone = false	// 关闭骨架屏
					uni.showTabBar()		// 显示tabbar

					if(!this.queryStoreID){
						// 获取推荐商家

						// 菜市
						let arrC4 = await apiStore.getNearlyStore({
							lat: this.reLocation && this.reLocation.lat? this.reLocation.lat : this.myLocation.lat,
							lng: this.reLocation && this.reLocation.lng? this.reLocation.lng : this.myLocation.lng,
							needWalkDistance:false
						})

						// 果园
						let arrGy = await apiStore.getNearlyStore({
							lat: this.reLocation && this.reLocation.lat? this.reLocation.lat : this.myLocation.lat,
							lng: this.reLocation && this.reLocation.lng? this.reLocation.lng : this.myLocation.lng,
							needWalkDistance:false
						},'wxGy')

						// 宠物
						let arrPet = await apiStore.getNearlyStore({
							lat: this.reLocation && this.reLocation.lat? this.reLocation.lat : this.myLocation.lat,
							lng: this.reLocation && this.reLocation.lng? this.reLocation.lng : this.myLocation.lng,
							needWalkDistance:false
						},'wxJxpet')

						arrGy = arrGy.map(item => ({...item,dnsType:'wxGy'}))
						arrPet = arrPet.map(item => ({...item,dnsType:'wwwJxpet'}))
						this.nearlyStores = arrC4.concat(arrGy).concat(arrPet)
						store.commit('indexPage/saveStoreList',this.nearlyStores)
					}else{
						await store.dispatch('indexPage/getTopGoods', this.storeID)	// 热销商品(扫码进店)
					}

					// 获取品牌信息
					await store.dispatch('indexPage/getBrandInfo', { brandID: this.brandID })

					await apiStore.getWayBillFeeMinus(this.storeID[0]) // 获取当前门店的运营策略
				}
			} catch (e) {
				console.error(e);
				this.showBone = false
				throw e;
			}finally{
				this.showBone = false
			}
		},
		
		async refreshStockAndGetMaterStore() {
			// 刷新物料库存
			await apiStore.refreshStock()

			// 获取购买限制
			let res= await apiStore.getMatterStoreOrderStatus(this.materialInfo.fromStoreID)
			store.commit('indexPage/savePreSaleCount',res.count)
			store.commit('indexPage/changeCanBuy',res.flag)
		},

		// 重新选择地址
		toDressPick() {
			jumpPage('navigateTo','/pagesAddress/position-address/index?choisePosition=1')
		},
		// 跳转到分类页面
		toGoods(banner, bannerID) {
			switch (banner.type) {
				case 3:
					uni.navigateToMiniProgram({
						appId: banner.toPath
					});
					break
				case 2:
					jumpPage('navigateTo','/pagesBanner/banner-template1/index?id=' + bannerID)
					break
				case 1:
					App.catID = banner.toPath;
					jumpPage('navigateTo','/pagesGoods/good/index')
					break
			}
		},
		toGoodsByID(cats) {
			if(cats.dnsType){
				// 跳转到果园，查询果园门店
				// store.commit('indexPage/changeStoreType',true)
				// dnsType  wxGy果园 	wwwJxpet宠物
				store.commit('indexPage/changeDNS',cats.dnsType)
				jumpPage('navigateTo',`/pagesStore/store/index?type=${cats.dnsType}`)
			}
			else{
				store.commit('indexPage/changeDNS','wxC4')
				// 跳转到门店列表
				jumpPage('navigateTo','/pagesStore/store/index?brandID=' +JSON.stringify( cats.id))
			}
		},
		// 商品 +
		async handleSkuNamePlus(index) {
			const skuName = this.topGoods[index];
			await this.changeCar({
				skuName,
				count:skuName.count + 1
			})
		},
		// 商品 -
		async handleSkuNameMinus(index) {
			let skuName = this.topGoods[index];
			await this.changeCar({
				skuName: skuName,
				count:skuName.count - 1,
			})
		},
		async handleSkuNameChange(count,index) {
			let skuName = this.topGoods[index];
			await this.changeCar({
				skuName: skuName,
				count,
			})
		},
		// 点击检索
		handleClickSearch() {
			jumpPage('navigateTo','/pagesGoods/good-search/index')
		}
	},
}
</script>

<style lang="scss" scoped>
@import './shop-index.scss';
</style>
