<template>
	<div class="content">
		<custom-header title="订单详情" :back="config.hasReturn === 'true'"></custom-header>
		<div style="padding: 20rpx" v-if='isShow'>
			<view class="title">
				订单详情
			</view>
			<view class="container">
				<template v-for='(item,index) in formData'>
					<view class="detail-item" :key='index' v-if='item.value !== "" && item.value !== undefined'>
						<text>{{item.label}}</text>
						<text class="amount">{{item.key === 'amount'? '￥'+ item.value:item.value}}</text>
					</view>
				</template>

			</view>
			<view class="payment-total">
				<text>实付款</text>
				<text class="amount">￥{{amount}}</text>
			</view>
			<button type="success" class="btn-txt btn" @click="submit">确认办理</button>
		</div>
	</div>
</template>
<script setup lang='ts'>
	import {
		unifyTemplate
	} from '@/hooks/unifyTemplate'
	import {
		reactive,
		ref
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		request,
		myJsonp,
		toWeixin
	} from '@/utils/network/request'
	import {
		setToken,
		getToken
	} from '@/utils/storage'
	const {
		CustomHeader, //头部组件
		initData, //初始化数据
		isShow, //是否展示formBuilderVue组件
		qdOrderVal //qdOrder中数据 ref
	} = unifyTemplate() //初始化数据
	// import {
	// 	request
	// } from '../../static/js/network/request'

	let formData = reactive < any > ([{
		label: '产品名',
		value: '',
		key: "product",
		key1: 'promoteName',
	}, {
		label: '车牌号',
		key: "vehiclePlate",
		value: '贵'
	}, {
		label: '车主姓名',
		key: "ownerName",
		value: ''
	}, {
		label: '邮寄地址',
		key: "orderInfoExt",
		key1: 'region,address',
		default: "不邮寄",
		value: ''
	}, {
		label: '产品金额',
		key: "amount",
		format: (val) => {
			return val * 0.01
		},
		value: '0'
	}, ])
	// 实付款
	const amount = ref < any > ('')
	let config = ref < any > ({
		submitName: '提交',
		titleWidth: 160
	})
	onLoad((opin) => {
		// 初始化数据
		initData(opin, 4).then(async data => {
			await login(data)
			detectAliPay()
			getOrderInfo(data.qdOrder.qtOrderNo)
			delete data.config.tableConfig
			config.value = Object.assign(data.config, config.value)
		})
	})
	// 无感登录,如果没有登录调用登录
	async function login(orderData) {
		const token = getToken();
		if (token) {
			return
		}
		let data = {
			userType: '',
			account: ''
		}
		if (qdOrderVal.value.userType == 1) {
			// 个人办理
			data.userType = 'PERSONAL'
			data.account = orderData.order.customerTel
		} else {
			// 单位办理
			data.userType = 'ENTERPRISE'
			data.account = orderData.order.customerIdnum
		}
		await request('abaf0013caa24dafad12b0f571e8ee40', {
			data,
		}).then((res) => {
			if (res.statusCode === 0) {
				let bizContent = JSON.parse(res.bizContent)
				// 保存token
				setToken(bizContent.accessToken)
			}
			// contractTesting(qdOrderVal.value.qdOrderNo, jumpPage)
		})
	}
	// 订单已支付
	async function detectAliPay() {
		await request('56', {
			data: {
				orderId: qdOrderVal.value.qdOrderNo
			}
		}).then((res) => {
			if (res.statusCode === 0) {
				let data = JSON.parse(res.bizContent)
				if (data.tradeState === 'SUCCESS') {
					let {
						jumpPage
					} = config.value
					contractTesting(qdOrderVal.value.qdOrderNo, jumpPage)
				}
			}
			// contractTesting(qdOrderVal.value.qdOrderNo, jumpPage)
		})
	}
	// 数据处理
	function getOrderInfo(orderId) {
		request('8', {
			data: {
				orderId
			}
		}).then((res) => {
			let data = JSON.parse(res.bizContent)
			amount.value = data.amount * 0.01
			formData.forEach(item => {
				let itemData = data[item.key]
				if (typeof itemData === 'object') {
					if (item.key1.includes(',')) {
						let str = ''
						item.key1.split(',').forEach(listItem => {
							str += itemData[listItem] || ''
						})
						itemData = str
					} else {
						itemData = itemData[item.key1]
					}
				}
				if (item.format) {
					itemData = item.format(itemData)
				}
				item.value = itemData || item.default
			})
			isShow.value = true;
		})
	}
	//提交
	function submit() {
		// console.log('提交内容', item)
		uni.showLoading({
			title: '正在支付...',
			mask: true
		})
		// let {
		// 	jumpPage
		// } = config.value
		// setTimeout(() => {
		// 	uni.hideLoading()
		// 	contractTesting(qdOrderVal.value.qdOrderNo, jumpPage)

		// }, 1000)

		// 根据公网ip获取支付地址
		myJsonp({
			url: 'https://www.taobao.com/help/getip.php',
			success(res) {
				console.log(res)
				// const data = {
				// 	fee: 1,
				// 	spbillCreateIp: res.ip,
				// }
				request('56', {
					data: {
						orderId: qdOrderVal.value.qdOrderNo,
						payConfigId: '6a9a54bc01f6443faea7ffe132b1234',
						h5Type: 'Wap',
						spbillCreateIp: res.ip,
					}
				}).then((res) => {
					uni.hideLoading()
					if (res.statusCode === 0) {
						let data = JSON.parse(res.bizContent)
						window.open(data.h5Url, '_blank')
					}
					// contractTesting(qdOrderVal.value.qdOrderNo, jumpPage)
				})
			}
		})
	}
	// 签约检测
	function contractTesting(qdOrderNo, jumpPage) {
		const data = {
			qdOrderNo,
		}
		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才进行下一步，否则进行签约初始化
					if (!jumpPage) return
					uni.navigateTo({
						url: '/' + jumpPage,
						animationType: 'pop-in',
						animationDuration: 500
					})
					/* 自定义返回 */
				} else {
					// 进行签约初始化
					signingInitialization(qdOrderNo)
				}
				// qdOrderStore.orderInfo.value.orderId = JSON.parse(res.bizContent).orderId
				// 通过检测
			}
		})
	}
	// 签约初始化
	function signingInitialization(qdOrderNo) {
		const data = {
			qdOrderNo
		}
		request('94569071cf814517908cd35693f1f2e1', {
			data,
		}).then((res) => {
			if (res.statusCode === 0) {
				const data = JSON.parse(res.bizContent)
				if (data.returnType === 0) {
					// 0-无需跳转，关闭H5即可 1-需跳转至返回url
					// const opened = window.open('about:blank', '_self');
					// opened.opener = null;
					// opened.close();
					closeWin()
				} else {
					window.open(data.signUrl, '_self')
				}
			}
		})
	}
	// 关闭当前页面方法
	function closeWin() {
		// @ts-ignore
		var jWeixin = import('jweixin-module')
		// @ts-ignore
		jWeixin.miniProgram.getEnv(function(res) {
			if (res.miniprogram) {
				// @ts-ignore
				jWeixin.miniProgram.navigateTo({
					url: '/path/to/page'
				})
			} else {
				const opened = window.open('about:blank', '_self');
				opened.opener = null;
				opened.close()
			}
		})
	}
</script>
<style lang='scss' scoped>
	.title {
		font-size: 30rpx;
		margin-left: 30rpx;
	}

	.container {
		padding: 10px;
		font-size: 14px;

		.detail-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 5px;
			margin-bottom: 8px;
			border-bottom: 1px solid #ccc;
		}
	}

	.payment-total {
		text-align: right;
		padding: 0 10px 20px;
	}

	text {
		margin-left: 10px;
	}

	.amount {
		color: #1AAC1B;
		max-width: 450rpx;
	}

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

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