<template>
	<view class="order-record-page">
		<!-- 自定义导航栏 -->
		<view class="navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="nav-content">
				<view class="nav-left" @click="goBack">
					<uni-icons type="left" size="24" color="#333"></uni-icons>
				</view>
				<view class="nav-title">订单记录</view>
				<view class="nav-right"></view>
			</view>
		</view>

		<!-- 页面内容 -->
		<view class="page-content" :style="{ paddingTop: navBarHeight + 'px' }">
			<!-- 标签导航 -->
			<view class="tab-nav">
				<view class="tab-item" :class="{ active: activeTab === 'paid' }" @click="switchTab('paid')">
					<text class="tab-text">已支付</text>
				</view>
				<view class="tab-divider"></view>
				<view class="tab-item" :class="{ active: activeTab === 'unpaid' }" @click="switchTab('unpaid')">
					<text class="tab-text">未支付</text>
				</view>
			</view>

			<!-- 订单列表 -->
			<view class="order-list">
				<view v-if="currentOrderList.length > 0">
					<view class="order-item" v-for="(order, index) in currentOrderList" :key="order.id">
					<!-- 订单号 -->
					<view class="order-header">
						<text class="order-number">订单号: {{ order.orderNumber }}</text>
						<!-- <text class="status-pill" :class="order.status">{{ order.status === 'paid' ? '已支付' : '未支付' }}</text> -->
						<button class="copy-btn" @click="copyOrderNumber(order.orderNumber)">
							<uni-icons type="copy" size="18" color="#666"></uni-icons>
							<text class="btn-text">复制</text>
						</button>
					</view>

					<!-- 课程名称 -->
					<view class="course-name">
						<text class="course-title">课程名称: {{ order.courseName }}</text>
					</view>

					<!-- 下单时间 -->
					<view class="order-time">
						<text class="time-text">下单时间: {{ order.orderTime }}</text>
					</view>

					<!-- 课程金额 -->
					<view class="course-amount">
						<text class="amount-text">课程金额: ¥{{ order.courseAmount }}</text>
					</view>

					<!-- 支付方式信息 -->
					<view class="payment-info" v-if="order.balancePayment">
						<text class="payment-text">余额支付: -¥{{ order.balancePayment }}</text>
					</view>
					<view class="payment-info" v-if="order.pointsPayment">
						<text class="payment-text">积分支付: -{{ order.pointsPayment }}积分 </text>
					</view>

					<!-- 实付金额 -->
					<view class="actual-payment">
						<text class="actual-text">实付金额: ¥{{ order.actualPayment }}</text>
					</view>

					<!-- 剩余时间（仅未支付订单显示） -->
					<view class="remaining-time" v-if="order.expire_time && activeTab === 'unpaid'">
						<text class="time-text">剩余时间: {{ countdownDisplay[order.id] || formatCountdown(order.expire_time) }}</text>
					</view>

					<!-- 操作按钮 -->
					<view class="action-buttons">
						<button class="action-btn secondary" @click="handleSecondaryAction(order)">
							<uni-icons type="eye" size="18" color="#555"></uni-icons>
							<text>{{ getSecondaryButtonText(order.status) }}</text>
						</button>
						<button class="action-btn primary" @click="handlePrimaryAction(order)">
							<uni-icons type="arrowright" size="18" color="#fff"></uni-icons>
							<text>{{ getPrimaryButtonText(order.status) }}</text>
						</button>
					</view>
					</view>
				</view>
				<view class="empty" v-else>
					<uni-icons type="cart" size="56" color="#E0E0E0"></uni-icons>
					<text class="empty-text">暂无订单</text>
				</view>
			</view>
		</view>
		
		<!-- 悬浮发票按钮 -->
	<view class="floating-invoice-btn" @click="goToInvoice">
		<view class="btn-content">
			<!-- <view class="icon-wrapper">
				<uni-icons type="receipt" size="20" color="#fff"></uni-icons>
			</view> -->
			<text class="btn-text">开具发票</text>
		</view>
		<view class="btn-shadow"></view>
	</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import course_api from "@/api/course_api.js"
