<template>
	<view class="content" v-if="online === 2">
		<image class="bg-image" mode="widthFix"
			src="https://qtzl.etcjz.cn/default-bucket/20240324/3eba2095f5204798a1f8101b_beijing.jpg"></image>
		<view class="content-re">
			<custom-header title="支付账户签约" :back="false"></custom-header>
			<view style="padding: 20rpx 0 30rpx" class="order-content">
				<!-- 获取产品展示 -->
				<view class="order-car" v-for="(item, index) in paymentChannelList" :key="index">
					<view class="l-img">
						<image class="icon-tip" :src="item.imgUrl" mode="aspectFit"></image>
					</view>
					<view class="c-amount">
						<view class="goods-name">
							{{ item.name }}
						</view>
						<view class="goods-des">
							{{ item.desc }}
						</view>
						<view class="goods-label">
							<view class="label-item" v-for="(labelItem, index) in item.label" :key="index">
								<u-tag :text="labelItem" mode="light" size="mini" bg-color="#38ca83" border-color="#38ca83"
									color="#fff" />
							</view>
						</view>
					</view>
					<view class="r-btn">
						<u-button shape="circle" plain class="custom-style" @click="handleCon">
							签约
						</u-button>
					</view>
				</view>
			</view>
		</view>
		<u-popup v-model="show" mode="right" :closeable="true" length="100%" z-index="990">
			<view style="background-color: #f4f4f4; height: 100vh; position: relative">
				<view class="title">签约</view>
				<view class="slot-content">
					<view style="background-color: #fff">
						<view class="con-img">
							<!-- <qrcode-vue :value="qrCodeValue" level="H" :render-as="renderAs" style='width: 100%;height: 100%;' /> -->
							<image style="width: 100%; height: 100%" :src="imageSign" mode="aspectFit"></image>
						</view>
						<view class="con-info">请打开微信扫码完成签约</view>
					</view>
				</view>
				<view class="bottom-btn">
					<button type="success" class="btn-txt btn" @click="handleNext">
						下一步
					</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>
