<template>
	<view class="p30">
		<!-- <view class="star_pile" style="margin-bottom: 30rpx"></view> -->
		<view class="orderdetail_info" style="margin-bottom: 30rpx">
			<view class="orderdetail_info_title">
				<view>{{ info.stationName }}</view>
			</view>
			<view style="font-size: 26rpx; margin-bottom: 15rpx; display: flex; align-items: center">
				<view style="opacity: 0.7">枪号：{{ info.gunName }}</view>
				<image style="width: 40rpx; height: 40rpx; margin-left: 15rpx" src="/static/icon/copy.png" @click="copy(info.gunName)" mode="widthFix"></image>
			</view>
			<view style="font-size: 26rpx; margin-bottom: 15rpx; opacity: 0.7">停车收费说明：{{ info.occupyCostInfo }}</view>
			<view style="font-size: 26rpx; opacity: 0.7">占用收费说明：{{ info.parkCostInfo }}</view>
		</view>
		<view class="orderdetail_info" style="margin-bottom: 30rpx">
			<view class="orderdetail_info_title">
				<view>费用信息</view>
			</view>
			<view style="max-width: 420rpx">
				<up-tag size="mini" :text="`当前计费时间段:${currentPrice.startTime}-${currentPrice.endTime}`" plain plainFill></up-tag>
			</view>
			<view class="orderdetail_info_fy">
				<view class="orderdetail_info_fy_left">电站价格</view>
				<view class="orderdetail_info_fy_right">
					{{ currentPrice.totalAmount }}
					<text style="font-weight: 500; font-size: 24rpx; color: #333; margin-left: 15rpx">元/度</text>
				</view>
			</view>
		</view>
		<view class="orderdetail_info" style="margin-bottom: 30rpx">
			<view class="orderdetail_info_title">
				<view style="display: flex; align-items: center">
					<view>支付方式</view>
					<!--  -->
					<view style="margin-left: 15rpx">
						<up-tag v-if="store.state.insertStatus == 1" size="mini" text="已插枪" plain plainFill></up-tag>
					</view>
				</view>
				<view style="display: flex; align-items: center">
					<up-button type="primary" size="small" :plain="true" text="余额充值" @click="navTo('/pages/money/recharge')"></up-button>
				</view>
			</view>
			<view style="font-size: 30rpx; margin-bottom: 30rpx">
				<!-- @click="payTo" -->
				<!-- <view>支付方式</view> -->
				<!-- <view>{{ payType == 1 ? '余额付款' : payType == 2 ? '电卡支付' : payType == 3 ? '预付款' : '请选择' }}</view> -->

				<view>
					<view
						class="flex-acsb"
						style="padding: 15rpx 30rpx; border-radius: 10rpx"
						v-for="(item, index) in payList"
						:key="index"
						:style="{
							border: item.id == payType ? '1rpx solid #4879e6' : ''
						}"
						@click="payType = item.id"
					>
						<view style="display: flex; align-items: center">
							<image :src="`/static/icon/lie${item.id}.png`" style="width: 50rpx; height: 50rpx; margin-right: 25rpx"></image>
							{{ item.name }}
						</view>
						<view v-if="item.id == 1" style="font-size: 28rpx; opacity: 0.7">可用余额：{{ infoUser.balance || 0 }}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="orderdetail_info" style="margin-bottom: 30rpx">
			<view class="orderdetail_info_yf">
				<view class="orderdetail_info_yf_left">
					<view class="orderdetail_info_yf_left_tit">
						<view style="margin-right: 30rpx">预付费</view>
						<up-tag size="mini" :text="`余额原路退款`" plain plainFill></up-tag>
					</view>
					<!-- <view>{{ dataForm.money }} 元</view> -->
					<view class="orderdetail_info_yf_left_mon">
						<!-- 预付金额： -->
						<view
							@click="
								dataForm.money = 30;
								inputBorder = false;
							"
							:style="{ border: `1rpx solid ${dataForm.money == 30 && !inputBorder ? '#4879e6' : '#c5c5c5'}` }"
						>
							30
						</view>
						<view
							@click="
								dataForm.money = 50;
								inputBorder = false;
							"
							:style="{ border: `1rpx solid ${dataForm.money == 50 && !inputBorder ? '#4879e6' : '#c5c5c5'}` }"
						>
							50
						</view>
						<view
							@click="
								dataForm.money = 100;
								inputBorder = false;
							"
							:style="{ border: `1rpx solid ${dataForm.money == 100 && !inputBorder ? '#4879e6' : '#c5c5c5'}` }"
						>
							100
						</view>
						<view @click="inputClik" :style="{ border: `1rpx solid ${inputBorder ? '#4879e6' : '#c5c5c5'}` }">
							<input adjust-position v-if="inputBorder" focus type="number" v-model="dataForm.money" placeholder="自定义" />
							<text v-else>自定义</text>
						</view>
					</view>
				</view>
				<!-- <view class="orderdetail_info_yf_right" @click="openDialog">预付金额</view> -->
			</view>
		</view>

		<view class="orderdetail_info" style="margin-bottom: 30rpx" v-if="payType == 2">
			<view>
				<view class="flex-acsb" style="font-size: 30rpx; margin-bottom: 20rpx">
					<view>当前可用电卡</view>
				</view>
				<view @click="userCardId = item.id" style="margin-bottom: 30rpx; position: relative" class="mt30 wallet_list" v-for="(item, index) in userCard" :key="index">
					<view v-if="userCardId == item.id" style="position: absolute; top: 0; left: 0; background-color: #e45656; border-radius: 0 0 20rpx 0">
						<up-icon name="checkbox-mark" color="#fff"></up-icon>
					</view>

					<view style="color: #fff">
						<view style="font-weight: bold; font-size: 30rpx; margin-bottom: 18rpx">
							{{ item.name }}
						</view>
						<view style="font-size: 28rpx; color: #eee">卡号：{{ item.cardNo }}</view>
					</view>
					<view style="display: flex; flex-direction: column; align-items: center; color: #fff; font-weight: bold; font-size: 26rpx">
						<view style="font-size: 36rpx; margin-bottom: 10rpx">{{ item.balance }}</view>
						<view style="font-weight: 500">余额</view>
					</view>
				</view>
			</view>
		</view>

		<view style="height: 500rpx"></view>
		<view class="orderdetail_btn p30" style="background-color: #fff">
			<view class="orderdetail_btn_left">
				{{ currentPrice.totalAmount }}
				<text>元/度 免费停车</text>
			</view>

			<view>
				<up-button v-if="!payType" :customStyle="{ height: '80rpx', width: '230rpx' }" disabled color="#4879e6" text="请选择支付方式" shape="circle"></up-button>
				<up-button v-if="payType == 1" :customStyle="{ height: '80rpx', width: '280rpx' }" @click="toRecharge" color="#4879e6" shape="circle" text="启动充电"></up-button>
				<up-button
					v-if="payType == 3"
					:customStyle="{ height: '80rpx', width: '280rpx' }"
					@click="toRechargeYuFu"
					color="#4879e6"
					shape="circle"
					:text="`预付${dataForm.money}元，启动充电`"
				></up-button>
				<!-- :text="`预付${dataForm.money}元，启动充电`" -->
				<up-button
					v-if="payType == 2"
					:customStyle="{ height: '80rpx', width: '280rpx' }"
					:disabled="!userCardId"
					color="#4879e6"
					:text="userCardId ? '启动充电' : '请选择电卡'"
					shape="circle"
					@click="toRechargeCard"
				></up-button>
			</view>

			<!-- <view v-if="!payType" class="orderdetail_btn_right" style="opacity: 0.5;">请选择支付方式</view> -->
			<!-- <view v-if="payType == 1" class="orderdetail_btn_right" @click="toRecharge">预付{{ dataForm.money }}元，启动充电</view> -->
			<!-- <view v-if="payType == 2" class="orderdetail_btn_right" @click="toRecharge">电卡支付，启动充电</view> -->
		</view>

		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog
				ref="inputClose"
				mode="input"
				title="请输入预付金额"
				:value="dataForm.money"
				placeholder="请输入内容"
				@confirm="dialogInputConfirm"
			></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { gunInfo, infoAroundApi, startChargingByWallet, userCardUsableList, startChargingByCard, ordersInfo, startChargingByAdaPay, userInfo } from '@/api/api.js';
