<template>
	<view class="content">
		<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="config.hasReturn === 'true'"></custom-header>
			<view 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 && !item.isHide'>
							<text>{{item.label}}</text>
							<text class="amount">{{item.key === 'amount'? '￥'+ item.value:item.value}}</text>
						</view>
					</template>
					<template v-for='(item,index) in amountList'>
						<view class="detail-item" :key='index'
							v-if='item.value !== "" && item.value !== undefined &&  parseFloat(item.value) !== 0'>
							<text>{{item.label}}</text>
							<view>
								<text class="amount">{{'￥'+ item.value}} </text>
								<text class="status" :class="{amount:item.status==='SUCCESS'}">{{item.statusName}}
								</text>
							</view>
						</view>
					</template>
					<view class="detail-item" v-if='amountData.totalFee &&  parseFloat(amountData.totalFee) !== 0'>
						<text>合计金额</text>
						<text class="amount">￥{{amountData.totalFee}} </text>
					</view>
				</view>
				<!-- 		<view class="payment-total"
					v-if='amountData.actualPayment && parseFloat(amountData.actualPayment) !== 0'>
					<text>待付款</text>
					<text class="amount">￥{{handleAmount(amountData.actualPayment)}}</text>
				</view> -->
				<view class="over-txt">
					<button type="success" class="btn-txt btn" :class='{disabledBtn:!qdOrderVal.h5ReturnQdUrl}'
						:disabled="!qdOrderVal.h5ReturnQdUrl" @click="toNav">用户车辆信息上传完成</button>
					<!-- 					<wx-open-launch-weapp id="launch-btn" appid="wxbd70e25d388d9f46" path="pages/index/index" env-version="trial"
						@error="handleErrorFn" @launch="handleLaunchFn" v-else>
						<div v-is="'script'" type='text/wxtag-template' style="display: block;">
							<div class="btn">跳转小程序</div>
						</div>
					</wx-open-launch-weapp> -->
				</view>
				<!-- <Hetong v-model="checked" :link='linkObj.url' v-if='linkObj.url' :name='linkObj.name' /> -->
				<!-- <button type="success" class="btn-txt btn" @click="submit">确认办理</button> -->
			</view>
			<u-toast ref="uToastRef" />
		</view>
	</view>