<script setup lang="ts">
	import { fileURL } from '@/utils/network/api.js';
	import { reactive, ref } from 'vue';
	import { unifyTemplate } from '@/hooks/unifyTemplate';
	import { onLoad } from '@dcloudio/uni-app';
	import { request, requestNew } from '@/utils/network/request';
	import wx from 'weixin-js-sdk';
	import QrcodeVue, { Level, RenderAs } from 'qrcode.vue';
	import { setToken, getToken, StorageKeys, setItem } from '@/utils/storage';
	import { handleToTypes } from '@/utils/utils';
	const {
		CustomHeader //头部组件
	} = unifyTemplate(); //初始化数据
	const qrCodeValue = ref('111')
	const {
		initData, //初始化数据
		qdOrderVal //qdOrder中数据 ref
	} = unifyTemplate(); //初始化数据
	const online = ref(1); //1为线上，2为线下
	const jumpPage = ref('pages/payment/signAContract');

	//获取页面配置
	onLoad((opin) => {
		initData(opin, 4).then(async (data) => {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			// if (opin.jumpPage) {
			// 	jumpPage.value = opin.jumpPage
			// }
			jumpPage.value = data.config.jumpPage || jumpPage.value;
			online.value = data.order.promotionModes;
			await login(data);
			let key = await contractTesting(
				qdOrderVal.value.orderNo,
				jumpPage.value,
				true
			);
			if (key) {
				return;
			}
			if (data.order.promotionModes === 1) {
				// 线上直接去内部判断
				handleToType(data.order.orderNo);
			} else {
				uni.hideLoading();
				getCodeIamge(data.order.orderNo);
			}
		});
	});
	// 获取签约二维码

	const getCodeIamge = (orderId) => {
		let data = {
			orderId,
			accessToken: loginData.token
		};
		// const code = '5f0b52cc55b94827840966e3af05ec53' //原有签约
		// const code = '79d2e1d45b88470985b358394748e45e'//更改签约
		requestNew('/iaw/issue/order/generateOrderSignQR', {
			data
		}).then((res) => {
			if (res.code === 0) {
				let bizContent = res.data;
				const reg = /^\//;
				if (!reg.test(bizContent.codeUrl)) {
					bizContent.codeUrl = '/' + bizContent.codeUrl;
				}
				// 处理为完整路径
				imageSign.value =
					window.location.protocol +
					'//' +
					window.location.host +
					bizContent.codeUrl;
				console.log('签约图片', bizContent);
			}
		});
	};
	// 无感登录,如果没有登录调用登录
	const loginData = reactive({
		token: '',
		openId: ''
	});
	async function login(orderData) {
		let data = {
			userType: '',
			accountNumber: '',
			loginSource: '431bfdc8b9c645e0b293b85d6ce1948n',
		};
		if (orderData.order.userType === 'PERSONAL_USER') {
			// 个人办理
			data.userType = 'PERSONAL';
			data.accountNumber = orderData.order.customerTel;
		} else {
			// 单位办理
			data.userType = 'ENTERPRISE';
			data.accountNumber = orderData.order.customerIdnum;
		}
		console.log(data, '无感登录', qdOrderVal.value);
		await requestNew('/iaw/portal/loginByNoPassword', {
			data
		}).then((res) => {
			if (res.code === 0) {
				let data = res.data;
				console.log('login', data);
				setToken(data.accessToken);
				setItem(StorageKeys.OpenId, data.openId)
				// 保存token
				loginData.token = data.accessToken;
				loginData.openId = data.openId;
			}
		});
	}
	// 处理进入类型
	const handleToType = (orderNo) => {
		let type = parseInt(uni.getStorageSync('web_type')) || '';
		let userAgent = navigator.userAgent.toLowerCase();
		console.log('类型', type);
		const agentType = handleToTypes();
		if (type) {
			if (type === 1) {
				// 微信小程序
				handleTonei();
			} else if (type === 2) {
				// 微信公众号
				handleToWai();
			} else if (type === 3) {
				// 支付宝小程序
				handleToZhifubao();
			} else {
				uni.hideLoading();
				getCodeIamge(orderNo);
			}
		} else {
			if (agentType === 'alipaymini') {
				// 支付宝小程序环境
				handleToZhifubao();
			} else if (agentType === 'wechatmini') {
				// 微信内部
				handleTonei();
			} else if (agentType === 'wechat') {
				// 微信公众号
				handleToWai();
			} else {
				uni.hideLoading();
				online.value = 2;
				getCodeIamge(orderNo);
			}
		}
	};
	const paymentChannelList = [
		{
			name: '微信支付',
			imgUrl: `${fileURL}image/applyCard/wx.png`,
			desc: '服务费是每笔交易金额的0',
			label: ['微信代付', '微信便捷支付']
		}
	];
	const show = ref(false);
	const imageSign = ref<String>('');
	const renderAs = ref<RenderAs>('svg');
	// 签约按钮
	function handleCon() {
		show.value = true;
	}

	// 点击下一步
	function handleNext() {
		contractTesting(qdOrderVal.value.orderNo, jumpPage.value);
	}
	// 跳转支付宝小程序
	function handleToZhifubao() {
		let token = loginData.token;
		let openId = loginData.openId;
		my.navigateTo({
			// appid:'2021004102619032',
			url: `/subpackage/orders/sign/sign-up-ali?token=${token}&openId=${openId}&orderId=${qdOrderVal.value.orderNo}&qdOrderNo=${qdOrderVal.value.orderNo}`
		});
	}
	// 跳转微信小程序内部
	function handleTonei() {
		let token = loginData.token;
		let openId = loginData.openId;
		// let data = JSON.parse(res.data.rd.bizContent)
		wx.miniProgram.navigateTo({
			// appId: 'wx008c60533388527a', // 要打开的小程序的AppID
			// url: `/pages/sign/auth?accessToken=${token}&openId=${openId}&orderId=${qdOrderVal.value.qtOrderNo}&qdOrderNo=${qdOrderVal.value.qdOrderNo}&reset=111`, // 可选，小程序的页面路径，可以不填
			url: `/carPark/pages/dmc/signingAContract/signingAContract?accessToken=${token}&openId=${openId}&orderId=${qdOrderVal.value.orderNo}&qdOrderNo=${qdOrderVal.value.orderNo}&reset=111`, // 可选，小程序的页面路径，可以不填
			extraData: {
				// 可选，传递给小程序的数据，如分享信息等
			},
			success(res) {
				// 打开小程序成功的回调
				// console.log(res);
				// alert(JSON.stringify(res) + '123')
			},
			fail(err) {
				// 打开小程序失败的回调
				// console.error(err);
				// alert(JSON.stringify(err) + '456')
			}
		});
	}

	// 跳转微信小程序-外链
	function handleToWai() {
		let token = loginData.token;
		let openId = loginData.openId;
		let getTokenUrl =
			'/cgi-bin/token?grant_type=client_credential&appid=wx008c60533388527a&secret=95197718b43b497f02732bd9f8011080';
		let getUrl = '/wxa/generatescheme?access_token=';

		uni.request({
			url: getTokenUrl,
			method: 'GET', //请求方式，必须为大写
			success: (res) => {
				// console.log('接口返回------', res);
				let accessToken = res.data['access_token'];
				uni.request({
					url: getUrl + accessToken,
					method: 'POST', //请求方式，必须为大写
					data: {
						jump_wxa: {
							path: '/carPark/pages/dmc/signingAContract/signingAContract',
							query: `accessToken=${token}&openId=${openId}&orderId=${qdOrderVal.value.orderNo}&qdOrderNo=${qdOrderVal.value.orderNo}&reset=111`,
							env_version: 'develop' //正式版为"release"，体验版为"trial"，开发版为"develop"，仅在微信外打开时生效。
						}
					},
					success: (res) => {
						console.log('接口返回------', res);
						if (res.data.errcode === 0) {
							location.href = res.data.openlink;
						}
						uni.hideLoading();
					}
				});
			}
		});
	}
	// 签约检测
	const contractTesting = async (orderNo, jumpPage, isInit = false) => {
		const data = {
			orderNo: orderNo
		};

		return await requestNew('/iaw/h5/order/web/signcheck', {
			data
		}).then((res) => {
			if (res.code === 0) {
				const data = res.data;
				if (
					data.signStatus === 1 &&
					data.accountStatus === 1 &&
					data.bindStatus === 1
				) {
					// 上面三值都为1才进行下一步，否则进行签约初始化
					uni.navigateTo({
						url: '/' + jumpPage + `?qdOrderNo=${orderNo}`,
						animationType: 'pop-in',
						animationDuration: 500
					});
					return true;
					/* 自定义返回 */
				} else {
					// 进行签约初始化
					// 提醒未通过
					if (!isInit) {
						uni.showModal({
							title: '提示',
							content: '请使用微信扫描二维码进行签约',
							success: function (res) { }
						});
					}
				}
				// qdOrderStore.orderInfo.value.orderId = JSON.parse(res.bizContent).orderId
				// 通过检测
			}
		});
	};
	// async function contractTesting(qdOrderNo, jumpPage, isInit = false) {
	// 	const data = {
	// 		qdOrderNo
	// 	};
	// 	// uni.navigateTo({
	// 	// 	url: '/' + jumpPage,
	// 	// 	animationType: 'pop-in',
	// 	// 	animationDuration: 500
	// 	// })
	// 	// signingInitialization(qdOrderNo)
	// 	// return
	// 	uni.showModal({
	// 		title: '提示',
	// 		content: '请使用微信扫描二维码进行签约',
	// 		success: (res) =>{
	// 			console.log(res);
	// 		},
	// 		fail:(err)=>{
	// 			console.log(err);
	// 		}
	// 	});
	// 	return  request('fdfbdddba6ec49f8b451cf2e299b4feb', {
	// 		data
	// 	}).then((res) => {
	// 		if (res.statusCode === 0) {
	// 			const data = JSON.parse(res.bizContent);
	// 			if (
	// 				data.signStatus === 1 &&
	// 				data.accountStatus === 1 &&
	// 				data.bindStatus === 1
	// 			) {
	// 				// 上面三值都为1才进行下一步，否则进行签约初始化
	// 				uni.navigateTo({
	// 					url: '/' + jumpPage + `?qdOrderNo=${qdOrderNo}`,
	// 					animationType: 'pop-in',
	// 					animationDuration: 500
	// 				});
	// 				return true;
	// 				/* 自定义返回 */
	// 			} else {
	// 				// 进行签约初始化
	// 				// 提醒未通过
	// 				console.log('isInit', isInit);
	// 				if (!isInit) {
	// 					console.log('isInit', isInit, uni.showModal);
	// 					uni.showModal({
	// 						title: '提示',
	// 						content: '请使用微信扫描二维码进行签约',
	// 						success: function (res) {}
	// 					});
	// 				}
	// 			}
	// 			// qdOrderStore.orderInfo.value.orderId = JSON.parse(res.bizContent).orderId
	// 			// 通过检测
	// 		}
	// 	});
	// }
