<template>
	<view class="content">
		<!-- <view class="content-top-bg" :style="{'backgroundColor': vdata.primaryColor}"></view> -->
		<view class="payment">
			<view class="payment-mchName"   @tap="advancedFunc">
				<view style="display: contents;">
					  <image src="/static/img/store.svg" mode="scaleToFill" class="payment-mchName-img"  />
					  	 <view style="display: grid;margin-left: 16rpx;font-size: 35rpx;">
							 付款给交易路由商家
					  		 <!-- <text class="payment-mchName1">{{ vdata.payOrderInfo.mchName }}</text>
					  		 <view class="payment-mchName2">
								 
								 <text class="payment-mchName2-text1">门店</text>
								 <text class="payment-mchName2-text2">{{vdata.payOrderInfo.storeName}}</text>	
							 </view> -->
						</view>
				</view>
			</view>
			<view class="payment-divider"></view>
			<view class="payment-amountTips">
				<view class="desc1 ">付款金额：</view>
				<view class="desc2 " v-if="!vdata.buyerRemark"  @tap="showRemarkModel"><span v-if="vdata.isForceReamrk" style='color: #FF0000;'>*</span>添加备注</view>
				<text class="desc2  buyer-remark" v-else @tap="showRemarkModel">
					{{ vdata.buyerRemark }}
					<text :style="{ 'padding-left': '6rpx'}">修改</text>
				</text>
			</view>
			<view class="payment-amount" >
				<text class="payment-amount-rmb">￥</text>
				<text class="payment-amount-value">{{ doubleToThousands(vdata.amount) }}</text>
			</view>
		</view>
		
		<view class="payment-keyboard" >				
			<syb-keyboard
				ref="sybKeyboardRef"
				:primaryColor="vdata.primaryColor"
				@change="onChange"
				@pay="getSybPayType">
			</syb-keyboard>
		</view>
		
		<view v-if="vdata.remarkVisible" class="remark-model">
			<view class="remark-content">
				<text class="remark-content-title" >添加备注</text>
				<input v-model="vdata.modelRemark" :focus="vdata.remarkVisible" maxlength="40" placeholder="最多输入20个字" class="remark-content-body" />
				<view class="remark-content-btn">
					<text class="btn-cancel" @tap.stop="closeRemarkModel">取消</text>
					<text class="btn-confirm" :style="{'backgroundColor': '#1678FF', 'borderColor': '#ffffff'}" @tap.stop="confirmRemark">确认</text>
				</view>
			</view>
		</view>
		
	</view>
	
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { $getPayOrderInfo, $payApiDoRoute,$getMarketingConfig,$getChannelUserId } from '@/http/apiManager.js'
import { doubleToThousands } from '@/util/amount.js'
import { toErrPageFunc } from '@/util/toErrorPageUtil.js'
import appConfig from '@/config/appConfig.js'
import theme from '@/config/theme.js'
import storageManage from '@/util/storageManage.js'
// import SelectedPay from './components/SelectedPay.vue'
import paywayCallFunc from '@/pages/payway/payway.js'

const sybCodePay = ref()
const sybKeyboardRef = ref()
const selectIfcodeRef = ref()