import { requestPayment } from "@/utils/payment.js"

// 响应式数据
const statusBarHeight = ref(0)
const navBarHeight = ref(88)
const activeTab = ref('paid') // 默认激活"已支付"标签
// 订单数据
const orderList = ref([])
// 倒计时定时器
const countdownTimer = ref(null)
// 倒计时显示数据
const countdownDisplay = ref({})

// 计算属性
const currentOrderList = computed(() => {
	return orderList.value[activeTab.value] || []
})

// 方法
const getSystemInfo = () => {
	const systemInfo = uni.getSystemInfoSync()
	statusBarHeight.value = systemInfo.statusBarHeight
	// #ifdef MP-WEIXIN
	navBarHeight.value = systemInfo.statusBarHeight + 44
	// #endif
	// #ifdef APP-PLUS
	navBarHeight.value = systemInfo.statusBarHeight + 44
	// #endif
}

const goBack = () => {
	uni.navigateBack()
}

// 倒计时计算函数
const formatCountdown = (timestamp) => {
	if (!timestamp) return ''
	
	const now = Math.floor(Date.now() / 1000) // 当前时间戳（秒）
	const expireTime = parseInt(timestamp) // 过期时间戳（秒）
	const remainingSeconds = expireTime - now
	
	if (remainingSeconds <= 0) {
		return '已过期'
	}
	
	const days = Math.floor(remainingSeconds / 86400)
	const hours = Math.floor((remainingSeconds % 86400) / 3600)
	const minutes = Math.floor((remainingSeconds % 3600) / 60)
	const seconds = remainingSeconds % 60
	
	if (days > 0) {
		return `${days}天${hours.toString().padStart(2, '0')}小时${minutes.toString().padStart(2, '0')}分钟`
	} else if (hours > 0) {
		return `${hours}小时${minutes.toString().padStart(2, '0')}分钟${seconds.toString().padStart(2, '0')}秒`
	} else if (minutes > 0) {
		return `${minutes}分钟${seconds.toString().padStart(2, '0')}秒`
	} else {
		return `${seconds}秒`
	}
}

// 更新所有订单的倒计时显示
const updateCountdownDisplay = () => {
	const currentList = orderList.value[activeTab.value] || []
	currentList.forEach(order => {
		if (order.expire_time) {
			countdownDisplay.value[order.id] = formatCountdown(order.expire_time)
		}
	})
}

// 启动倒计时定时器
const startCountdown = () => {
	if (countdownTimer.value) {
		clearInterval(countdownTimer.value)
	}
	
	// 立即更新一次倒计时显示
	updateCountdownDisplay()
	
	countdownTimer.value = setInterval(() => {
		updateCountdownDisplay()
	}, 1000)
}

// 停止倒计时定时器
const stopCountdown = () => {
	if (countdownTimer.value) {
		clearInterval(countdownTimer.value)
		countdownTimer.value = null
	}
}

const switchTab = (tab) => {
	// 停止当前倒计时
	stopCountdown()
	
	activeTab.value = tab
	console.log('切换到标签:', tab)
    getOrderList()
}

const copyOrderNumber = (orderNumber) => {
	// 复制订单号到剪贴板
	uni.setClipboardData({
		data: orderNumber,
		success: () => {
			uni.showToast({
				title: '订单号已复制',
				icon: 'none'
			})
		}
	})
}

const getSecondaryButtonText = (status) => {
	switch (status) {
		case 'created':
			return '取消订单'
		case 'overtime':
			return '支付超时'
		case 'failed':
			return '支付失败'
		case 'canceled':
			return '已取消'
		default:
			return '查看订单'
	}
}

