<template>
	<view class="order-page">

		<HeaderCom></HeaderCom>
		<view class="tab">
			<view class="tab-item" :class="{'active':tabIndex === index}" v-for="(item,index) in tabList" :key="index"
				@click="tabCk(index)">
				<!-- <image src="@/static/mine/tab_bottom.png" mode="" class="tab-img" v-if="tabIndex === index"></image> -->
				{{item.label}}
				<view class="active-heng" v-if="tabIndex === index"></view>
				<view class="heng" v-else></view>
			</view>
		</view>

		<scroll-view class="scroll-list-view" scroll-y="true" scroll-with-animation @scrolltolower="scrolltolower">
			<view v-if="list.length === 0" style="padding-top: 200rpx;">
				<empty></empty>
			</view>
			<view class="list" v-for="(item,index) in list" :key="index" @click.stop="goDetail(item)">
				<view class="list-header">
					<view class="header-left">
						{{item.no}}
					</view>
					<view class="header-right">{{statusObj[item.status]}}({{item.type === 'MALL' ? '商城' : '盲盒'}})</view>
				</view>
				<view class="list-detail">
					<view class="shop-img">
						<image :src="item.productCoverResource.url" mode="aspectFit" class="detail-img"></image>
					</view>
					<view class="detail">
						<view class="name">{{item.productName}}</view>
						<view class="price-name">
							<!-- <view class="old-price"><text>¥</text>{{item.amount}}</view> -->
							<view class="old-price">
								<template v-if="item.type === 'MALL'">
									{{item.points}}积分
								</template>

							</view>
							<view class="num">x {{item.quantity}}</view>
						</view>
					</view>
				</view>
				<!-- <view class="price">
							
							<view class="new-price" v-if="item.method === 'ALIPAY' || item.method === 'WECHAT'">
								<view class="new-sym">实付金额</view>
								<view class="new-value">¥{{item.totalAmount}}</view>
							</view>
							<view class="new-price" v-if="item.method === 'POINTS'">
								<view class="new-sym">实付积分</view>
								<view class="new-value">{{item.points}}</view>
							</view>
							<view class="new-price" v-if="item.method === 'NONE'">
								<view class="new-sym">无需支付</view>
							</view>
						</view> -->
				<view class="list-footer"
					v-if="item.status === 'WAITING_FOR_RECEIPT' || item.status === 'RECEIVED' || item.status === 'COMPLETED' || item.status === 'SHIPPED' || item.status === 'WAITING_FOR_SHIPMENT'">
					<!-- <view class="btn del" v-if="item.status === 'COMPLETED'">删除订单</view> -->
					<view class="btn "
						v-if="item.status === 'WAITING_FOR_RECEIPT' || item.status === 'RECEIVED' || item.status === 'SHIPPED'"
						@click.stop="orderReceipt(item)">确认收货</view>
					<view class="btn "
						v-if="item.status === 'WAITING_FOR_SHIPMENT' && item.expireTime > new Date().getTime()"
						@click.stop="orderRefund(item)">取消订单</view>

					<view class="btn" v-if="item.status === 'COMPLETED'" @click.stop="againProduct(item)">再次购买</view>
					<view class="btn"
						v-if="item.status === 'WAITING_FOR_RECEIPT' || item.status === 'SHIPPED' || item.status === 'RECEIVED'"
						@click.stop="lookLogistics(item)">物流信息</view>
				</view>
			</view>
			<view class="no-data" v-if="total == list.length && list.length > 0">没有更多了～</view>
		</scroll-view>


		<popup-view v-model="openShow" mode="bottom" border-radius="15" zIndex="1">
			<view class="dlg-main" @click.stop="">
				<view class="header">
					<view class="title">物流明细</view>
					<image src="" mode="" class="close" @click="openShow = false"></image>
				</view>
				<view class="popup-scroll">
					<logistics :wlInfo="detailData.logistics" :img="detailData.productCoverResource.url"
						:name="detailData.productName" :address="address" :logisticsStatus="detailData.logisticsStatus">
					</logistics>
				</view>
				<!-- <image src="@/static/order/close.png" mode="" class="popup-close" @click.stop="close"></image> -->
			</view>
		</popup-view>
		
		
		<popup-view v-model="logOutvisible" mode="center" border-radius="15" zIndex="1">
			<view class="log-out">
				<view class="log-title">温馨提示</view>
				<view class="log-sub">以下物品已超过发货时间，取消后将自动兑换为积分</view>
				<scroll-view scroll-y="true" class="log-out-tip">
					<!-- 该物品已超过发货时间，取消后将自动兑换为{{recoveryPoint}}分 -->
					<view class="re-list" v-for="(item,index) in reList" :key="index">
						<image v-if="item.productCoverResource" :src="item.productCoverResource.url" mode="" class="re-img"></image>
						<view class="re-info">
							<view class="re-name">{{item.productAbbreviation}}</view>
							<view class="re-point">回收积分：{{item.recoveryPoint}}</view>
						</view>
					</view>
				</scroll-view>
				<view class="log-out-footer">
					<view class="cancel" @click="closeBoxRefund">取消</view>
					<view class="shu"></view>
					<view class="log-out-submit" @click="submitBoxRefund">确定</view>
				</view>
			</view>
		</popup-view>
		
		
		<!-- 所有页面的弹框 -->
		<page-popup page="/pages/order/index"></page-popup>
	</view>