import { onLoad, onShow } from '@dcloudio/uni-app';
import store from '@/store/index.js';
import { copy } from '@/utils/fun.js';

import { useNav } from '@/hooks/useNav.js';
const { navTo } = useNav();

const inputDialog = ref(null);
let info = reactive({});
let infoUser = reactive({});

let inputBorder = ref(false);
let currentPrice = ref({});
let id = ref('');
let userCard = ref([]);
let userCardId = ref(null);
let payType = ref(1);
let dataForm = reactive({
	money: 30
});

let payList = reactive([
	{
		id: 1,
		name: '余额支付'
	}
]);

onLoad((options) => {
	if (options.q) {
		let search = decodeURIComponent(options.q);
		search = search.split('?')[1];
		const pairs = search ? search.split('&') : [];
		const query = {};
		for (let i = 0; i < pairs.length; ++i) {
			const [key, value] = pairs[i].split('=');
			query[key] = query[key] || decodeURIComponent(value);
		}
		if (query.num) {
			id.value = query.num;
			infoDate(query.num);
		}
	}

	if (options.id) {
		id.value = options.id;
		infoDate(options.id);
	}
});

onShow(async () => {
	if (uni.getStorageSync('token') && id.value) {
		infoDate(id.value);
		let _res = await userInfo();
		infoUser.value = _res;
	}
});