const getPrimaryButtonText = (status) => {
	switch (status) {
		case 'canceled':
			return '已取消'
		case 'overtime':
		case 'failed':
			return '查看课程'
		case 'created':
			return '继续支付'
		default:
			return '进入学习'
	}
}

const handleSecondaryAction = (order) => {
	switch (order.status) {
		case 'created':
			cancelOrder(order)
			break
		case 'timeout':
		case 'failed':
			viewOrder(order)
			break
		default:
			viewOrder(order)
	}
}

const handlePrimaryAction = (order) => {
	switch (order.status) {
		case 'created':
			continuePayment(order)
			break
		case 'timeout':
		case 'failed':
			viewCourse(order)
			break
		default:
			enterLearning(order)
	}
}

const cancelOrder = (order) => {
	uni.showModal({
		title: '确认取消',
		content: '确定要取消这个订单吗？',
		success: (res) => {
			if (res.confirm) {
				// 调用取消订单接口
				cancelExcellencourseOrder(order)
			}
		}
	})
}

const continuePayment = (order) => {
	console.log('继续支付订单:', order.id)
	// 调用继续支付接口
	payExcellencourseOrderContinue(order)
}

const viewCourse = (order) => {
	console.log('查看课程:', order.id)
	uni.navigateTo({
		url: '/pages_course/course_detail/course_detail'
	})
}

const enterLearning = (order) => {
	console.log('进入学习:', order.id)
	uni.navigateTo({
		url: '/pages_course/course_detail/course_detail'
	})
}

// 跳转到开具发票页面
const goToInvoice = () => {
	uni.navigateTo({
		url: '/pages_course/invoice/invoice'
	})
}

const viewOrder = (order) => {
	console.log('查看订单详情:', order.id)
	uni.showToast({
		title: '订单详情功能',
		icon: 'none'
	})
}

const getOrderList = () => {
	course_api.listExcellencourseOrder(activeTab.value, 1).then(res => {
		console.log('订单列表:', res)
		if (res.code === 200) {
			const data = res.data || {}
			const list = data.list || []

			const toYuan = (v) => (Number(v || 0) / 100).toFixed(2)
			const formatTs = (sec) => sec ? new Date(sec * 1000).toLocaleString('zh-CN') : ''
			const includesBalance = (t) => [1,3,5,7].includes(Number(t))
			const includesPoints = (t) => [2,3,6,7].includes(Number(t))

			const mapped = list.map(item => {
				let balanceCents = 0
				let points = 0
				;(item.childOrder || []).forEach(child => {
					const t = Number(child.order_pay_type)
					if (includesBalance(t)) balanceCents += Number(child.account || 0)
					if (includesPoints(t)) points += Number(child.bonuspoints || 0)
				})

				return {
					id: item.id,
					orderNumber: item.uuid || '-',
					courseName: item.excellencourse_title || '-',
					orderTime: formatTs(item.create_date),
					courseAmount: toYuan(item.account),
					balancePayment: balanceCents > 0 ? toYuan(balanceCents) : null,
					pointsPayment: points > 0 ? points : null,
					actualPayment: toYuan(item.pay_account),
					status: item.order_status,
					expire_time: item.expire_time // 保持原始时间戳格式
				}
			})

			orderList.value[activeTab.value] = mapped
			
			// 清空倒计时显示数据
			countdownDisplay.value = {}
			
			// 如果有未支付订单，启动倒计时
			if (activeTab.value === 'unpaid' && mapped.length > 0) {
				startCountdown()
			}
		} else {
			uni.showToast({ title: res.msg || '获取订单失败', icon: 'none' })
		}
	}).catch(() => {
		uni.showToast({ title: '获取订单失败', icon: 'none' })
	})
}