const vdata = reactive({
	scrollLeft: 0, // 滚动位置
	      scrollSpeed: 2, // 滚动速度，单位px/ms
	      scrollInterval: null, // 定时器ID
		  navigatorUrl:"",
	 payTypeList:[] as any,
	 typeItems: [{
		    img:"/static/img/wechat.png",
			value: 1,
			name: '微信支付',
			checked: false,
		},{
		    img:"/static/img/wechat.png",
			value: 2,
			name: '微信H5',
			checked: false,
		},{
		    img:"/static/payIcon/zfb.png",
			value: 3,
			name: '支付宝支付',
			checked: false,
		},{
		    img:"/static/payIcon/zfb.png",
			value: 4,
			name: '支付宝H5',
			checked: false,
		},{
		    img:"/static/img/payred.png",
			value: 5,
			name: '红包',
			checked: false,
			price: '',
		},
	],
	addIfCodeList:{} as any,
	isAdsOpen:false,
	redPacketIsOpen:false,
	current: 0,
	primaryColor: '',
	originAmount: '0',
	amount: '0',
	buyerRemark: '', // 买家备注
	modelRemark: '', // 弹层显示备注
	remarkVisible: false,
	doubleToThousands: doubleToThousands(),
	payOrderInfo: {},
	calcDiscount:{},
	storeId:'',
	clearStorageFlag: 0, //显示清空缓存的提示
	isForceReamrk:false,
	appid:"",
	tk:"",
	env:"route"
}) as any

onLoad((options) => {	
		uni.setNavigationBarColor({
			backgroundColor: '#ffffff',
			frontColor: '#000000',
		})
		options.env = 'route'	
		if(appConfig.currentPageType == 'alipayLite' && options.env !='route'){
			options = uni.getLaunchOptionsSync().query
		}	
		 uni.setStorageSync('payH5', JSON.stringify(options)) // 改变存储		
		appConfig.payH5 = options
		appConfig.itoken = options.tk
	    storageManage.iToken(options.tk)
		appConfig.tk = options.tk
		appConfig.tokenValue = options.tk
		 if(options.ap){
		   vdata.appid = options.ap;
		 }
		// uni.showToast({title: JSON.stringify(appConfig),icon:'none',duration:5000})
		 if(options.env){
		     vdata.env = options.env;
			   if(vdata.env =='route'){					   
				   // if((appConfig.currentPageType == 'wechatH5' || appConfig.currentPageType == 'alipayH5') && options.env == 'route' && !appConfig.channelUserId){
				   // 	   location.href = appConfig.env.JEEPAY_PAY_BASE_URL+"/pages/hub/h5?tk="+options.tk+"&env="+options.env
				   // 		 return false;
				   // }
			   }
		 }
		 console.log(appConfig.currentPageType,'appConfig.currentPageType')
		 if(appConfig.currentPageType == 'wechatH5' || appConfig.currentPageType == 'wechatLite' || appConfig.currentPageType == 'alipayLite'){
		 	  // getLogin();
		 }
		 if(appConfig.currentPageType == 'alipayH5' && that.env == "scan"){
		 	  // getLogin();
		 }
		 // if(appConfig.currentPageType == 'alipayH5'){
		 // 	 loadScriptAndCallFunction();
		 // }
		 vdata.tk = options.tk;
	
})
onMounted(() => {
 if(appConfig.currentPageType == 'alipayH5'){
 	 // loadScriptAndCallFunction();
 }
})