</script>
<!-- 签约管理 -->
<style lang="scss" scoped>
	.order-car {
		margin: 30rpx 30rpx 0;
		width: calc(100% - 60rpx);
		height: 190rpx;
		border-radius: 20rpx;
		background-image: linear-gradient(to right, #15e5c3, #44a2df);
		display: flex;
		justify-content: space-between;
		box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
		align-items: center;
		color: #fff;

		.l-img {
			flex-shrink: 0;
			width: 120rpx;
			height: 120rpx;

			.icon-tip {
				height: 100%;
				width: 100%;
				object-fit: contain;
			}
		}

		.c-amount {
			flex: 1;
			padding: 20rpx 0;
			height: 100%;
			box-sizing: border-box;

			.goods-name {
				margin-bottom: 15rpx;
				font-size: 38rpx;
			}

			.goods-des {
				font-size: 26rpx;
				margin-bottom: 15rpx;
				color: #eff;
			}

			.goods-label {
				display: flex;
				align-items: center;

				.label-item {
					margin-right: 10rpx;
				}
			}
		}

		.r-btn {
			margin-left: 10rpx;
			flex-shrink: 0;
			width: 130rpx;
			margin-right: 20rpx;

			.custom-style {
				height: 70rpx;
				color: #fff;
				border-color: #fff;
				background-color: rgba(255, 255, 255, 0.2);
			}
		}
	}

	.title {
		font-size: 36rpx;
		text-align: center;
		font-weight: bold;
		padding: 20rpx 0;
	}

	.slot-content {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: absolute;
		top: 40%;
		left: 50%;
		transform: translate(-50%, -50%);

		.con-img {
			width: 550rpx;
			height: 550rpx;
			padding: 100rpx;
			box-sizing: border-box;
		}

		.con-info {
			text-align: center;
			font-size: 26rpx;
			margin-bottom: 100rpx;
		}
	}

	.bottom-btn {
		position: absolute;
		padding: 20rpx;
		display: flex;
		align-items: center;
		bottom: 100rpx;
		width: 750rpx;

		.btn {
			height: 80rpx;
			opacity: 1;
			border-radius: 100rpx;
			margin: 20rpx 20rpx 20rpx 20rpx;
			width: 100%;
		}

		.btn-txt {
			background: #1aac1b;
			margin: 10px;
			color: #ffffff;
			font-size: 28rpx;
		}
	}
</style>