const payExcellencourseOrderContinue = (order) => {
	// 显示加载提示
	uni.showLoading({ title: '处理中...' })
	
	let openid = ""
	
	if (process.env.UNI_PLATFORM == "h5") {
		if (process.env.NODE_ENV === 'development') {
			openid = uni.getStorageSync('DEV_APPID');
		} else {
			openid = uni.getStorageSync('AUTH_APPID');
		}
	} else if(process.env.UNI_PLATFORM == "mp-weixin") {
		const {
			envVersion
		} = uni.getAccountInfoSync().miniProgram;
		if (envVersion == "release") {
			openid = uni.getStorageSync('DEV_APPID');
		} else {
			openid = uni.getStorageSync('AUTH_APPID');
		}
	}else{
		//app
	}
	
	course_api.payExcellencourseOrderContinue(order.id, openid).then(res => {
		console.log('继续支付订单:', res)
		uni.hideLoading()
		
		if (res.code == 200) {
			const payParams = res.data.order
			
			console.log(payParams)
			requestPayment(
			  payParams,
			  // 支付成功
			  (res) => {
				uni.showToast({ title: '支付成功', icon: 'none' })
				// 可以跳转到支付成功页，或者查询订单状态
				getOrderList()
			  },
			  // 支付失败
			  (err) => {
				console.error('支付失败', err)
				uni.showToast({ title: '支付失败或取消', icon: 'none' })
			  }
			)
		} else {
			uni.showToast({ 
				title: res.msg || '继续支付失败', 
				icon: 'none',
				duration: 3000
			})
		}
	}).catch(err => {
		uni.hideLoading()
		console.error('继续支付订单失败:', err)
		uni.showToast({ 
			title: '网络错误，请重试', 
			icon: 'none',
			duration: 3000
		})
	})
}

const cancelExcellencourseOrder = (order) => {
	// 显示加载提示
	uni.showLoading({ title: '取消中...' })
	
	course_api.cancelExcellencourseOrder(order.id).then(res => {
		console.log('取消订单:', res)
		uni.hideLoading()
		
		if (res.code == 200) {
			uni.showToast({ 
				title: '订单已取消', 
				icon: 'none',
				duration: 2000
			})
			// 成功后刷新订单列表
			setTimeout(() => {
				getOrderList()
			}, 1500)
		} else {
			uni.showToast({ 
				title: res.msg || '取消订单失败', 
				icon: 'none',
				duration: 3000
			})
		}
	}).catch(err => {
		uni.hideLoading()
		console.error('取消订单失败:', err)
		uni.showToast({ 
			title: '网络错误，请重试', 
			icon: 'none',
			duration: 3000
		})
	})
}

// 生命周期
onMounted(() => {
	getSystemInfo()
	getOrderList()
})

onUnmounted(() => {
	stopCountdown()
})
</script>

<style lang="scss">
.order-record-page {
	min-height: 100vh;
	background-color: #f5f5f5;
}

// 导航栏
.navbar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	background-color: #fff;
	border-bottom: 1rpx solid #e5e5e5;
	
	.nav-content {
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
		
		.nav-left, .nav-right {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.nav-title {
			font-size: 36rpx;
			font-weight: 600;
			color: #333;
		}
	}
}

.page-content {
	background-color: #f5f5f5;
}

// 标签导航
.tab-nav {
	background-color: #fff;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 24rpx 0;
	position: relative;
	
	.tab-item {
		padding: 16rpx 32rpx;
		position: relative;
		
		.tab-text {
			font-size: 28rpx;
			color: #999;
			transition: color 0.3s;
		}
		
		&.active {
			.tab-text {
				color: #333;
				font-weight: 600;
			}
		}
	}
	
	.tab-divider {
		width: 2rpx;
		height: 32rpx;
		background-color: #e0e0e0;
		margin: 0 16rpx;
	}
}

// 订单列表
.order-list {
	padding: 24rpx;
}

.empty {
	padding: 120rpx 0;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 16rpx;

	.empty-text {
		font-size: 26rpx;
		color: #999;
	}
}