function loadScriptAndCallFunction() {
  // 动态加载外部 JavaScript 文件
  const script = document.createElement('script');
  script.src = 'https://gw.alipayobjects.com/as/g/h5-lib/alipayjsapi/3.1.1/alipayjsapi.min.js'; // 假设alipayjsapi.min.js在static文件夹中
  script.onload = () => {
	  
	// 脚本加载完成后调用函数
	callApFunction();
  };
  document.head.appendChild(script);
}
function callApFunction() {
  // 调用 ap.getAuthCode() 函数
  ap.getAuthCode({
	appId:vdata.appid,
	// appId:'2021002175627786',
	scopes: ['auth_user']
  }, (res) => {
	  // setPay(res.authCode)	
	uni.showToast({title: "授权"+JSON.stringify(res),icon:'none'})
	// res.authCode
  });
}
function getPayType(){	
	const typeItems = vdata.typeItems
	vdata.payTypeList = [];
	console.log(appConfig.redPacketIsOpen,'appConfigredPacketIsOpen')
	if(!appConfig.redPacketIsOpen){
		delete typeItems[4]
	}
	if(appConfig.currentPageType == 'wechatLite'){
		delete typeItems[1]
	    delete typeItems[2]
	    delete typeItems[3]
	}
	if(appConfig.currentPageType == 'wechatH5'){
	   delete typeItems[0]
	   delete typeItems[2]
	   delete typeItems[3]
	}
	if(appConfig.currentPageType == 'alipayLite'){
	   delete typeItems[0]
	   delete typeItems[1]
	   delete typeItems[3]
	}
	// return uni.showToast({
	// 	title: appConfig.currentPageType,
	// 	icon: 'none'
	// })
	if(appConfig.currentPageType == 'alipayH5'){
	   delete typeItems[0]
	   delete typeItems[1]
	   delete typeItems[2]
	}
	console.log(typeItems,'codePay')
	typeItems.forEach(function(item,index){
		if(index == 4){
			item.price = appConfig.redbalance
		}
		if(appConfig.currentPageType == 'wechatLite' || appConfig.currentPageType == 'wechatH5'){
			if(item.value == 3 || item.value == 4){
				
			}else{				
				vdata.payTypeList.push(item)
			}
		}else if(appConfig.currentPageType == 'alipayLite' || appConfig.currentPageType == 'alipayH5'){
			if(item.value == 0 || item.value == 1){
				
			}else{
				vdata.payTypeList.push(item)
			}
		}
	})
	
	if(typeItems.length){
		typeItems[0].checked = true
	}
}
function updataBank (index,type=0) {
	console.log(type,'typetype')
	pay()
}
function scrollToLower(){
	  vdata.scrollLeft = 0;
}
function getSybPayType(){
	if(vdata.amount <= 0) {
		return uni.showToast({
			title: '金额必须大于0',
			icon: 'none'
		})
		return false;
	}
	if(vdata.payTypeList.length <= 1){
		pay()
		return false;
	}else{
		sybCodePay.value.open();	
	}
}


// 输入金额
function onChange(e: any) {
	if(vdata.payOrderInfo['fixedFlag']){
		return false;
	}
	vdata.amount = e
	vdata.originAmount = e
	
}
function getadsName(){
	if(!appConfig.marketingConfig.isAdsOpen){
		return false;
	}
	uni.navigateTo({
		url: '/pages/H5/H5?url='+ appConfig.marketingConfig.adsUrl
	})
}