</template>

<script>
	import {
		myMixins
	} from "@/mixins/mixins.js";
	import {
		orderList,
		orderDetail,
		orderReceiptApi,
		orderRefundApi,
		orderDetailId,
		refundTimeApi,
		boxRefundTimeApi,
		boxRefundTimeExpiredApi
	} from '@/API/order.js'
	import logistics from '@/components/xinyu-logistics/xinyu-logistics.vue'
	import HeaderCom from '@/pages/components/header.vue'
	export default {
		mixins: [myMixins],
		data() {
			return {
				tabList: [{
						label: "全部",
						value: ''
					},
					{
						label: "待发货",
						value: 'WAITING_FOR_SHIPMENT'
					},
					{
						label: "待收货",
						value: 'WAITING_FOR_RECEIPT'
					},
					{
						label: "已完成",
						value: 'COMPLETED'
					},
				],
				tabIndex: 0,
				list: [],
				type: '',
				page: 1,
				statusObj: {
					"WAITING_FOR_PAYMENT": "待付款",
					"WAITING_FOR_SHIPMENT": "待发货",
					"SHIPPED": "已发货",
					"WAITING_FOR_RECEIPT": "待收货",
					"RECEIVED": "已收货",
					"COMPLETED": "已完成",
					"CANCELED": "已取消",
					"REFUNDED": "已退款",
					"RECOVERED": "已回收"
				},
				height: '0rpx',
				total: 0,
				openShow: false,
				detailData: {
					productCoverResource: {},
					logistics: {}
				},
				address: '',
				expireTime: '', //过期时间
				logOutvisible:false,
				id:'',
				shipExpiredTime:'',
				timer:null,
				recoveryPoint:0,
				reList:[]
			}
		},
		components: {
			logistics,
			HeaderCom
		},
		onLoad(opation) {
			this.type = opation.type
			this.tabList.forEach((item, index) => {
				if (item.value === this.type) {
					this.tabIndex = index
				}
			})
			// this.getOrderList()
			this.getRefundTime()
		},
		methods: {
			closeBoxRefund(){
				clearInterval(this.timer)
				this.timer = null
				this.logOutvisible = false
			},
			submitBoxRefund(){
				uni.showLoading()
				orderRefundApi({
					id: this.id
				}).then(res => {
					uni.hideLoading()
					this.$api.msg(res.message)
					if (res.code === 200) {
						clearInterval(this.timer)
						this.timer = null
						this.logOutvisible = false
						setTimeout(() => {
							this.page = 1
							this.getOrderList()
						}, 500)
				
					}
				}).catch(err => {
					uni.hideLoading()
				})
			},
			getRefundTime() {
				refundTimeApi().then(res => {
					console.log(res)
					if (res.code === 200) {
						this.expireTime = res.data
						this.getOrderList()
					} else {
						this.$api.msg(res.message)
					}

				})
			},
			thimeFn(shipExpiredTime){
				const secondsPerDay = 86400; // 1天有86400秒
				  // 将时间戳除以每天的秒数
				const currentTime = Math.floor(Date.now() / 1000);
				const targetTime = Math.floor(new Date(shipExpiredTime).getTime() / 1000);
				if (isNaN(targetTime)) {
					this.shipExpiredTime = '';
				}else{
					const countdown = targetTime - currentTime;
					if (countdown <= 0) {
						this.shipExpiredTime = '已过期'
					}else if(countdown > secondsPerDay){
						const days = parseInt(countdown / secondsPerDay); 
						this.shipExpiredTime = `${days}天`
						this.isShow = true
					}else {
						const hours = Math.floor(countdown / 3600);
						const minutes = Math.floor((countdown % 3600) / 60);
						const seconds = countdown % 60;
						this.shipExpiredTime = `${this.padZero(hours)}:${this.padZero(minutes)}:${this.padZero(seconds)}`
					}
				}
			},
			orderRefund(item) {
				this.id = ''
				if (item.expireTime < new Date().getTime()) {
					this.$api.msg('超过取消时长，无法取消')
					setTimeout(() => {
						this.getOrderList()
					}, 500)
					return
				}
				this.id = item.id
				if (item.type === 'BOX_DELIVERY') {
					uni.showLoading()
					
					boxRefundTimeExpiredApi({
						id: item.id
					}).then(res => {
						uni.hideLoading()
						if (res.code === 200) {
							console.log(res)
							if(res.data.length === 0){
								uni.showLoading()
								orderRefundApi({
									id: item.id
								}).then(result => {
									uni.hideLoading()
									this.$api.msg(result.message)
									if (result.code === 200) {
										setTimeout(() => {
											this.page = 1
											this.getOrderList()
										}, 500)
								
									}
								}).catch(err => {
									uni.hideLoading()
								})
							}else{
								this.reList = res.data
								this.logOutvisible = true
							}
							
							// this.recoveryPoint = res.data.recoveryPoint
							// let shipExpiredTime = res.data.shipExpiredTime ? res.data.shipExpiredTime : ''
							// if(shipExpiredTime){
							// 	const secondsPerDay = 86400; // 1天有86400秒
							// 	  // 将时间戳除以每天的秒数
							// 	const currentTime = Math.floor(Date.now() / 1000);
							// 	const targetTime = Math.floor(new Date(shipExpiredTime).getTime() / 1000);
							// 	const countdown = targetTime - currentTime;
							// 	if (countdown <= 0) {
							// 		this.logOutvisible = true
							// 	}else{
							// 		uni.showLoading()
							// 		orderRefundApi({
							// 			id: item.id
							// 		}).then(result => {
							// 			uni.hideLoading()
							// 			this.$api.msg(result.message)
							// 			if (result.code === 200) {
							// 				setTimeout(() => {
							// 					this.page = 1
							// 					this.getOrderList()
							// 				}, 500)
									
							// 			}
							// 		}).catch(err => {
							// 			uni.hideLoading()
							// 		})
							// 	}
							// }
						} else {
							this.$api.msg(res.message)
						}
					}).catch(err => {
						uni.hideLoading()
					})
					
					
					// boxRefundTimeApi({
					// 	id: item.id
					// }).then(res => {
					// 	uni.hideLoading()
					// 	if (res.code === 200) {
					// 		this.recoveryPoint = res.data.recoveryPoint
					// 		let shipExpiredTime = res.data.shipExpiredTime ? res.data.shipExpiredTime : ''
					// 		if(shipExpiredTime){
					// 			const secondsPerDay = 86400; // 1天有86400秒
					// 			  // 将时间戳除以每天的秒数
					// 			const currentTime = Math.floor(Date.now() / 1000);
					// 			const targetTime = Math.floor(new Date(shipExpiredTime).getTime() / 1000);
					// 			const countdown = targetTime - currentTime;
					// 			if (countdown <= 0) {
					// 				this.logOutvisible = true
					// 			}else{
					// 				uni.showLoading()
					// 				orderRefundApi({
					// 					id: item.id
					// 				}).then(result => {
					// 					uni.hideLoading()
					// 					this.$api.msg(result.message)
					// 					if (result.code === 200) {
					// 						setTimeout(() => {
					// 							this.page = 1
					// 							this.getOrderList()
					// 						}, 500)
									
					// 					}
					// 				}).catch(err => {
					// 					uni.hideLoading()
					// 				})
					// 			}
					// 		}
					// 	} else {
					// 		this.$api.msg(res.message)
					// 	}
					// }).catch(err => {
					// 	uni.hideLoading()
					// })
				} else {
					uni.showLoading()
					orderRefundApi({
						id: item.id
					}).then(res => {
						uni.hideLoading()
						this.$api.msg(res.message)
						if (res.code === 200) {
							setTimeout(() => {
								this.page = 1
								this.getOrderList()
							}, 500)

						}
					}).catch(err => {
						uni.hideLoading()
					})
				}

			},
			
			padZero(num) {
				return num.toString().padStart(2, '0');
			},
			goBack() {
				uni.switchTab({
					url: `/pages/mine/index`
				})
			},
			orderReceipt(item) {
				uni.showLoading()
				orderReceiptApi({
					id: item.id
				}).then(res => {
					uni.hideLoading(),
						this.$api.msg(res.message)
					if (res.code === 200) {
						this.page = 1
						this.getOrderList()
					}
				})
			},
			getOrderList() {
				uni.showLoading()
				orderList({
					page: this.page,
					size: 10,
					status: this.tabList[this.tabIndex].value
				}).then(res => {
					uni.hideLoading()
					res.data.content.forEach(item => {
						if (item.paidAt) {
							// 初始时间
							const initialDate = new Date(item.paidAt);
							// 增加的秒数
							const secondsToAdd = this.expireTime;

							const millisecondsToAdd = secondsToAdd * 1000;
							// 计算新的时间
							const newDate = new Date(initialDate.getTime() + millisecondsToAdd);

							// 格式化输出新的时间
							const year = newDate.getFullYear();
							const month = String(newDate.getMonth() + 1).padStart(2,
							'0'); // 月份从 0 开始，所以要加 1
							const day = String(newDate.getDate()).padStart(2, '0');
							const hours = String(newDate.getHours()).padStart(2, '0');
							const minutes = String(newDate.getMinutes()).padStart(2, '0');
							const seconds = String(newDate.getSeconds()).padStart(2, '0');

							const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
							item['expireTime'] = new Date(formattedTime).getTime()
						}

						// console.log("formattedTime:",formattedTime);
						// console.log("formattedTime:",new Date(formattedTime).getTime()); // 输出结果
						// console.log("formattedTime:",new Date().getTime());
					})
					this.total = res.data.total
					if (this.page > 1) {
						this.list = [...this.list, ...res.data.content]
					} else {
						this.list = res.data.content
					}
					console.log(this.list)
				}).catch(err => {
					uni.hideLoading()
				})
			},
			tabCk(index) {
				this.page = 1
				this.tabIndex = index
				this.getOrderList()
			},
			scrolltolower() {
				if (this.total == this.list.length) {
					return
				}
				this.page += 1
				this.getOrderList()
			},
			goDetail(item) {
				// uni.navigateTo({
				// 	url: `/pages/mine/orderStatusDetail?no=${item.no}&id=${item.id}`
				// })
				clearInterval(this.timer)
				this.timer = null
				uni.navigateTo({
					url: `/pages/mine/orderStatusDetail?id=${item.id}`
				})
			},
			againProduct(item) {
				uni.navigateTo({
					url: `/pages/shop/detail?id=${item.productId}`
				})
			},
			close() {
				this.openShow = false
			},
			lookLogistics(item) {
				this.getDetail(item.id)
			},

			// 获取详情
			getDetail(id) {
				uni.showLoading()
				orderDetailId(id).then(res => {
					uni.hideLoading()
					if (res.code === 200) {
						this.detailData = res.data
						console.log("this.detailData:", this.detailData)
						this.detailData.logistics['logisticsStatus'] = this.detailData.logisticsStatus
						this.address = this.detailData.receiver.address
						this.openShow = true
					} else {
						this.$api.msg(res.message)
					}
				}).catch(err => {
					uni.hideLoading()
				})
			},
		}
	}