.order-item {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 24rpx;
	box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
	
	// 订单号
	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
		
		.order-number {
			font-size: 26rpx;
			color: #333;
			font-weight: 500;
		}
		
		.copy-btn {
			background: transparent;
			color: #666;
			border: none;
			padding: 8rpx 12rpx;
			border-radius: 6rpx;
			font-size: 24rpx;
			line-height: 1;
			transition: opacity 0.15s ease;
			
			&:active { opacity: 0.6; }
		}
	}
	
	// 课程名称
	.course-name {
		margin-bottom: 16rpx;
		
		.course-title {
			font-size: 26rpx;
			color: #333;
			line-height: 1.4;
		}
	}
	
	// 下单时间
	.order-time {
		margin-bottom: 16rpx;
		
		.time-text {
			font-size: 24rpx;
			color: #666;
		}
	}
	
	// 课程金额
	.course-amount {
		margin-bottom: 16rpx;
		
		.amount-text {
			font-size: 24rpx;
			color: #666;
		}
	}
	
	// 支付方式信息
	.payment-info {
		margin-bottom: 16rpx;
		
		.payment-text {
			font-size: 24rpx;
			color: #666;
		}
	}
	
	// 实付金额
	.actual-payment {
		margin-bottom: 16rpx;
		
		.actual-text {
			font-size: 26rpx;
			color: #FF4757;
			font-weight: 600;
		}
	}
	
	// 剩余时间
	.remaining-time {
		margin-bottom: 16rpx;
		
		.time-text {
			font-size: 24rpx;
			color: #FF6B35;
			font-weight: 500;
		}
	}
	
	// 操作按钮
	.action-buttons {
		display: flex;
		justify-content: flex-end;
		gap: 16rpx;
		margin-top: 24rpx;
		
		.action-btn {
			min-height: 64rpx;
			padding: 0 28rpx;
			border-radius: 12rpx;
			font-size: 26rpx;
			border: 1rpx solid transparent;
			line-height: 64rpx;
			transition: transform 0.08s ease, box-shadow 0.2s ease;
			
			&:active { transform: scale(0.98); }
			
			&.secondary {
				background-color: #fff;
				color: #555;
				border-color: #e6e6e6;
				box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
			}
			
			&.primary {
				background-color: #FF4757;
				color: #fff;
				border-color: #FF4757;
				box-shadow: 0 6rpx 14rpx rgba(255, 71, 87, 0.18);
			}
		}
	}
}

// 悬浮发票按钮
.floating-invoice-btn {
	position: fixed;
	right: 40rpx;
	bottom: 140rpx;
	width: 140rpx;
	height: 140rpx;
	z-index: 999;
	cursor: pointer;
	
	.btn-content {
		width: 100%;
		height: 100%;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 50%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		position: relative;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		border: 3rpx solid rgba(255, 255, 255, 0.2);
		
		&:active {
			transform: scale(0.92);
			background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
		}
		
		.icon-wrapper {
			width: 48rpx;
			height: 48rpx;
			background: rgba(255, 255, 255, 0.15);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 8rpx;
			backdrop-filter: blur(10rpx);
		}
		
		.btn-text {
			color: #ffffff;
			font-size: 24rpx;
			font-weight: 600;
			text-align: center;
			line-height: 1.2;
			text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
			letter-spacing: 1rpx;
		}
	}
	
	.btn-shadow {
		position: absolute;
		top: 8rpx;
		left: 8rpx;
		right: -8rpx;
		bottom: -8rpx;
		background: linear-gradient(135deg, rgba(102, 126, 234, 0.3), rgba(118, 75, 162, 0.3));
		border-radius: 50%;
		z-index: -1;
		filter: blur(8rpx);
		opacity: 0.8;
		transition: all 0.3s ease;
	}
	
	&:hover .btn-shadow {
		opacity: 1;
		transform: scale(1.05);
	}
}
</style>
