<template>
	<view class="menu-box">
		<view class="menu-banner" :style="{'height':buied?'360rpx':'450rpx'}">
			<!-- <image :src="img"/> -->
			<ImageLoader :defaultSrc="'../../static/imgs/shouyezhanweitu.png'" :realSrc="img" width="100%" height="400rpx"/>
			<!-- <video autoplay muted loop :controls="false" :enable-progress-gesture="false" objectFit='cover' src="http://songclound.oss-cn-hongkong.aliyuncs.com/2022/06/27/71d36be0ed966.mp4" /> -->
			<!-- <HomeBanner /> -->
			<view class="shop-info" :style="'top:100rpx'">
				<view class="shop-box">	
					<text @click="showArea" class="shop-name">{{ shopInfo.name }}</text>
					<image class="arrow-right-select" :src="'../../static/imgs/jiantoubai.png'" />
				</view>
				<view v-if="shopInfo.distance && shopInfo.distance!=-1" class="distance">距您{{ shopInfo.distance }}</view>
			</view>
			<view class="login-area">
				<view class="avatar">
					<image :src="'../../static/touxiang.png'"></image>
				</view>
				<view class="user-info" @click="goToMyPage(userms)">
					<view class="user-infocontent">
						<view class="user-name" v-if="userms">HI！{{ userInfo.customerName || '我是谁' }}</view>
						<view class="user-name" v-else>未登录</view>
						<view class="dialog">
							<view class="content" v-if="userms">希望你今天，明天，天天都开心～</view>
							<view class="content" v-if="!userms">请您尽快登录～</view>
						</view>
					</view>
					<view>
						<image class="arrow-right-select"  v-if="userms" :src="'../../static/imgs/jiantouhei.png'" />
						<button class="login-btn" v-if="!userms" open-type="getPhoneNumber"
							@getphonenumber="getPhoneNumber">立即登录
						</button>
					</view>
				</view>
			</view>
		</view>
		<view class="order-banner" v-if="buied" @click="openQrcode">
			<view class="info">
				<view class="first">取单码：<text class="first-code">{{ orderInfo.orderNum }}</text></view>
				<view class="second1" v-if="orderInfo.state =='4'">订单已制作完成，请尽快取餐~</view>
				<view class="second" v-else>请您耐心等候，剩余等候时间<text class="time">{{ orderInfo.waitTime }}</text>分钟</view>
			</view>
			<view class="line"></view>
			<view class="barCode-box">
				<view class="barCode">
					<image :src="'/static/imgs/icon-barcode.png'"></image>
				</view>
				<view class="barCode-dis">点击二维码取单</view>
			</view>
		</view>
		<MenuAssembly ref="MenuAssembly" @getallNum="getallNum" :buied="buied" :shopState="shopState"/>
		<!-- <u-picker @cancel="show = false" :show="show" :immediateChange="true" ref="uPicker" :columns="columns"
			@confirm="confirm" keyName="name" @change="changeHandler"></u-picker> -->
		<AreaPicker ref="AreaPicker" />
		<OrderQrCode ref="OrderQrCode" />
		<canvas class="canvas-code" canvas-id="myQrcode2"
			style="background:#fff;width: 200px;height: 200px; display:block; left:-800rpx;position:absolute;" />
		<show-toast ref="toast"/>
		<taBar select="0"></taBar>
		<ShopCar ref="shopbar" :shopState="shopState" />
	</view>
</template>
<script>
import MenuAssembly from '@/components/menuAssembly'
import ImageLoader from '@/components/ImageLoader/index.vue'
import AreaPicker from '@/components/AreaPicker/index.vue'
import HomeBanner from '@/components/canvas/HomeBanner.vue'
import User from '@/request/user'
import ShopCar from '../../components/shopCar/shopCar.vue'
import Utils from '@/utils/utils'
import Menu from '@/request/menu'
import { $EventBus } from '@/utils/EventBus';
import Order from '@/request/order'

