<template>
	<view class="main-page">
		<!-- <page-standby v-if="showPageStandby" @click="showPageStandby=!showPageStandby"></page-standby> -->
		<view>
			<view-header class="mheader" @closeStandby="handle_closeStandby"></view-header>
			<view class="holdplace" :style="{ height: 100 + 'rpx' }"></view>


			<block v-for="(e,i) in shopList" :key="i">
				<list-item :mkey="i" :mitem="e" @addItem="handle_add" @minusItem="handle_minus"
					@delItem="handle_del"></list-item>
			</block>

			<view class="holdplace" :style="{ height:'340rpx' }"></view>
			<!-- <view class="holdplace" :style="{ height: footerHeight + 'px' }"></view> -->


			<view ref="mfooter" class="mfooter" v-if="true">
				<view-footer :tolPrice="shopListTotalPrice" :tolCount="shopListTotalCount" @clickQR="handle_clickQR"
					@clickVIP="handle_clickVIP" @clickToPay = "clickToPay"></view-footer>
			</view>

			<!-- 条形码输入框 -->
			<input-qr-box v-if="showQRInputBox" :maskHeight="screenHeight" :maxInput="11"
				@showIt="handle_closeQRInputBox" @clickCommit="handle_clickCommit_qr"></input-qr-box>

			<!-- 手机尾号后4位数验证 -->
			<input-box-end-phone v-if="showEndPhoneBox" :maskHeight="screenHeight" :maxInput="4"
				@showIt="handle_closeEndPhoneBox" @clickCommit="handle_clickCommit_qr"></input-box-end-phone>
		</view>

		<keyboard-listener style="height: 1px;" @keyup="onKeyup" @keydown="onKeydown"></keyboard-listener>

	</view>
</template>