// 发起支付
function pay() {
	
	if(vdata.isForceReamrk && !vdata.modelRemark){
		 vdata.remarkVisible = true
		 return false;
	}
	
	if(vdata.amount <= 0) {
		return uni.showToast({
			title: '金额必须大于0',
			icon: 'none'
		})
		return false;
	}
	
	// if(!appConfig.channelUniId){
	// 	getLogin()
	// 	return false;
	// }
	
	uni.showLoading({
		title: '请稍等...',
		mask: true
	})
	$payApiDoRoute(vdata.amount, vdata.buyerRemark).then( ({bizData}) => {
		
		console.log(bizData,'bizDatabizData')
		uni.hideLoading()
		 //订单创建异常
		if(bizData.orderState != 0) {
			let msg = bizData.msg;
			if(bizData.msg =='系统：Success'){
				msg = '订单异常'
			}
		   return uni.showToast({title: msg,icon:'none'})
		} 
		
		if(bizData.orderState == 0){	
			if(appConfig.currentPageType == 'alipayH5' && bizData.extData.payMethod == 0){
				uni.navigateTo({
					url:"/pages/payment/index?ap="+bizData.extData.appid+"&tk="+bizData.payData+"&order_no="+bizData.payOrderId+"&price="+vdata.amount+"&env=scan&opTk="+vdata.tk
				})
			}else if(appConfig.currentPageType == 'wechatH5'  && bizData.extData.payMethod == 0){
				console.log('wechatH5支付')
				uni.navigateTo({
					url:"/pages/payment/index?tk="+bizData.payData+"&order_no="+bizData.payOrderId+"&price="+vdata.amount+"&env=scan&opTk="+vdata.tk
				})
			}else if(appConfig.currentPageType == 'wechatH5'  && bizData.extData.payMethod == 1){	
				
				const query = encodeURIComponent("tk="+bizData.payData+"&order_no="+bizData.payOrderId+"&price="+vdata.amount+"&env=scan&opTk="+vdata.tk+"&env_version=release")
 				const url = "weixin://dl/business/?appid="+bizData.extData.liteAppid+"&path=pages/payment/index&query="+query;
		       console.log('wechatH5小程序支付')
				location.href = url 
			// 	vdata.navigatorUrl = url						
			// 	// 获取a标签
			// setTimeout(()=>{
			// 	var link = document.getElementById('myLink');
			// 	// 模拟点击
			// 	link.click();
			// },2000)
			// window.open(url)

			}else if(appConfig.currentPageType == 'alipayH5'  && bizData.extData.payMethod == 1){
				var query = encodeURIComponent("price="+vdata.amount+"&tk="+bizData.payData+"&order_no="+bizData.payOrderId+"&env=scanXcx&opTk="+vdata.tk+"&env_version=release")
				
			    var url = encodeURIComponent('pages/payment/index');
				
				var pathUrl ="alipays://platformapi/startapp?appId="+bizData.extData.liteAppid+"&page="+url+"&query="+query;
				// window.open(pathUrl)
				// vdata.navigatorUrl = pathUrl						
				// 	// 获取a标签
				// setTimeout(()=>{
				// 	var link = document.getElementById('myLink');
				// 	// 模拟点击
				// 	link.click();
				// },2000)
			   // console.log(pathUrl,'url')
				window.location.href = pathUrl 				
			}else{
				console.log(9999)
			}

			return false;
		}

	}).catch( () => {
		uni.hideLoading()
	})
	
}

// 显示备注弹窗
function showRemarkModel() {
	vdata.modelRemark = vdata.buyerRemark
	vdata.remarkVisible = true 
}

// 备注弹窗确认
function confirmRemark() {
	vdata.buyerRemark = vdata.modelRemark
	vdata.remarkVisible = false
}

// 关闭备注弹窗
function closeRemarkModel() {
	vdata.modelRemark = ''
	vdata.remarkVisible = false
}

// 高级功能模块的显示
function advancedFunc(){
	
	vdata.clearStorageFlag = vdata.clearStorageFlag + 1
	
	if(vdata.clearStorageFlag >= 10){
		vdata.clearStorageFlag = 0
		
		// 目前仅清空缓存
		uni.showModal({
			title: '确认清除缓存？',
			success: function(r) {
				if (r.confirm) {
					uni.clearStorageSync()
					return uni.showToast({title: '已清空'})
				}
			}
		});
	}
	
}

function getLogin(){		
	
	if(appConfig.currentPageType == 'wechatH5' || appConfig.currentPageType == 'alipayH5'){
		 // that.setPay(that.aliCode);
		 that.setPay(null)
		 return false;
	}
	
	
	// 获取服务供应商
	uni.getProvider({
	  service: 'oauth',
	  success: function (res) {
		 // 获取用户登录凭证code
		 // let provider = res.provider[0];
		 uni.login({
		   provider: res.provider[0],
		   success: function (loginRes) {
			 console.log('uniapp登录凭证登录凭证登录凭证登录凭证',loginRes); 
			
			 // #ifdef MP-ALIPAY
				getLoginCode(loginRes.code)
			 // #endif
			 // #ifdef MP-WEIXIN
				 getLoginCode(loginRes.code)
			 // #endif
		   }
		 });
	  }
	});				
}