import OrderQrCode from '@/components/OrderQrCode'
import QRCode from '@/utils/qrCode'
export default {
	components: { ShopCar, MenuAssembly, OrderQrCode, AreaPicker, ImageLoader, HomeBanner },
	data() {
		return {
			shopInfo: { name: '请选择' },// 店铺信息
			buied: false,//控制首页取单码区域显隐
			orderInfo: {},//即将取餐的订单信息
			classifyData: [],
			customerName: '',
			loginInfo:"",
			img:''
		};
	},
	computed: {
		shopState() {
			console.log(this.shopInfo)
			const { shopInfo } = this
			const {startTime,endTime,state} = shopInfo
			if(!startTime||!endTime||!state) return true
			function getNowFormatDate() {
				let date = new Date(),
				  seperator1 = '/', //格式分隔符
				  year = date.getFullYear(), //获取完整的年份(4位)
				  month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
				  strDate = date.getDate() // 获取当前日(1-31)
				if (month >= 1 && month <= 9) month = '0' + month // 如果月份是个位数，在前面补0
				if (strDate >= 0 && strDate <= 9) strDate = '0' + strDate // 如果日是个位数，在前面补0

				let currentdate = year + seperator1 + month + seperator1 + strDate 
				return currentdate
			}
			const startTimeNew = Date.parse(getNowFormatDate()+ ' ' +startTime+':00')
			const endTimeNew = Date.parse(getNowFormatDate()+ ' ' +endTime+':00')
			if(startTimeNew<new Date().valueOf()&&new Date().valueOf()<endTimeNew&&state===1) {
				uni.setStorageSync("shopState",true)
				return true
			}else{
				uni.setStorageSync("shopState",false)
				return false
			}
		},
		userms() {
			return this.$store.getters.Authorization;
		},
		userInfo() {
			return this.$store.state.user.userInfo;
		},
	},
	created() {
		let platform = uni.getSystemInfoSync().platform;
		uni.downloadFile({
			url: 'http://songclound.oss-cn-hongkong.aliyuncs.com/2022/06/27/71d36be0ed966.mp4', //仅为示例，并非真实的资源
			success: (res) => {
				if (res.statusCode === 200) {
					console.log(res);
					this.img = res.tempFilePath
				}
			}
		});
		// if(platform == 'android'){
		// 	this.img = '../../static/imgs/shouyezhanweitu.png'
		// }else{
		// 	this.img = 'https://s3.bmp.ovh/imgs/2022/07/02/2cfab823b35322e3.gif'
		// }
	},
	onLoad: async function () {
		uni.getSetting({
			success: (res) => {
				// 已经授权位置不获取默认店铺
				if(res.authSetting['scope.userLocation']){
					User.getLocation((state, params) => {
						if(state != 1) {
							return;
						}
						this.getShopMenus(params);
					});
				} else {
					this.getShopMenus();
					this.authLocation();
				}
			}
		})
		if(!this.userms){
			User.wxLoginAndGetOpenid(true).then(loginInfo=>{
				this.loginInfo = loginInfo
			})
		}
	},
	onHide() {
		this.$refs.shopbar.showShopCar = false;
	},
	async onShow() {
		this.getHomeOrder()
	},
	methods: {
		getShopMenus(params) {
			$EventBus.$off('getMenuList');
			$EventBus.$on('getMenuList', (data) => {
				console.log("shop:"+JSON.stringify(data));
				if(this.shopInfo && this.shopInfo.id != data.id) {
					// 切换店铺清空购物车
					uni.removeStorageSync('shopCarInfo');
					$EventBus.$emit('updateCar');
				}
				this.shopInfo = data;
				uni.setStorageSync("shopInfo",JSON.stringify(this.shopInfo))
				this.getMenuList(data.id);
				this.getHomeOrder(data.id)
			});
			User.getShopInfo(params);	
		},
		async getHomeOrder(id = this.shopInfo.id){
			if (!this.userms) return;
			const res = await Order.getHomeOrder({shopId:id})
			const data = res?.data
			if (data?.data) {
				// this.$set(data.data, 'state', '2');
				// console.log("getHomeOrder:"+JSON.stringify(data.data));
				this.buied = true;
				this.orderInfo = data.data
			} else {
				this.buied = false
			}
		},
		openQrcode() {
			// 不生成二维码
			if(['2', '3'].indexOf(this.orderInfo.state) != -1){
				this.$refs.OrderQrCode.open(this.orderInfo, "");
				return;
			}

			new QRCode('myQrcode2', {
				text: this.orderInfo.pickCode,
				width: 141,	//canvas 画布的宽
				height: 141,	//canvas 画布的高
				padding: 0, // 生成二维码四周自动留边宽度，不传入默认为0
				correctLevel: QRCode.CorrectLevel.L, // 二维码可辨识度
				callback: (res) => {
					this.$refs.OrderQrCode.open(this.orderInfo, res.path)
				}
			})
		},
		showArea() {
			console.log(this.$refs)
			this.$refs.AreaPicker.showArea()
		},
		// 手机号授权登录
		getPhoneNumber(e) {
			if (e.detail.errMsg == 'getPhoneNumber:ok') {
				e.loginInfo = this.loginInfo
				User.getPhoneNumber(e,this.getHomeOrder);
			} else if (e.detail.errMsg == "getPhoneNumber:fail user deny") {
				this.showToast({ title: '已拒绝手机号授权', icon: 'error' })
			}
		},
		// 获取定位授权
		authLocation(callback) {
			uni.getSetting({
				success: (res) => {
					uni.authorize({
						scope: 'scope.userLocation',
						success: () => { //1.1 允许授权
							// console.log("允许授权位置");
							User.getLocation((state, params) => {
								if(state != 1){
									return;
								}
								callback ? callback(params) : this.getShopMenus(params);
							});
						},
						fail: (err) => { //1.2 拒绝授权
							wx.exitMiniProgram({ success: (res) => { } })
							// console.log("获取位置失败")
							this.showToast({ "title" : "获取位置失败,请打开位置授权", icon : 'error'})
						}
					})
					// if (res.authSetting['scope.userLocation']) {
					// 	console.log("以前允许授权位置");
					// 	User.getLocation((state, params) => {
					// 		if(state != 1){
					// 			return;
					// 		}
					// 		callback && callback(params);
					// 	});
					// } else {
						
					// }
				}
			})
		},
		async getMenuList(id) {
			let { data } = await Menu.getMenuList(id);
			// console.log("menus:"+JSON.stringify(data));
			if (data.code == 200) {
				data.data = data.data;
				this.$store.commit('setMenuAllInfo', data.data);
				this.$store.commit('setMenuCategorys', data.data.categorys);
				uni.setStorageSync('countOfOrder', parseInt(data.data.countOfOrder));
				// this.$refs.MenuAssembly.createList(data.data.categorys)
			}
		},
		// 加入购物车数据
		async getallNum(item, category) {
			let itemCopy = JSON.parse(JSON.stringify(item));
			const sku = itemCopy.skus.find(v => v.isDefault == 1);
			const {data} = await Order.checkSku({skuId:sku.skuId})
			const {state,goods} = data.data
			const newsku = goods.skus.find(v => v.isDefault == 1 && v.state != 2) || goods.skus.find(v => v.isDefault == 0 && v.state != 2);
			if(state == 2){
				if(newsku){
					if(newsku.isDefault != 1){
						this.showToast({ title: '默认规格已售罄,已添加其他规格', icon: 'none' });
						itemCopy.skus = [newsku];
						itemCopy.sku = newsku
						itemCopy.skuId = newsku?.skuId
						itemCopy.num = 1;
						itemCopy.flag = true;
						itemCopy.categoryId = category.id;
						itemCopy.goodsName = category.name;
						Utils.getallNum(itemCopy);
					}
				}else{
					this.showToast({ title: '本商品已经售罄', icon: 'none' });
					return;
				}
			}else{
				itemCopy.skus = [newsku];
				itemCopy.sku = newsku
				itemCopy.skuId = newsku?.skuId
				itemCopy.num = 1;
				itemCopy.flag = true;
				itemCopy.categoryId = category.id;
				itemCopy.goodsName = category.name;
				Utils.getallNum(itemCopy);
			}
			return
		},
		goToMyPage(logined) {
			logined && uni.switchTab({ url: '/pages/mine/mine' })
		}
	},

}
</script>

