<template>
	<view class="content">
		<u-swiper height="250" @click="clickBanner" :list="imageTopList"></u-swiper>
		<!-- 导航按钮 -->
		<view class="nav">
			<u-grid :col="4" :border="false" @click="toPage">
				<u-grid-item :index="3">
					<u-image width="90rpx" height="90rpx" src="/static/hexiao.png"></u-image>
					<view class="grid-text">投递/兑换</view>
				</u-grid-item>
				<u-grid-item :index="0">
					<u-image width="90rpx" height="90rpx" src="/static/zhinan.png"></u-image>
					<view class="grid-text">回收分类</view>
				</u-grid-item>
				<u-grid-item :index="1">
					<u-image width="90rpx" height="90rpx" src="/static/liucheng.png"></u-image>
					<view class="grid-text">使用指南</view>
				</u-grid-item>
				<u-grid-item :index="2">
					<u-image width="90rpx" height="90rpx" src="/static/shouyi.png"></u-image>
					<view class="grid-text">投递二维码</view>
				</u-grid-item>
			</u-grid>
		</view>
		<!-- 网点 -->
		<view class="storeList">
			 <u-section title="附近的回收机" :right="false" line-color="#01c9b2" class="store-section"></u-section>
			 <view class="stores-box">
			 	<view class="stores-item" v-for="item in stationDataList" :key="item.id" @click="viewStore(item)">
			 		<view class="item-con">
			 			<image src="/static/md-icon.png" class="item-icon"></image>
			 			<view class="s-name item-main">{{ item.name }}</view>
			 		</view>
			 		<view class="item-con">
			 			<image src="/static/dz-icon.png" class="item-icon"></image>
			 			<view class="s-address item-main">
			 				<view>{{ item.provinceName||'' }}{{ item.cityName||'' }}{{ item.districtName||'' }}{{ item.address||'' }}</view>
			 				<view>
			 					<u-icon name="map-fill" color="#01c9b2" size="30"></u-icon>
			 					{{ getDistanct(item) }}KM
			 					<u-icon name="arrow-right" color="#999" size="20"></u-icon>
			 				</view>
			 			</view>
			 		</view>
			 		<view class="item-con">
			 			<image src="/static/time-icon.png" class="item-icon"></image>
			 			<view class="s-time item-main">
			 				<view>
			 					<text>营业时间：</text>
			 					<text v-for="(tItem, tInd) in item.deliveryTimeRuleItemList" :key="tInd">
			 						{{ tItem.openTime }} - {{ tItem.closeTime }}{{ tInd == item.deliveryTimeRuleItemList.length - 1 ? '' : '，' }}
			 					</text>
			 				</view>
			 			</view>
			 		</view>
			 	</view>
				<view v-if="stationDataList.length==0">
					<u-empty icon-size="60" text="暂无数据" mode="list"></u-empty>
				</view>
			 </view>
		</view>
		
		<!-- 抽奖活动弹框 -->
		<u-mask :show="showLottery" @click="showLottery = false">
			<view class="lottery-content">
				<view>
					<view class="bg">
						<u-image src="/static/toLottery.png" width="495rpx" height="466rpx" @click="toLuckDraw"></u-image>
					</view>
					<view class="close-btn" @click="showLottery = false">
						<u-image src="/static/closeLottery.png" width="54rpx" height="163rpx"></u-image>
					</view>
				</view>
			</view>
		</u-mask>
	</view>
</template>