let getUserCard = async (e) => {
	let _res = await userCardUsableList({ stationId: e });
	userCard.value = _res;
	if (_res.length == 0) {
		payType.value = 1;
	} else {
		payType.value = 2;
		userCardId.value = _res[0].id;
		if (!payList.find((val) => val.name == '电卡支付')) {
			payList.push({
				id: 2,
				name: '电卡支付'
			});
		}
	}
};

let inputClik = () => {
	inputBorder.value = true;
	dataForm.money = dataForm.money == 30 || dataForm.money == 50 || dataForm.money == 100 ? '' : dataForm.money;
};

let infoDate = async (e) => {
	let _res = await gunInfo({ deviceNo: e });
	info = _res;
	getUserCard(_res.stationId);
	currentPrice.value = _res.currentPrice;
	console.log(_res.deviceNo, '_res.deviceNo');
	console.log(_res.gunNo, '_res.gunNo');

	store.commit('setInsertStatus', _res.insertStatus);
	uni.sendSocketMessage({
		data: JSON.stringify({
			command: 'sub',
			deviceNo: _res.deviceNo,
			gunNo: _res.gunNo
		}),
		success: (res) => {
			console.log('发送成功');
		},
		fail: (err) => {
			console.log(err);
			console.log('发送失败');
		}
	});
};

let dialogInputConfirm = (e) => {
	dataForm.money = e;
};

let openDialog = () => {
	console.log(12345);
	inputDialog.value.open();
};

let toRechargeCard = async () => {
	uni.showLoading({
		title: '启动充电中...',
		mask: true
	});
	let _res = await startChargingByCard({
		deviceNo: info.deviceNo,
		gunNo: info.gunNo,
		amount: dataForm.money,
		userCardId: userCardId.value
	});
};

let toRechargeYuFu = async () => {
	uni.showLoading({
		title: '启动充电中...',
		mask: true
	});
	let _res = await startChargingByAdaPay({
		deviceNo: info.deviceNo,
		gunNo: info.gunNo,
		amount: dataForm.money
	});
	let data = _res.payInfo;
	uni.requestPayment({
		provider: 'wxpay',
		timeStamp: data.timeStamp,
		nonceStr: data.nonceStr,
		package: data.package,
		signType: data.signType,
		paySign: data.paySign,
		success: function (r) {
			store.commit('setTransactionNo', _res.transactionNo);
			store.commit('setSokStatus', 0);
			timeMap(_res);
		},
		fail: function (err) {
			uni.showToast({
				title: '已取消支付',
				icon: 'none'
			});
			console.log('fail:' + JSON.stringify(err));
		}
	});
	// store.commit('setTransactionNo', _res.transactionNo);
	// store.commit('setSokStatus', 0);
	// timeMap(_res);
	// uni.navigateTo({
	// 	url: `/pageOrder/recharge/recharge?transactionNo=${_res.transactionNo}&type=order`
	// });
};

let toRecharge = async () => {
	uni.showLoading({
		title: '启动充电中...',
		mask: true
	});
	let _res = await startChargingByWallet({
		deviceNo: info.deviceNo,
		gunNo: info.gunNo,
		amount: dataForm.money
	});
	store.commit('setTransactionNo', _res.transactionNo);
	store.commit('setSokStatus', 0);
	timeMap(_res);

	// uni.navigateTo({
	// 	url: `/pageOrder/recharge/recharge?transactionNo=${_res.transactionNo}&type=order`
	// });
	// uni.navigateTo({
	// 	url: `/pageOrder/recharge/recharge?transactionNo=${_res.transactionNo}`
	// });
	// console.log(_res);
};