<style lang="scss" scoped>
.menu-box {
	min-height: 100vh;

	.shop-info {
		z-index: 100;
		position: absolute;
		left: 32rpx;
		color: #FFFFFF;

		.shop-box {
			font-size: 32rpx;
			font-weight: 500;
			color: #FFFFFF;
			font-family: PingFangSC-Medium, PingFang SC;
			display: flex;
			align-items: center;
			height: 62rpx;
			line-height: 62rpx;

			.shop-name {
				margin-right: 12rpx;
				flex: 1;
				font-size: 32rpx;
			}

			.arrow-right-select {
				width: 15.27rpx;
				height: 21.68rpx;
				// border: 3rpx solid #FFFFFF
			}
		}

		.distance {
			height: 46rpx;
			font-size: 24rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #FFFFFF;
			line-height: 42rpx;
		}
	}
}

.menu-banner {
	height: 40rpx;
	position: relative;

	video {
		width: 100%;
		height: 400rpx;
		
	}
	image {
		width: 100%;
		height: 400rpx;
	}

	.login-area {
		display: flex;
		width: 686rpx;
		height: 104rpx;
		padding: 16rpx 32rpx 16rpx 32rpx;
		background: #ffffff;
		position: absolute;
		z-index: 1;
		bottom: -2rpx;
		left: 33rpx;
		box-sizing: border-box;
		box-shadow: 0px 2px 8px 0px rgba(102, 102, 102, 0.1);
		backdrop-filter: blur(0px);
		z-index: 9;

		.avatar {
			display: flex;
			justify-items: center;
			align-items: center;
			width: 72rpx;
			height: 72rpx;
			margin-right: 16.93rpx;
			border-radius: 72rpx;
			image {
				width: 100%;
				height: 100%;
				border-radius: 72rpx;
			};
		}

		.user-info {
			display: flex;
			align-items: center;
			width: 530.55rpx;
			justify-content:space-between;
			flex-wrap:nowrap;
			.user-name {
				margin-top: 2.68rpx;
				font-size: 24rpx;
				font-weight: normal;
				font-family: Arial-BoldMT, Arial;
				color: #333333;
			}

			.dialog {
				font-size: 20rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #666666;
				margin-top: 4.64rpx;

				.content {
					flex: 1;
				}
			}
			.arrow-right-select{
				width: 15.27rpx;
				height: 21.68rpx;
			}
		}

		.login-btn {
			//  width: 114rpx;
			margin-right: -5rpx;
			width: 167rpx;
			height: 64rpx;
			background: #0050F6;
			border-radius: 2rpx;
			text-align: center;
			font-size: 24rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #FFFFFF;
			line-height: 64rpx;
		}
	}
}