<script>
	import util from "@/utils/util.js"
	import dictKeyboard from '@/utils/dictOfKeyboard'
	import {
		API
	} from "@/utils/api";
	import {
		ox
	} from "@/utils/server";
	import pageStandby from '@/components/index/page_standby.vue'; //待机页
	import viewHeader from '@/components/index/view_header.nvue'; //头部
	import viewFooter from '@/components/index/view_footer.nvue'; //底部
	import listItem from '@/components/index/list_item.vue'; //列表项
	import inputQrBox from '@/components/index/keyboard/input_box_QR.vue'; //条形码
	import inputBoxEndPhone from '@/components/index/keyboard/input_box_end_phone.vue'; //手机号尾号
	import keyboardListener from '@/components/index/keyboard/keyboard_listener.vue'; //键盘监听

	// import { uni } from "@dcloudio/uni-h5";

	// import { ref } from 'vue';
	// import { onLoad,onReady } from '@dcloudio/uni-app';

	// #ifdef APP-NVUE
	let dom = weex.requireModule("dom");
	// #endif
	let app = "";
	export default {
		components: {
			'page-standby': pageStandby,
			'view-header': viewHeader,
			'view-footer': viewFooter,
			'list-item': listItem,
			'input-qr-box': inputQrBox,
			'input-box-end-phone': inputBoxEndPhone,
			'keyboard-listener': keyboardListener,
		},
		watch: {
			//已拆分standby到单独页面, 不再需要计算在本nvue页面高度
			// showPageStandby(ov,nv){
			// 	if(nv){
			// 		// #ifdef APP-NVUE
			// 		setTimeout(async()=>{
			// 			dom = weex.requireModule("dom");
			// 			let size = await util.getNvueRefSize(this,dom,"mfooter");
			// 			this.footerHeight = size.height.toFixed(2)
			// 		},200)
			// 		// #endif
			// 	}
			// }
		},
		computed: {
			shopListTotalPrice() {
				let _total = 0
				this.shopList.forEach(item => {
					_total += item.shopCountPrice
				})
				return _total
			},
			shopListTotalCount() {
				let _total = 0
				this.shopList.forEach(item => {
					_total += item.shopCount
				})
				return _total
			},
			//已拆分standby到单独页面, 不再需要计算在本nvue页面高度
			// footerHeight(){
			// 	return this.screenHeight - 100
			// }
		},
		data() {
			return {
				// showPageStandby: false,
				showQRInputBox: false,
				showEndPhoneBox: false,
				screenHeight: '',
				footerHeight: '',
				// globalData: app.globalData,
				globalData: "",
				shopList: [],
				decryptList: [],
				strResult: "",
			}
		},
		async onLoad(res) {
			console.log("onload:", res)

			// this.test()

			// this.showPageStandby = true
		},
		async onReady() {
			this.screenHeight = await util.getPageHeight()
			// this.globalData = app.globalData
			console.log(`the index page onReady----` + this.screenHeight)
			app = getApp();
			setTimeout(async () => {
				await this.updateGoodsList().then(async () => {

					console.log("skulist:", this.shopList)
				})

				console.log("test set SKU 10000012")
				let skulist = await this.searchGoodBySku("10000012")
				//将skulist合并到shopList
				this.shopList = this.shopList.concat(skulist)
				this.setFooterHeight()

			}, 1000)
		},
		methods: {
			clickToPay() {

				// 将shopList进行精简为						{
				// 			"id": 57,
				// 			"name": "光明纯牛奶",
				// 			"price": 1,
				// 			"nums": 1,
				// 			"unit": "袋"
				// 		}组成的数组
				let shopListData = this.shopList.map(item => {
					return {
						id: item.erp_goods.id,
						name: item.erp_goods.erp_goods_name,
						price: item.erp_goods.erp_goods_price,
						nums: item.shopCount,
						unit: item.erp_goods.erp_goods_unit
					}
				})
				// shopCount

				let _query = {
					shopList: shopListData,
					shopListTotalPrice: this.shopListTotalPrice,
					shopListTotalCount: this.shopListTotalCount
				}
				util.routeTo(`/pages/pay/index?query=${JSON.stringify(_query)}`, 'nT');
			},
			clickToUse() {
				util.routeTo(`/pages/login/success`, 'nT');
			},
			handle_closeStandby(val) {
				console.log("handle_closeSetting", val)
				this.showPageStandby = !this.showPageStandby
			},
			handle_closeQRInputBox(val) {
				console.log("handle_closeKeyboardBox", val)
				this.showQRInputBox = !this.showQRInputBox
			},
			handle_closeEndPhoneBox(val) {
				console.log("handle_closeEndPhoneBox", val)
				this.showEndPhoneBox = !this.showEndPhoneBox
			},
			handle_clickQR() {
				util.showNone("输入条形码")
				this.showQRInputBox = !this.showQRInputBox
			},
			handle_clickCommit_qr(res) {
				console.log("handle_clickCommit_qr", res)
				console.log(JSON.stringify(res.goods))
				// util.showNone("条码"+res.inputCode+"-"+res.goods.length)
				util.showNone("添加商品成功,数量:" + res.goods.length + "个");
				this.shopList = this.shopList.concat(res.goods)
				this.showQRInputBox = !this.showQRInputBox
			},
			handle_clickVIP() {
				util.showNone("会员登录")
				this.showEndPhoneBox = !this.showEndPhoneBox
			},
			async setFooterHeight() {
				// #ifdef APP-NVUE
				console.log("APP-NVUE setFooterHeight")
				let size1 = await util.getNvueRefSize(this, dom, "mfooter");
				this.footerHeight = size1.height.toFixed(2)
				// #endif

				// #ifdef H5
				console.log("H5 setFooterHeight")
				let size2 = await util.getH5RefSize(this, "mfooter");
				console.log("H5 setFooterHeight size2:", size2)
				this.footerHeight = size2.height.toFixed(2)
				// #endif
			},
			// 按键松开事件
			async onKeyup(event) {
				console.log("按键松开事件: ", event)

				let res = dictKeyboard.dict[event.keyCode];
				console.log("未转换：", res);
				console.log("this.decryptList0: " + this.decryptList)
				this.decryptList.push(res);

				console.log("this.decryptList0: ", this.decryptList)
				if (event.keyCode != 13) {
					return console.log("this.decryptList1: ", this.decryptList)
				};
				this.decryptList.pop();
				this.strResult = await dictKeyboard.resultScan(this.decryptList);

				console.log("扫码结果strResult--22：", this.strResult)


				this.orderQrcode = this.strResult
				console.log("扫码结果--11：", this.decryptList)

				console.log("扫码结果--33：", this.strResult)

				this.decryptList.splice(0);

				console.log("this.decryptList2: " + this.decryptList)

				//过滤结果中的down_arrow
				if (this.strResult.indexOf("down_arrow") != -1) {
					this.strResult = this.strResult.replace("down_arrow", "")
				}

				console.log("扫码结果--44：", this.strResult)
				let skulist = await this.searchGoodBySku(this.strResult)
				//将skulist合并到shopList
				this.shopList = this.shopList.concat(skulist)
				console.log("skulist:", this.shopList)

				// let info = await this.getOrderInfo(this.strResult)
				// console.log("核销码状态---111", info)

				// this.clearTimer()
				// this.isShowPage = 1
				// this.setTimerCountdown();

				// if(info.status == true){
				// 	this.bindOrderInfo = info.order
				// 	this.bindOrderInfo.order_type = info.order_type || ''

				// 	return this.issueBtn(); //发放手环
				// }else{

				// 	return this.tipsTxt = "核销码不可用\n请重试或联系管理员";
				// }

			},

			// 监听按键按下事件
			onKeydown(event) {
				console.log("监听按键按下事件: ", event)
			},
			handle_add(i) {
				console.log("handle_add", i)
				this.shopList[i].shopCount++
				this.shopList[i].shopCountPrice = (this.shopList[i].erp_goods?.erp_goods_price || 0) * this.shopList[i]
					.shopCount
			},
			handle_minus(i) {
				console.log("handle_minus", i)
				if (this.shopList[i].shopCount > 1) {
					this.shopList[i].shopCount--
					this.shopList[i].shopCountPrice = (this.shopList[i].erp_goods?.erp_goods_price || 0) * this.shopList[i]
						.shopCount
				} else {
					util.showNone("商品数量不能小于1")
				}
			},
			handle_del(i) {
				let that = this
				console.log("handle_del", i)
				that.shopList.splice(i, 1)
				util.showNone("删除成功")
				// 真机异常, 会导致白屏, 原因未知
				// uni.showModal({
				// 	title: '提示',
				// 	content: '确定删除该商品吗？',
				// 	success: function (res) {
				// 		if (res.confirm) {
				// 			that.shopList.splice(i,1)
				// 			uni.showToast({
				// 				title: '删除成功',
				// 				icon: 'success'
				// 			});
				// 		} else if (res.cancel) {
				// 			uni.showToast({
				// 				title: '取消删除',
				// 				icon: 'none'
				// 			});
				// 		}
				// 	}
				// });
			},
			test() {
				console.log("test")
				let url =
					"https://testmanager.ouxuanzhineng.cn/admin/erpRetailGoods/list?brand_id=63&stadium_id=167&type_key=&key=&page=1&page_size=9999&is_sale=1&is_show_on_assistant=1&token=e6cabeae-0c1a-11ee-aa40-5254005df464";
				//将url请求的参数转化为json对象并打印
				let urlParams = util.getUrlParams(url);
				console.log("urlParams:", urlParams)

				return ox.get({
					url: API.getGoodsList,
					data: urlParams,
					isDefaultGet: false
				}).then(res => {
					console.log("test suc: ", res)
					return res
				})
			},
			// 业务逻辑
			getGoodFromPad(sku, brand_id) {
				return ox.get({
						url: API.getGoodFromPad,
						data: {
							sku,
							brand_id
						},
						isDefaultGet: true
					})
					.then(res => {

						util.hideLoad();
						// console.log("离场校验 suc: ",res)
						if (res.data.code == 0) {}

						return res
					})
			},
			// 更新商品列表
			async updateGoodsList() {
				let _list = await this.getGoodsList()
				//打印信息
				console.log("app.globaldata: ", app.globalData)
				app.globalData.goodsList = _list
			},
			// 更新购物车列表
			updateShopList() {
				app.globalData.shopList = this.shopList
			},
			getGoodsList() {
				let url =
					"https://testmanager.ouxuanzhineng.cn/admin/erpRetailGoods/list?brand_id=63&stadium_id=167&type_key=&key=&page=1&page_size=9999&is_sale=1&is_show_on_assistant=1&token=e6cabeae-0c1a-11ee-aa40-5254005df464";
				let urlParams = util.getUrlParams(url);
				console.log("需要适配urlParams:", urlParams)

				return ox.get({
						url: API.getGoodsList,
						data: urlParams,
						isDefaultGet: true,
						failMsg: "获取商品列表失败"
					})
					.then(res => {

						util.hideLoad();
						console.log("getGoodsList suc: ", res)

						//为res.list中每一项设置shopCountPrice,shopCount
						res.list.forEach(item => {
							item.shopCount = 1
							item.shopCountPrice = item.erp_goods.erp_goods_price
						})
						return res
					})
			},
			searchGoodBySku(sku) {
				console.log("apppp", app)
				return new Promise((resolve, reject) => {
					let _list = app.globalData.goodsList.list
					// let _good = _list.find(item=>item.erp_goods.erp_goods_sku == sku)
					//sku可能不唯一, 返回数组
					let _goods = _list.filter(item => item.erp_goods.erp_goods_sku == sku)

					if (_goods.length) {
						resolve(_goods)
					} else {
						reject("未找到商品")
					}
				})
			},

		}
	}
</script>


<style lang="scss" scoped>
	// page{
	//   background: #F5F7F8;
	// }
	.main-page {
		// background-color: red;
		width: 750rpx;
		@include fls(flex-start);
		flex-direction: column;
		// height: auto;
		// padding-top: 100rpx;
		// padding-bottom: 120rpx;

		.holdplace {
			height: 110rpx;
		}

		// height: 1000rpx;

		// width: 100%;
		// height: 100%;
		// background-color: #fff;
		// display: flex;
		// flex-direction: column;
		// align-items: center;
		// justify-content: center;

		.mheader {
			position: fixed;
			top: 0;
			left: 0;
			width: 750rpx;
			height: 100rpx;
			// background: #fff;
			z-index: 5;
		}

		.mfooter {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 750rpx;
			z-index: 5;
		}
	}
</style>