<template>
	<view class="pay-page">
		<keyboard-listener @keyup="onKeyup" @keydown="onKeydown" ></keyboard-listener>
		<view v-if="paySuccessStatus==0">
			<view-header class="mheader" :backgroundCustom="('none')" :needBorder="(false)" 
			@closeUse=""></view-header>
			<paying v-if="true" @clickVipCard="handle_clickVipCard"></paying>
		</view>
		<pay-success v-else></pay-success>
		
		<!-- 手机尾号后4位数验证 -->
		<input-box-end-phone v-if="showEndPhoneBox"  :maskHeight="screenHeight" :maxInput="4"
		@showIt="handle_closeEndPhoneBox" @clickCommit="handle_clickCommit_end_phone"></input-box-end-phone>

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

<script>
	import util from "@/utils/util.js"
	import {
		API
	} from "@/utils/api";
	import {
		ox
	} from "@/utils/server";
	import dictKeyboard from '@/utils/dictOfKeyboard'
	import viewHeader from '@/components/index/view_header.nvue';//头部
	import inputQrBox from '@/components/index/keyboard/input_box_QR.vue'; //条形码
	import inputBoxEndPhone from '@/components/index/keyboard/input_box_end_phone.vue';//手机号尾号
	import paying from '@/components/pay/paying.vue';//支付中
	import paySuccess from '@/components/pay/success.vue';//支付成功
	import keyboardListener from '@/components/index/keyboard/keyboard_listener.vue';//键盘监听

	export default {
		components: {
			'view-header': viewHeader,
			'input-box-end-phone': inputBoxEndPhone,
			'paying': paying,
			'pay-success': paySuccess,
			'input-qr-box': inputQrBox,
			'keyboard-listener': keyboardListener,
		},
		watch:{

		},
		data() {
			return {
				showPageStandby: false,
				showEndPhoneBox:false,
				screenHeight: '1000',
				footerHeight: '',
				paySuccessStatus:0,
				decryptList: [],
				strResult: "",
				dataQuery:""
			}
		},
		async onLoad(res) {
			console.log("pay onload:",res)
			this.setPayData(res)
		},
		async onReady() {
			await this.setPageHeight()
		},
		methods: {
			setPayData(res){
				console.log("setPayData:",res)
				res = JSON.parse(res.query)

				console.log("setPayData1:",res)
				let _data = {
					goods_data:res.shopList,
					amount:res.shopListTotalPrice,
				} 
				console.log("setPayData2:",_data)
				this.dataQuery = _data
			},
			// 字符数字10，11，12，13，14，15开头是WECHAT_MICROPAY,28是ALI_BARCODEPAY
			getPayType(code){
				let pay_type = ""
				if(code.indexOf("10") == 0 || code.indexOf("11") == 0 || code.indexOf("12") == 0 || code.indexOf("13") == 0 || code.indexOf("14") == 0 || code.indexOf("15") == 0){
					pay_type = "WECHAT_MICROPAY"
				}else if(code.indexOf("28") == 0){
					pay_type = "ALI_BARCODEPAY"
				}else{
					pay_type = null
				}
				return pay_type
			},
			async acceptScanCode(code) {
				console.log("acceptScanCode:",code)
				// util.showNone("支付中...")
				util.showLoad("交易处理中...")
				let pay_code = code
				let pay_type = this.getPayType(pay_code)
				
				if(pay_type == null){
					util.showNone("支付类型未知,请重试！")
					return
				}
				await this.makeOrder((makeInfo)=>{
					console.log("makeInfo-result",makeInfo)
				}).then((orderInfo)=>{
					console.log("orderInfo-result",orderInfo)
					return this.payOrder({
						"order_no":orderInfo.order_no,
						pay_code,pay_type
					})
				}).then((payInfo)=>{
					console.log("payInfo-result:",payInfo)
					return this.checkOrder(payInfo)
				}).then((checkInfo)=>{
					console.log("最终checkInfo:",checkInfo)
					let {payRes,checkRes} = checkInfo
					// util.showNone(payRes.res.respMsg+"-"+payRes.res.respCode)
					if(checkRes.pay_order.status == "1"){
						util.showNone(checkRes.res.respMsg+"-"+checkRes.res.respCode)
						this.paySuccessStatus = 1
					}else{
						util.showNone(checkRes.res.respMsg+"-"+checkRes.res.respCode)
					}
				}).finally(()=>{
					util.hideLoad()
				})
			},
			async makeOrder(){
				let {store_id,brand_id,token} = getApp().globalData.accountInfo
				let {goods_data,amount} = this.dataQuery
				let urlParams = {
					store_id,brand_id,token,amount,
					"goods_data": goods_data,
					"pay_type": 7,
					"other_pay_type":"付款码支付",
					"card_no": "",
					"mark": ""
				}
				console.log("需要适配makeOrder urlParams:", urlParams)
				
				return ox.post({
					url: API.makeOrder,
					data: urlParams,
					isDefaultGet: true,
					failMsg: '操作失败！'
				})
				.then(res => {
					util.hideLoad();
					console.log("makeOrder suc: ", res)
					return res
				})
			},
			payOrder(orderInfo){
				console.log("payOrder get param:",orderInfo)
				let {order_no,pay_code,pay_type} = orderInfo
				let {goods_data,amount} = this.dataQuery
				let {store_id,brand_id,token} = getApp().globalData.accountInfo
				let urlParams = {
					order_no,
					pay_code,
					pay_type,
					brand_id,
					token,
					"order_amt": amount, //未知TODO 问家华- 猜测是金额
					"goods_info": order_no,
				}
				
				console.log("需要适配payOrder urlParams:", urlParams)
				
				return ox.post({
					url: API.payOrder,
					data: urlParams,
					isDefaultGet: true,
					failMsg: "payOrder fail"
				})
				.then(res => {
					console.log("payOrder suc: ", res)
					let _pay_res = {
						"order_no": order_no,
						"pay_code": pay_code,
						"pay_type": pay_type,
						"orderAmt":res.res.orderAmt,
						"transNo":res.res.transNo,
						"res":res.res
					}
					return _pay_res
				})
			},
			checkOrder(res){
				let {store_id,brand_id,token} = getApp().globalData.accountInfo
				let {transNo,orderAmt,payCode} = res

				let urlParams= {
					transNo,payCode,brand_id,token,orderAmt,
					"manual": "yes",//是否手动
				}
				console.log("需要适配checkOrder urlParams:", urlParams)
				
				return ox.get({
					url: API.checkOrder,
					data: urlParams,
					isDefaultGet: true,
					failMsg: "checkOrder fail"
				})
				.then(res2 => {
					console.log("checkOrder suc: ", res)
					return {
						payRes:res,
						checkRes:res2
					}
				})
			},
			handle_clickVipCard() {
				util.showNone("储值卡支付未接入")
				// this.paySuccess = true
				this.handle_clickVIP()
				// util.routeTo(`/pages/pay/success`, 'nT');
			},

			handle_closeEndPhoneBox(val) {
				console.log("handle_closeEndPhoneBox", val)
				this.showEndPhoneBox = !this.showEndPhoneBox
			},
			handle_clickCommit_end_phone(val) {
				console.log("handle_clickCommit_end_phone", val)
				this.showEndPhoneBox = !this.showEndPhoneBox
			},
			handle_closeQRInputBox(val) {
				console.log("handle_closeQRInputBox", val)
			},
			handle_clickCommit_qr(val) {
				console.log("handle_clickCommit_qr", val)
				this.showQRInputBox = !this.showQRInputBox
			},

			handle_clickVIP() {
				// util.showNone("会员登录")
				this.showEndPhoneBox = !this.showEndPhoneBox
			},
			async setPageHeight(){
				this.screenHeight = await util.getPageHeight()
			},

			// 按键松开事件
			async onKeyup(event) {
				let res = dictKeyboard.dict[event.keyCode];
				this.decryptList.push(res);
				if(event.keyCode != 13) {
					return console.log("this.decryptList1: ",this.decryptList)
				};
				this.decryptList.pop();
				this.strResult = await dictKeyboard.resultScan(this.decryptList);
				this.orderQrcode = this.strResult
				// console.log("扫码结果--：", this.strResult)
				this.decryptList.splice(0);
				console.log("this.decryptList: "+this.decryptList)
				//过滤结果中的down_arrow
				if(this.strResult.indexOf("down_arrow") != -1){
					this.strResult = this.strResult.replace("down_arrow","")
				}
				console.log("扫码最终结果--：", this.strResult)
				this.acceptScanCode(this.strResult)
				
			}, 
			
			// 监听按键按下事件
			onKeydown(event) {
				// console.log("监听按键按下事件: ",event)
			},
			
		}
	}
</script>


<style lang="scss" scoped>
	.pay-page {
		width: 750rpx;
		.mheader{
			width: 750rpx;
		}
	}
</style>