</script>
<style lang="scss" scoped>
	page {
		background-color: #f5f5f5;
	}

	.order-page {
		padding-top: 112rpx;

		.tab {
			display: flex;
			align-items: center;

			.tab-item {
				width: 188rpx;
				height: 96rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;
				font-weight: 500;
				font-size: 28rpx;
				color: #666666;

				.active-heng {
					width: 48rpx;
					height: 8rpx;
					background: linear-gradient(90deg, #00AAFF 0%, rgba(0, 170, 255, 0) 100%);
					border-radius: 4rpx 0px 0px 4rpx;
				}

				.heng {
					width: 48rpx;
					height: 8rpx;
				}
			}

			.active {
				font-weight: 800;
				font-size: 28rpx;
				color: #000000;
			}
		}

		.scroll-list-view {
			height: calc(100vh - 208rpx);
			padding: 0 32rpx;

			.list {
				margin-bottom: 24rpx;
				width: 686rpx;
				background: #FFFFFF;
				border-radius: 24rpx;
				padding: 24rpx;

				.list-header {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.header-left {
						font-weight: 500;
						font-size: 24rpx;
						color: #999999;
					}

					.header-right {
						font-weight: bold;
						font-size: 28rpx;
						color: #000000;
					}
				}

				.list-detail {
					display: flex;
					align-items: center;

					.shop-img {
						width: 160rpx;
						height: 160rpx;
						border-radius: 0 24rpx 24rpx 0;
						background-image: url('@/static/new/shop-bg.png');
						background-size: contain;
						display: flex;
						align-items: center;
						justify-content: center;

						.detail-img {
							width: 142rpx;
							height: 132rpx;
						}
					}

					.detail {
						margin-left: 24rpx;

						.name {
							width: 360rpx;
							overflow: hidden;
							white-space: nowrap;
							text-overflow: ellipsis;
							font-weight: 500;
							font-size: 28rpx;
							color: #000000;
						}

						.price-name {
							display: flex;
							align-items: center;
							justify-content: space-between;
							margin-top: 44rpx;

							.old-price {
								font-weight: bold;
								font-size: 32rpx;
								color: #000000;
							}

							.num {
								font-weight: 500;
								font-size: 28rpx;
								color: #999999;
							}
						}
					}
				}

				.list-footer {
					display: flex;
					align-items: center;
					justify-content: end;

					.btn {
						margin-left: 16rpx;
						width: 160rpx;
						height: 64rpx;
						background: #FFFFFF;
						border-radius: 8rpx;
						border: 2rpx solid #EBEBEB;
						font-weight: 500;
						font-size: 24rpx;
						color: #666666;
						display: flex;
						align-items: center;
						justify-content: center;
					}
				}
			}
		}

		.dlg-main {
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;

			.header {
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: 750rpx;
				height: 96rpx;
				padding: 0 32rpx;

				.title {
					font-weight: bold;
					font-size: 32rpx;
					color: #000000;
				}

				.close {
					width: 48rpx;
					height: 48rpx;
				}
			}

			.popup-scroll {
				width: 706rpx;
				height: 900rpx;
				background-color: #fff;
				border-radius: 20rpx;
				overflow-y: scroll;
			}

			.popup-close {
				margin-top: 36rpx;
				width: 54rpx;
				height: 54rpx;
			}
		}
		
		
		
		.log-out{
			width: 630rpx;
			// height: 300rpx;
			background: #FFFFFF;
			border-radius: 16rpx;
			.log-title{
				text-align: center;
				font-size: 40rpx;
				color: #000;
				font-weight: bold;
				padding-top: 20rpx;
			}
			.log-sub{
				text-align: center;
				font-size: 24rpx;
				color: #999;
			}
			.log-out-tip{
				padding: 40rpx 20rpx;
				height: 400rpx;
				// overflow-y: auto;
				// height: 200rpx;
				font-weight: 500;
				font-size: 32rpx;
				color: rgba(0,0,0,0.85);
				text-align: center;
				.re-list{
					display: flex;
					align-items: center;
					margin-bottom: 10rpx;
					padding-bottom: 10rpx;
					border-bottom: 1px solid rgba(0,0,0,0.06);
					.re-img{
						width: 100rpx;
						height: 100rpx;
						border-radius: 10rpx;
						border: 1px solid red;
					}
					.re-info{
						margin-left: 10rpx;
						width: 400rpx;
						height: 100rpx;
						display: flex;
						// align-items: center;
						justify-content: space-between;
						flex-direction: column;
						.re-name{
							width: 400rpx;
							text-align: left;
							overflow: hidden;
							white-space: nowrap;
							text-overflow: ellipsis;
							font-weight: 500;
							font-size: 28rpx;
							color: #000000;
						}
						.re-point{
							width: 400rpx;
							text-align: left;
							overflow: hidden;
							white-space: nowrap;
							text-overflow: ellipsis;
							font-weight: 500;
							font-size: 28rpx;
							color: #999999;
						}
					}
				}
			}
			.log-out-footer{
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-top: 2rpx solid rgba(0,0,0,0.06);
				height: 100rpx;
				.cancel{
					width: 294rpx;
					height: 100rpx;
					line-height: 100rpx;
					font-weight: 500;
					font-size: 32rpx;
					color: #000000;
					text-align: center;
					border-right: 1px solid rgba(0,0,0,0.06);
				}
				.log-out-submit{
					width: 294rpx;
					height: 100rpx;
					line-height: 100rpx;
					font-weight: 500;
					font-size: 32rpx;
					color: #E55353;
					text-align: center;
				}
			}
		}
	}
</style>