.order-banner {
	width: 718rpx;
	height: 179rpx;
	background: #FFFFFF;
	box-shadow: -2px -2px 8px 0px rgba(102, 102, 102, 0.1), 2px 2px 8px 0px rgba(102, 102, 102, 0.1);
	box-sizing: border-box;
	position: relative;
	left: 16rpx;
	top: 0rpx;
	z-index: 10;
	display: flex;
	justify-content: flex-start;

	.info {
		padding-left: 34.48rpx;

		.first {
			height: 44rpx;
			font-size: 28rpx;
			font-family: PingFangSC-Semibold, PingFang SC;
			font-weight: 600;
			color: #666666;
			line-height: 44rpx;
			margin-top: 44rpx;
			.first-code{
				font-family: Arial, Helvetica SC;
				font-size: 28rpx;
				color: #333333;
			}
		}

		.second1,
		.second {
			margin-top: 12rpx;
			width: 400rpx;
			font-size: 24rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #999999;
			letter-spacing: 0rpx;
			text-shadow: -2px -4px 8px rgba(102, 102, 102, 0.1);
			white-space: nowrap;

			.time {
				font-size: 32rpx;
				font-family: Futura Medium, Arial, sans-serif;
				font-weight: normal;
				color: #0050F6;
				margin: 0 16rpx;
			}
		}
		.second1 {
			margin-top: 20rpx;
		}
	}

	.line {
		width: 4rpx;
		height: 104rpx;
		border-right: 1rpx solid #E8E8E8;
		position: absolute;
		left: 510rpx;
		box-shadow: -2px -4px 8px 0px rgba(102, 102, 102, 0.1);
		top: 36rpx;
	}

	.barCode-box {
		margin-top: 30rpx;
		margin-left: 115rpx;
		width: 150rpx;
		height: 122rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		text-align: center;
		flex-direction: column;

		.barCode {
			width: 86rpx;
			height: 86rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.barCode-dis {
			text-align: center;
			margin-top: 12rpx;
			font-size: 16rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #999999;
			line-height: 22rpx;
		}
	}
}
</style>