<script>
	import {
		getCartList,
		addGoodsToCart,
		deleteGoodsFormCart,
		updateGoodsBuyQty
	} from '@/api/shoppingCart.js'
	import {findEnable,findCustomerTimes} from '@/api/luckyDraw.js'
	import {bannerList} from '@/api/banner.js'
	import {getLookUpDatas,openDevice} from '@/api/data.js'
	import {stationList} from '@/api/station.js'
	import {checkLogin,getUserInfo} from '@/api/login.js'
	import {parseQueryString} from '@/libs/tools.js'
	import {sellerFindByPartnerNo} from '@/api/user.js'
	import moment from 'moment'
	export default {
		data() {
			return {
				imageTopList: [],
				stationDataList: [] ,//  附近网点列表
				hasLogin: false,
				userData: null,
				showLottery: false, // 是否显示抽奖弹框
			}
		},
		onLoad() {
			// 检查更新
			this.checkUpdate()
			// 判断是否有抽奖活动
			this.getLuckDraw()
			// 查询购物车列表
			this.getCartList()
			// 刷新购物车列表
			uni.$on("getCartList",item =>{
				this.getCartList()
			})
			// 更新购物车数量
			uni.$on('getCarCount',item => {
				this.getCarCount()
			})
			// 查询用户信息
			uni.$on("getUserInfo",item=>{
				this.getUserInfo(item)
			})
		},
		onUnload() {
			console.log('onUnload')
			uni.$off('getCarCount')
			uni.$off('getCartList')
			uni.$off('getUserInfo')
			
			// 开启分享
			uni.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline']
			})
		},
		onShareAppMessage(res) {
			console.log(res)
		},
		onShareTimeline(res) {
			console.log(res)
		},
		onShow() {
			// 获取订单状态数据字典
			// this.getCodeList('RUBBISH_TYPE','vuex_rubbishType')
			// 获取顶部轮播图
			this.getbannerList()
			//  获取经纬度
			this.getLocation()
			// 是否登录
			checkLogin().then(res => {
				console.log(res,'checkLogin')
				this.hasLogin = res.status == 200
				if(!this.hasLogin&&!this.$store.state.vuex_noLogin){
					uni.navigateTo({
						url:"/pages/login/login"
					})
				}
			})
		},
		methods: {
			checkUpdate(){
				const updateManager = uni.getUpdateManager();
				updateManager.onCheckForUpdate(function (res) {
				  // 请求完新版本信息的回调
				  console.log(res.hasUpdate);
				});
				updateManager.onUpdateReady(function (res) {
				  uni.showModal({
				    title: '更新提示',
				    content: '新版本已经准备好，是否重启应用？',
				    success(res) {
				      if (res.confirm) {
				        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
				        updateManager.applyUpdate();
				      }
				    }
				  });
				});
				updateManager.onUpdateFailed(function (res) {
				  // 新的版本下载失败
				});
			},
			// 计算距离
			getDistanct(item){
				return item.distanct&&item.distanct.distance ? (item.distanct.distance / 1000).toFixed(1) : 0
			},
			// 抽奖弹框
			getLuckDraw(){
				findEnable().then(res => {
					if(res.status == 200 && res.data){
						this.$u.vuex('vuex_LuckDraw',res.data)
						// 判断活动是否过期
						
						findCustomerTimes({id:res.data.luckyDrawNo}).then(res => {
							let reTimes = 0
							if(res.status == 200){
								reTimes = res.data.timesSurplus || 0
							}
							this.$u.vuex('vuex_LuckDrawTimes',reTimes)
							this.showLottery = reTimes > 0
						})
					}else{
						this.$u.vuex('vuex_LuckDraw',null)
					}
				})
			},
			// 获取用户信息
			getUserInfo(){
				getUserInfo().then(res => {
					console.log('getUserInfo',res.data)
					if(res.status == 200){
						this.$u.vuex("vuex_userData",res.data)
					}
				})
			},
			// 获取数据字典
			getCodeList(code,key) {
				getLookUpDatas({
					type: code
				}).then(res => {
					if (res.status == 200) {
						this.$u.vuex(key, res.data)
					}
				})
			},
			//  获取经纬度
			getLocation() {
				const _this = this;
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						_this.getStationList(res.longitude, res.latitude)
					},
					fail: function(error) {
						console.log(error)
						uni.showToast({ icon: 'none', title: '定位失败' })
					}
				});
			},
			//  获取网点列表
			getStationList(lng, lat) {
				stationList({ lng: lng, lat: lat }).then(res => {
					if (res.status == 200) {
						this.stationDataList = res.data
					} else {
						this.stationDataList = []
					}
				});
			},
			// 获取banner
			getbannerList(){
				bannerList({type:'banner',location:'HOME_TOP'}).then(res=>{
					if(res.status==200){
						this.imageTopList=res.data
					}
				})
			},
			// 点击banner
			clickBanner(index){
				let row = this.imageTopList[index]
				console.log(index,row)
				if(row.jumpType !== 'NONE'){
					uni.navigateTo({
						url: row.jumpUrl
					})
				}
			},
			// 查询购物车
			getCartList(){
				getCartList({}).then(res => {
					if(res.status == 200){
						this.$u.vuex('vuex_cartList', res.data)
						this.getCarCount()
					}
					uni.hideLoading()
				})
			},
			// 计算购物车数量
			getCarCount(){
				let arr = this.$store.state.vuex_cartList || []
				let count = 0
				arr.map(item=>{
					count = count + item.shoppingCartGoodsList.length
				})
				this.$u.vuex('vuex_cartNums', count)
			},
			// 更多商品
			toGoods(clsId){
				uni.navigateTo({
					url:"/pages/goods/goods?id="+clsId
				})
			},
			// 去登录
			toLoginPage(){
				uni.navigateTo({
					url: '/pages/login/login'
				})
			},
			// 快速导航
			toPage(e){
				let path=[
					'/pages/userCenter/fenlei',
					'/pages/userCenter/zhinan',
					'/pages/userCenter/myCode/myCode',
					''
				]
				 
				if(e>1){
					//判断是否登录
					if(this.hasLogin){
						if(path[e]!=''){
							uni.navigateTo({
								url: path[e]
							})
						}else{
							// 核销
							this.smHx()
						}
					}else{
						this.toLoginPage()
					}
				}else{
					uni.navigateTo({
						url: path[e]
					})
				}
			},
			// 扫码核销
			smHx(){
				const _this = this
				uni.scanCode({
					success(e) {
						console.log(e)
						// 普通二维码，用户扫箱体的二维码开箱
						if(e.scanType == 'QR_CODE'){
							let params = parseQueryString(e.result)
							console.log(params)
							if(params.codeType == 'hexiao'){  //  扫商户码
								_this.getStoreData(params.officialPartnerNo)
							}else{  //  扫箱体码
								_this.openDevice(e.result)
							}
						}
						// 小程序码，用户核销
						// if(e.scanType == 'WX_CODE'){
						// 	let scene = e.path.split('?')[1]
						// 	uni.navigateTo({
						// 		url: '/pages/checkOut/checkOut?scene='+scene.split("=")[1]
						// 	})
						// }
					},
					fail(err) {
						console.log(err)
					}
				})
			},
			// 扫商户码，获取商户信息
			getStoreData(params) {
				let userData = this.$store.state.vuex_userData
				if(userData.customerRole == 9){
					uni.showToast({
						icon:"none",
						title:"抱歉，您目前无法使用乐豆"
					})
				}else{
					sellerFindByPartnerNo({officialPartnerNo: params}).then(res => {
						if(res.status == 200){
							let store = res.data
							uni.navigateTo({
								url: '/pages/checkOut/checkOut?store='+encodeURIComponent(JSON.stringify(store))
							})
						} 
					})
				}
			},
			// 开箱
			openDevice(data){
				let params = parseQueryString(data)
				openDevice(params).then(res => {
					console.log(res)
					if(res.status == 200){
						// uni.showToast({
						// 	icon:"none",
						// 	title:"认证成功，请点击设备开启按钮"
						// })
					}
				})
			},
			// 查看网点
			viewStore(item){
				uni.navigateTo({
					url: '/pages/store/store?id=' + item.id + '&stationNo=' + item.stationNo
				})
			},
			// 去抽奖
			toLuckDraw(){
				uni.navigateTo({
					url: '/pagesA/luckDraw/luckDraw'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		// background: url(../../static/topBg.png) no-repeat top center;
		// background-size: 100%;
		width: 100%;
		.nav {
			margin: 20upx 0;
			border-radius: 15upx;
			box-shadow: 0upx 3upx 6upx #eee;
			overflow: hidden;
			.grid-text {
				padding-top: 10upx;
			}
		}
		.lottery-content{
			display: flex;
			align-items: center;
			justify-content: center;
			height: 100%;
			> view{
				width: 495rpx;
				height: 466rpx;
				position: relative;
				.close-btn{
				 position: absolute;
				 right: 32rpx;
				 top: 0 ;
				}
				.bg{
					position: absolute;
					left: 0;
					top: 0 ;
				}
			}
		}
		.storeList {
			padding: 25upx 0 20upx;
			.store-section {
				display: block;
				margin-bottom: 20rpx;
			}
			.stores-box {
				padding-top: 5upx;
				.stores-item {
					background: #ffffff;
					border-radius: 15upx;
					box-shadow: 0upx 3upx 6upx #eee;
					border-bottom: 1px solid #f8f8f8;
					padding: 10upx 20upx;
					margin-bottom: 20rpx;
					&:last-child {
						border: 0;
					}
					.item-con {
						display: flex;
						align-items: center;
						&:last-child {
							.item-main {
								border: none;
							}
						}
						.item-icon {
							width: 30rpx;
							height: 30rpx;
							margin-right: 10rpx;
							flex-shrink: 0;
							padding: 22rpx 0;
						}
						.item-main {
							font-size: 28rpx;
							color: #666;
							padding: 22rpx 0;
							border-bottom: 1rpx solid #f2f2f2;
							flex-grow: 1;
						}
						.s-name{
							font-size: 30rpx;
							color: #333;
						}
						.s-address {
							display: flex;
							align-items: center;
							justify-content: space-between;
							>view{
								&:last-child{
									width: 30%;
									display: flex;
									align-items: center;
									justify-content: flex-end;
								}
							}
						}
					}
				}
			}
		}
	}
</style>