function getLoginCode(code){
			uni.showLoading({
				title: '加载中...',
				mask: true,
				duration:2000
			}) 
		// 以下为不存在缓存数据
		$getChannelUserId({isUseSubmchAccount:0,code:code}).then(({ bizData }) => {		
			appConfig.channelUserId = bizData;	
			uni.hideLoading()	
			// 保存到localStorage 
			if(bizData.channelUserIdCacheKey){
					storageManage.channelUserId(bizData.channelUserIdCacheKey, bizData)
			}
			if(vdata.amount >0) {
				pay()
				return false;
			}
			console.log(appConfig,'appConfigappConfig')
		}).catch(err => {
			uni.hideLoading()
		})
}

</script>

<style lang="scss">
	.remark-model {
		position: fixed;
		height: 100vh;
		width: 100vw;
		z-index: 20;
		background-color: rgba(0,0,0,0.6);
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		
		.remark-content {
			height: 290rpx;
			width: 600rpx;
			background-color: #FFFFFF;
			border-radius: 20rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			padding: 50rpx 0 20rpx 0;
			margin-bottom: 70%;
			.remark-content-title {
				font-weight: bold;
				font-size: 33rpx;
				letter-spacing: 0.05em;
				margin-left: 50rpx;
			}
			
			.remark-content-body {
				margin-left: 50rpx;
			}
			
			.remark-content-btn {
				display: flex;
				flex-direction: row;
				justify-content: space-around;
				margin-left: 20rpx;
				
				text {
					width: 230rpx;
					height: 90rpx;
					border-radius: 10rpx;
					display: flex;
					flex-direction: row;
					justify-content: center;
					align-items: center;
				}
				
				.btn-cancel{
					background: #fff;
					border: 1rpx solid #c5c7cc;
					font-weight: 500;
					font-size: 30rpx;
					letter-spacing: 0.07em;
					color: #808080;
				}
				
				.btn-confirm{
					border: 3rpx solid #0041c4;
					font-weight: 500;
					font-size: 30rpx;
					letter-spacing: 0.07em;
					color: #fff;
				}
			}
		}
	}
	.content {
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: flex-start;
		width: 100%;
		height: 100%;
		 
		.content-top-bg {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			width: 100%;
			height: 212rpx;
			border-radius: 0 0 30rpx 30rpx;
			z-index: 0;
		}
	}
	
	.payment {
		// position: relative;
		// width: 650rpx;
		width: 96%;
		// height: 321rpx;
		margin-top: 20rpx;
		border-radius: 30rpx;
		background: #fff;
		z-index: 1;
		display: flex;
		flex-direction: column;
		
		.payment-mchName {
			width: 100%;
			// height: 105rpx;
			padding: 30rpx 0;
			font-size: 30rpx;
			letter-spacing: 0.04em;
			padding-left: 30rpx;
			color: #000;
			display: flex;
			align-items: center;
		}
		.payment-divider {
			height: 1rpx;
			width: 100%;
			background-color: $uni-bg-color-grey;
		}
		.payment-amountTips {
			display: flex;
			width: 100%;
			font-size: 25rpx;
			letter-spacing: 0.04em;
			text-align: left;
			padding: 30rpx 0 0 40rpx;
			color: rgba(0, 0, 0, 0.6);
			.desc{
				width: 50%;
			}
			.desc1{
				width: 30%;
			}
			.desc2{
				width: 70%;
				text-align: right;
				margin-right: 10%;
				color: #387CE7;
			    text-decoration: underline;
			}
		}
		.payment-amount {
			padding: 15rpx 0 0 40rpx;
			
			.payment-amount-value {
				font-size: 80rpx;
				letter-spacing: 0.03em;
				padding-left: 15rpx;
			}
		}
	}
	.payment-keyboard {
		width: 100%;
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 5;
		bottom: constant(safe-area-inset-bottom);
		bottom: env(safe-area-inset-bottom);
		
		.buyer-remark {
			position: absolute;
			top : -80rpx;
			width: 100%;
			display: flex;
			flex-direction: row;
			justify-content: center;
		}
	}
	.payment-no-keyboard {
		width: 80%;
		height: 88rpx;
		position: fixed;
		left: 10%;
		right: 10%;
		bottom: 240rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 36rpx;
		color: $uni-text-color-inverse;
		border-radius: 8rpx;
	}
	.payment-text{
		margin-bottom: 16rpx;
		width: 92%;
		background: #FAFAFA;
		display: flex;
		padding:15px;
		color: #8F97A9;
		margin-left: 1%;
		.txt{
			width: 50%;
		}
		.payment-text-guanggao{
			text-align: left;
			 width: 100%;
			overflow: hidden;
			white-space: nowrap;
		}
		.payment-text-amount{
			text-align: right;
			// margin-right: 10%;
			text{
				font-weight: 600;
				color: #000;
			}
		}
	}
	.pay-div-type{
		width: 96%;
		border-radius: 5%;
		margin-left: 1%;
		margin-top: 10px;
		background: #ffffff;
		.radio-group-box{
			padding: 20rpx;
			border-bottom: 2rpx solid #F4F4F4;
			.radio-group-div{
				width: 50%;
			}
			.radio-group-name{
				width: 70%;
				text-align: left;
				display: flex;
				image{
					width: 50rpx;
					height: 50rpx;
					border-radius: 50%;
				}
				text{
					padding: 8rpx 0 10rpx 10rpx ;
				}
				.radio-group-name-price{
					color: #c3c3c3;
				}
			}
			.radio-group-radio{
				width: 30%;
				text-align: right;
			}
		}
	}
	
	.payment-amountTips-price{
		display: flex;
		width: 100%;
		font-size: 25rpx;
		letter-spacing: 0.04em;
		text-align: left;
		padding: 30rpx 0 0 40rpx;
		color: rgba(0, 0, 0, 0.6);
		padding: 20rpx 0;
		.desc3{
			font-size: 21rpx;
			width: 50%;
			text-align: left;
			margin-left: 3%;
			color: #3D3D3D;			
			.desc3-text1{
				border:2rpx solid #FE5735 ;
				border-radius: 10rpx;
				color: #FE5735;
				padding: 2rpx;
			}		
			.desc3-text2{
				padding-left: 8rpx;
			}
		}
		.desc4{
			font-size: 30rpx;
			width: 50%;
			text-align: right;
			margin-left: 3%;
			margin-right: 20rpx;
			color: #3D3D3D;			
			.desc4-text1{
			   color: #8F97A9;		
			   font-size: 24rpx;
				// border:2rpx solid #FE5735 ;
				// border-radius: 10rpx;
				// color: #FE5735;
				padding: 2rpx;
			}		
			.desc4-text2{
				font-weight: 600;
				padding-left: 8rpx;
			}
		}
	}
	.payment-mchName-img{
		width: 120rpx;
		height: 120rpx;
		margin-right: 10rpx;
	}
	.payment-mchName1{
		font-size: 32rpx;
		font-weight: 500;
	}
	.payment-mchName2{
		font-size: 26rpx;
		margin-top: 15rpx;
		font-weight: 400;
	}
	.payment-mchName2-text1{
		color: #3598FE;
		border: 1px solid #3598FE;
		border-radius: 10rpx;
		padding: 4rpx 8rpx;
	}
	.payment-mchName2-text2{
		font-size: 28rpx;
		color: #3D3D3D;
		margin-left: 10rpx;
	}
	  .scroll-view {
	    width: 100%;
	  }
	 .scroll-content {
	    display: inline-block;
	    // width: 1000rpx; /* 设置一个足够大的宽度以确保文本可以滚动 */
	    animation: slide 5s linear infinite;
	  }
	   @keyframes slide {
	      0% {
	        transform: translateX(0);
	      }
	      100% {
	        transform: translateX(-100%);
	      }
		}
</style>