const timeMap = (_res) => {
	var time = setInterval(async () => {
		if (store.state.sokStatus != 1) {
			let _data = await ordersInfo({
				transactionNo: _res.transactionNo
			});
			store.commit('setDataObj', _data);
			if (_data.status == 3) {
				uni.hideLoading();
				uni.navigateTo({
					url: `/pageOrder/recharge/recharge?transactionNo=${_res.transactionNo}&type=order`
				});
				clearTimeout(time);
				store.commit('setSokStatus', 0);
			}
			if (_data.status == -1) {
				uni.hideLoading();
				uni.showModal({
					title: '提示',
					content: '启动失败，请重试',
					showCancel: false,
					confirmText: '确认',
					success: () => {}
				});
				clearTimeout(time);
				store.commit('setSokStatus', 0);
			}
			if (_data.status == -2) {
				uni.hideLoading();
				uni.showModal({
					title: '提示',
					content: '启动超时，请重试',
					showCancel: false,
					confirmText: '确认',
					success: () => {}
				});
				clearTimeout(time);
				store.commit('setSokStatus', 0);
			}
		}
	}, 5000);
};

const payTo = () => {
	let itemList = ['余额付款'];
	if (userCard.value.length != 0) {
		itemList.push('电卡支付');
	}
	// itemList.push('预付款');
	uni.showActionSheet({
		itemList: itemList,
		success: function (res) {
			// if (itemList[1] == '预付款' && res.tapIndex == 1) {
			// 	payType.value = 3;
			// } else {
			// 	payType.value = res.tapIndex + 1;
			// }

			payType.value = res.tapIndex + 1;
		},
		fail: function (res) {
			console.log(res.errMsg);
		}
	});
};
</script>

<style lang="scss">
.star_pile {
	width: 100%;
	box-shadow: 0rpx -6rpx 8rpx 2rpx rgba(66, 115, 229, 0.05);
	border-radius: 16rpx 16rpx 16rpx 16rpx;
	padding: 20rpx;
	background-color: #fff;
}

.orderdetail_info {
	background: #ffffff;
	border-radius: 16rpx 16rpx 16rpx 16rpx;
	padding: 25rpx;
	box-shadow: 0rpx -6rpx 8rpx 2rpx rgba(66, 115, 229, 0.05);
	&_title {
		font-size: 32rpx;
		color: #232323;
		margin-bottom: 30rpx;
		@include flex($space: space-between);
	}

	&_fy {
		background: linear-gradient(to right, rgba(72, 121, 230, 0.4), rgba(72, 121, 230, 0));
		border-radius: 15rpx;
		padding: 40rpx 20rpx 40rpx 40rpx;
		color: #fff;
		margin-top: 30rpx;
		@include flex;
		&_left {
			font-size: 32rpx;
			font-weight: 800;
			font-style: italic;
			color: #4879e6;
		}
		&_right {
			font-size: 36rpx;
			font-weight: 800;
			color: #4879e6;
			margin-left: 30rpx;
			@include flex;
		}
	}

	&_yf {
		@include flex($space: space-between);
		&_left {
			flex: 1;
			// view {
			// 	@include flex;
			// }

			&_tit {
				font-size: 28rpx;
				color: rgba(51, 51, 51, 0.8);
				margin-bottom: 20rpx;
				@include flex;
			}
			&_mon {
				font-size: 30rpx;
				@include flex($space: space-between);
				view {
					// width: 22%;
					padding: 15rpx 35rpx;
					border: 1rpx solid #c5c5c5;
					margin-right: 15rpx;
					border-radius: 10rpx;
				}
				input {
					width: 100rpx;
				}
			}
		}
		&_right {
			padding: 15rpx 30rpx;
			color: #1779ff;
			border: 1rpx solid #1779ff;
			border-radius: 50rpx;
		}
	}
}

.orderdetail_btn {
	width: 100%;
	position: fixed;
	left: 0;
	bottom: 0rpx;
	padding: 30rpx;
	@include flex($space: space-between);
	&_left {
		// background-color: #e5eaf4;
		color: #333;
		font-size: 38rpx;
		font-weight: bold;
		text {
			font-size: 26rpx;
			font-weight: 500;
		}
	}
	&_right {
		background: #1779ff;
		color: #fff;
		font-weight: bold;
		font-size: 32rpx;
		padding: 0 40rpx;
	}
}

.wallet_list {
	border-radius: 15rpx;
	background-color: #4879e6;
	padding: 20rpx 50rpx 20rpx 30rpx;
	display: flex;
	align-items: flex-end;
	justify-content: space-between;
}
</style>