</template>
<script setup lang='ts'>
	import {
		unifyTemplate
	} from '@/hooks/unifyTemplate'
	import {
		reactive,
		ref
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import Hetong from '@/components/Hetong/Hetong.vue'
	import {
		request,
		requestNew,
		myJsonp,
		toWeixin
	} from '@/utils/network/request'
	import {
		payType,
		payMentStatus
	} from './common.js'
	import {
		setToken,
		getToken,
		setItem,
		StorageKeys
	} from '@/utils/storage'
	import handleAmount from '@/utils/handleAmount.js';
	import {
		handleToTypes,
		isWeb,
		handleToZhifubao,
		handleTonei,
		isWxDuan
	} from '@/utils/utils';
	const {
		CustomHeader, //头部组件
		initData, //初始化数据
		isShow, //是否展示formBuilderVue组件
		qdOrderVal //qdOrder中数据 ref
	} = unifyTemplate() //初始化数据
	// import {
	// 	request
	// } from '../../static/js/network/request'
	function handleErrorFn(e) {
		console.log('fail', e.detail);
	}

	function handleLaunchFn(e) {
		console.log('success');
	}
	let orderObj = {}
	let formData = reactive < any > ([{
		label: '产品名',
		value: '',
		key: "equityName",
		key1: 'promoteName',
	}, {
		label: '订单步骤',
		value: '',
		key: "orderStepName",
	}, {
		label: '车牌号',
		key: "vehiclePlate",
		value: '贵'
	}, {
		label: '车牌颜色',
		key: "vehiclePlateColorStr",
		value: '贵'
	}, {
		label: '车主姓名',
		key: "customerName",
		value: ''
	}, {
		label: '收费车型',
		key: "vehicleClassStr",
		value: ''
	}, {
		label: '邮寄地址',
		key: "orderInfoExt",
		key1: 'region,address',
		default: "不邮寄",
		isHide: false,
		value: ''
	}])
	const amountList = ref < any > ([])
	const checked = ref(false)
	// 实付款
	const amountData = ref({
		totalFee: '',
		actualPayment: 0
	})
	let config = ref < any > ({
		submitName: '提交',
		titleWidth: 160
	})
	onLoad((opin) => {

		// 初始化数据
		initData(opin, 4).then(async data => {
			console.log(data, 'data');
			orderObj = data.order
			amountData.value.totalFee = handleAmount(data.order.amount)
			await login(data)
			// getLink(data.order.orderNo)
			getOrderInfo(data.order.orderNo)
			delete data.config.tableConfig
			config.value = Object.assign(data.config, config.value)

		})
	})
	const linkObj = reactive({
		url: "",
		name: ""
	})
	// 获取协议链接
	async function getLink(orderId) {
		await requestNew('/iaw/issue/order/agreementInSertOrder', {
			data: {
				orderId
			}
		}).then((res) => {
			if (res.code === 0) {
				let data = res.data.data[0]
				console.log(data, '协议');
				linkObj.url = data.address[0].url
				linkObj.name = data.name
			}
			// contractTesting(qdOrderVal.value.qdOrderNo, jumpPage)
		})
	}
	// 无感登录,如果没有登录调用登录
	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 {
			// 单位办理
			console.log('单位办理');
			data.userType = 'ENTERPRISE'
			data.accountNumber = orderData.order.customerIdNum
		}
		console.log('login请求参数', data);
		await requestNew('/iaw/portal/loginByNoPassword', {
			data,
		}).then((res) => {
			if (res.code === 0) {
				let data = res.data
				// 保存token
				setToken(data.accessToken)
				setItem(StorageKeys.OpenId, data.openId)
				console.log(data, '登录获取的数据')
			}
			// contractTesting(qdOrderVal.value.qdOrderNo, jumpPage)
		})
	}
	const stepOptions = [{
			value: 1,
			label: "完成填写基本信息"
		},
		{
			value: 2,
			label: "完成个人/单位信息上传"
		},
		{
			value: 3,
			label: "已支付，待签约"
		},
		{
			value: 4,
			label: "完成车辆信息上传,待支付"
		},
		{
			value: 5,
			label: "完成签约"
		},
		{
			value: 6,
			label: "待审核"
		},
		{
			value: 7,
			label: "审核不通过"
		},
		{
			value: 8,
			label: "待发货"
		},
		{
			value: 9,
			label: "待收货"
		},
		{
			value: 10,
			label: "待激活"
		},
		{
			value: 11,
			label: "已完成"
		},
		{
			value: 12,
			label: "已申请-换货"
		},
		{
			value: 13,
			label: "已申请-退货"
		},
		{
			value: 14,
			label: "已结束"
		},
		{
			value: 15,
			label: "退款中"
		},
		{
			value: 16,
			label: "退款成功"
		},
		{
			value: 17,
			label: "退货成功"
		},
	]

	function getOrderInfo(orderId) {
		let options = {
			type: 2,
			data: {
				orderId
			},
			method: 'POST',
			showLoading: true
		}
		requestNew('/iaw/issue/order/orderDetailQuery', options).then((res) => {
			if (res.code === 0) {
				let data = res.data.data
				console.log(data, '订单数据'); //data.releaseProduct.isPay
				data.orderStepName = stepOptions.find(item => item.value === data.orderStep)?.label || data
					.orderStep
				formData.forEach(item => {
					let itemData = data[item.key]
					if (typeof itemData === 'object' && itemData) {
						console.log(itemData, item.key1);
						if (item.key1 && item.key1.includes(',')) {
							let str = ''
							item.key1.split(',').forEach(listItem => {
								str += itemData[listItem] || ''
							})
							itemData = str
						} else {
							console.log(itemData, 'item.key1');
							itemData = itemData[item.key1]
						}
					}
					if (item.format) {
						itemData = item.format(itemData)
					}
					if (!itemData && itemData !== 0 && item.isHide === false) {
						item.isHide = true
					}
					item.value = itemData || item.default
				})
				
				amountData.value.actualPayment = 0
				amountList.value = data.feeList?.map(item => {
					if (item.payStatus === 'UNPAY') {
						amountData.value.actualPayment += parseInt(item.fee)
					}
					return {
						status: item.payStatus,
						statusName: data.releaseProduct.isPay == 1 ? '' : `(${payMentStatus[item
							.payStatus]})`,
						label: payType[item.payType],
						value: handleAmount(item.fee)
					}
				}) || []
				console.log(amountList.value, 'amountList.value');
				if (data.releaseProduct.isPay == 1) {
					amountData.value.totalFee = ''
					amountList.value = []
				}
				isShow.value = true;
			}
			console.log(res, '请求订单获取的数据');
		})
	}
	// 数据处理
	// function getOrderInfo(orderId) {
	// 	request('8', {
	// 		data: {
	// 			orderId
	// 		}
	// 	}).then((res) => {
	// 		let data = JSON.parse(res.bizContent)
	// 		console.log(data, '订单数据');
	// 		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)
	// 			}
	// 			if (!itemData && itemData !== 0 && item.isHide === false) {
	// 				item.isHide = true
	// 			}
	// 			item.value = itemData || item.default
	// 		})
	// 		amountData.value.totalFee = handleAmount(data.sumFee)
	// 		amountData.value.actualPayment = 0
	// 		amountList.value = [] || data.datas.map(item => {
	// 			if (item.payStatus === 'UNPAY') {
	// 				amountData.value.actualPayment += parseInt(item.fee)
	// 			}
	// 			return {
	// 				status: item.payStatus,
	// 				statusName: payMentStatus[item.payStatus],
	// 				label: payType[item.payType],
	// 				value: handleAmount(item.fee)
	// 			}
	// 		})
	// 		isShow.value = true;
	// 	})
	// }
	const uToastRef = ref(null)
	//确认办理
	function submit() {
		if (checked.value || !linkObj.url) {
			uni.navigateTo({
				url: '/pages/payment/orderPayment',
				animationType: 'pop-in',
				animationDuration: 500
			})
		} else {
			uToastRef.value.show({
				title: '请先勾选协议',
				type: 'warning',
			})
		}
	}
	const toNav = () => {
		handleFinish()
	}

	const handleOther = (returnUrl) => {
		const type = handleToTypes();
		if (type === 'alipaymini') {
			handleToZhifubao(returnUrl);
		} else if (type === 'wechatmini') {
			let returnUrls = returnUrl.split('?')
			if (returnUrls.length === 1) {
				returnUrls = returnUrl +
					`?orderId=${orderObj.orderNo}&ownerName=${orderObj.ownerName}&productName=${orderObj.productName}&tel=${orderObj.customerTel || orderObj.agentTel}&vehicleId=${orderObj.vehicleId}&qdOrderNo=${orderObj.orderNo}`
			} else {
				returnUrls = returnUrl
			}
			console.log('returnUrls', returnUrls);
			handleTonei(returnUrls);
		}
	};
	const handleFinish = () => {
		console.log(qdOrderVal.value, '获取的qdorder');
		const h5ReturnQdUrl = qdOrderVal.value.h5ReturnQdUrl || '';
		if (!h5ReturnQdUrl) {
			return;
		}
		if (isWeb(h5ReturnQdUrl) || isWxDuan(h5ReturnQdUrl)) {
			window.open(h5ReturnQdUrl, '_self');
		} else {
			handleOther(h5ReturnQdUrl);
		}
	};
</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;
	}

	.status {
		margin: 0;
	}

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

	.over-txt {
		text-align: center;
		font-size: 32rpx;
		padding-top: 30rpx;
	}

	.over-txt .disabledBtn {
		background-color: #ccc !important;
		color: #666;
	}
</style>