<template>
	<view class="wrap">
		<up-navbar placeholder style="z-index: 100800;" @leftClick="navBack">
			<template #center>
				<view>订单</view>
			</template>
		</up-navbar>
		<up-sticky bgColor="#fff">
			<view style="padding: 10rpx 20rpx 0 20rpx;">
				<up-search shape="round" v-model="keyword" @custom="searchOn" @search="searchOn" @clear="searchOn"
					:actionStyle="{color: '#20b128'}"></up-search>
			</view>
			<up-tabs :current="tabsActive" :list="tablist" lineColor="#20b128" :scrollable="false"
				:activeStyle="	{ color: '#20b128', fontWeight: 'bold' }" @change="changeTab"></up-tabs>
		</up-sticky>

		<swiper class="swiper-box" :current="swiperCurrent" @animationfinish="animationfinish">
			<swiper-item class="swiper-item" v-for="(list, k) in orderList" :key="k">
				<scroll-view scroll-y style="height: 100%;width: 100%;" @scrolltolower="loadMoreGood">
					<view class="page-box">
						<view v-if="list.length>0" class="list">
							<good v-for="(item, index) in list" :datas="item" :key="index" :type="k"
								@cancleOrder="cancleOrder" @takeOrder="takeOrder" @rePay="rePay"
								@purchaseAgain="purchaseAgain" @applyAfterSales="applyAfterSales"></good>
						</view>
						<view v-if="!where[k].loading&&list.length==0" style="padding-top: 100rpx;">
							<up-empty text="订单空空如也"
								icon="https://lihai001.oss-cn-chengdu.aliyuncs.com/def/29955202404260944367594.png">
							</up-empty>
						</view>
						<view v-else-if="where[k].loadend" style="padding-top: 100rpx;">
							<view style="text-align: center;color: #999;">没有更多了</view>
						</view>
						<view v-if="where[k].loading"
							style="padding-top: 100rpx;display: flex;flex-direction: column;align-items: center;">
							<up-loading-icon mode="circle"></up-loading-icon>
							<view style="margin-top: 20rpx;color: #999;">加载中</view>
						</view>
						<view style="width: 100%;height: 300rpx;"></view>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
	<orderCanclePopup :show="showCancel" @close="showCancel=false" @change="submitCancel" />
	<modal :show="showTake" title="确认收货" content="请确认您已收到货" @close="showTake=false" @change="confirmReceipt" />

	<!-- 退款原因 -->
	<up-popup :show="refundShow" closeable round="10" @close="close">
		<view class="address-popup">
			<view class="head-title">选择商品</view>

			<view class="afterSales-type">
				<view class="afterSales-type-title">售后类型</view>
				<view class="afterSales-type-con">
					<view class="afterSales-type-item">仅退款</view>
					<view class="afterSales-type-item">退款退货</view>
					<view class="afterSales-type-item">换货</view>
				</view>
			</view>


			<scroll-view style="max-height: 50vh;padding-bottom: 20rpx;" scroll-y>



				<block v-for="(item,index) in refundReasonList" :key="index">
					<view class="row" @click="refundType = item.value">
						<view class="content">
							<view class="top"></view>
							<view class="bottom u-line-2">{{item.value}}</view>
						</view>
						<image v-if="refundType==item.value" src="@/static/icon/check.png"></image>
						<image v-else src="@/static/icon/n-check.png"></image>
					</view>
				</block>
			</scroll-view>
			<up-button color="#20B128" shape="circle" @click="onSubmitReason">提交</up-button>
		</view>
	</up-popup>
</template>

<script setup>
	import {
		onLoad,
		onUnload
	} from "@dcloudio/uni-app"
	import {
		ref
	} from 'vue';
	import good from "./component/good.vue";
	import orderCanclePopup from "@/components/orderCanclePopup.vue"
	import modal from "@/components/modal.vue"
	import {
		cancelOrderApi,
		rePaymentApi,
		confirmReceiptApi,
		orderListApi,
		purchaseAgainApi
	} from "@/api/order.js"

	const tabsActive = ref(0)
	const changeTab = ({
		index
	}) => {
		tabsActive.value = index;
		swiperCurrent.value = index;
	}
	const tablist = ref([{
		name: '全部'
	}, {
		name: '待付款'
	}, {
		name: '待核销'
	}, {
		name: '已核销'
	}, {
		name: '退款/售后'
	}]);

	const swiperCurrent = ref(0);
	const animationfinish = ({
		detail: {
			current
		}
	}) => {
		swiperCurrent.value = current;
		tabsActive.value = current;

		if (swiperCurrent.value == 0 && orderList.value[0].length == 0) getOrderList(0, '', ''); //全部
		if (swiperCurrent.value == 1 && orderList.value[1].length == 0) getOrderList(1, '', 0); //代付款
		if (swiperCurrent.value == 2 && orderList.value[2].length == 0) getOrderList(2, 1, 1); //待核销
		if (swiperCurrent.value == 3 && orderList.value[3].length == 0) getOrderList(3, 2, 1); //已核销
		if (swiperCurrent.value == 4 && orderList.value[4].length == 0) getOrderList(2, -1, 1); //退款
	}

	// 取消订单
	const showCancel = ref(false);
	let cancelId = '';
	const submitCancel = (e) => {
		showCancel.value = false;
		cancelOrderApi({
			order_id: cancelId,
			value: e.value
		}).then(res => {
			uni.showToast({
				title: '取消成功',
				icon: 'none'
			})
			orderList.value[1] = orderList.value[1].filter(item => item.id !== cancelId)
		})
	}

	// 取消订单
	const cancleOrder = (e) => {
		cancelId = e.id;
		showCancel.value = true;
	}

	// 确认收货
	const showTake = ref(false);
	let takeId = "";
	const takeOrder = (e) => {
		takeId = e.id;
		showTake.value = true;
	}

	// 确认收货
	const confirmReceipt = () => {
		confirmReceiptApi({
			order_id: takeId
		}).then(res => {
			showTake.value = false;
			uni.$u.toast('确认收货成功');
			reloadAll();
		})
	}

	// 再次购买
	const purchaseAgain = (e) => {
		purchaseAgainApi({
			order_id: e.id
		}).then(res => {
			uni.$u.toast('已加入购物车');
			uni.navigateTo({
				url: '/pages/cart/cart'
			})
		})
	}

	const refundShow = ref(true);

	// 申请售后
	const applyAfterSales = (item) => {
		uni.navigateTo({
			url: "/pages/afterSales/afterSales",
			success(res) {
				res.eventChannel.emit('orderDetail', item)
			}
		})
	}

	const rePay = (e) => {
		rePaymentApi({
			order_id: e.id,
			address_id: e.address_id,
			mer_id: e.merchant,
			pay_type: 1
		}).then(res => {
			if (!res.data?.nonceStr) return uni.$u.toast('支付失败!');
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: res.data.timeStamp,
				nonceStr: res.data.nonceStr,
				package: res.data.package,
				signType: res.data.signType,
				paySign: res.data.paySign,
				success: (e) => {
					if (e.errMsg == 'requestPayment:ok') {
						uni.showToast({
							title: '订单支付成功',
							icon: 'success'
						})
						reloadAll();
					} else uni.$u.toast('支付失败')
				},
				fail: (e) => {
					uni.$u.toast('用户取消支付')
				}
			})
		}).catch(err => {
			uni.$u.toast('网络错误')
		})
	}

	// 订单
	const where = ref([{
			page_no: 1,
			page_size: 25,
			loading: false,
			loadend: false
		}, {
			page_no: 1,
			page_size: 25,
			loading: false,
			loadend: false
		},
		{
			page_no: 1,
			page_size: 25,
			loading: false,
			loadend: false
		},
		{
			page_no: 1,
			page_size: 25,
			loading: false,
			loadend: false
		},
		{
			page_no: 1,
			page_size: 25,
			loading: false,
			loadend: false
		}
	])
	const keyword = ref('')
	const orderList = ref([
		[],
		[],
		[],
		[],
		[]
	])
	const getOrderList = (type = 0, status = '', paid = 1) => {
		if (where.value[type].loadend) return;
		where.value[type].loading = true;
		orderListApi({
			page_no: where.value[type].page_no,
			page_size: where.value[type].page_size,
			order_id: keyword.value,
			status: status,
			paid: paid
		}).then(res => {
			if (where.value[type].page_no == 1) orderList.value[type] = [];
			orderList.value[type] = [...orderList.value[type], ...res.data.lists];
			if (res.data.lists.length < where.value[type].page_size) where.value[type].loadend = true;
			where.value[type].page_no++;
			where.value[type].loading = false;
		}).catch(err => {
			where.value[type].loading = false;
		})
	}

	const loadMoreGood = () => {
		if (swiperCurrent.value == 0) getOrderList(0, '', ''); //全部
		if (swiperCurrent.value == 1) getOrderList(1, '', 0); //代付款
		if (swiperCurrent.value == 2) getOrderList(2, 1, 1); //待核销
		if (swiperCurrent.value == 3) getOrderList(3, 2, 1); //已核销
		if (swiperCurrent.value == 4) getOrderList(2, -1, 1); //退款
	}

	// 搜索
	const searchOn = () => {
		orderList.value[+swiperCurrent.value] = [];
		where.value[+swiperCurrent.value].page_no = 1;
		where.value[+swiperCurrent.value].loadend = false;
		if (swiperCurrent.value == 0) getOrderList(0, '', ''); //全部
		if (swiperCurrent.value == 1) getOrderList(1, '', 0); //代付款
		if (swiperCurrent.value == 2) getOrderList(2, 1, 1); //待核销
		if (swiperCurrent.value == 3) getOrderList(3, 2, 1); //已核销
		if (swiperCurrent.value == 4) getOrderList(2, -1, 1); //退款
	}

	let back = 0;
	const navBack = () => {
		uni.navigateBack({
			delta: back ? +back : 0
		})
	}

	const reloadAll = () => { //对订单进行操作时刷新页面
		where.value.forEach(item => {
			item.page_no = 1;
			item.loadend = false;
		});

		getOrderList(0, '', ''); //全部
		getOrderList(1, '', 0); //代付款
		getOrderList(2, 1, 1); //待核销
		getOrderList(3, 2, 1); //已核销
		getOrderList(2, -1, 1); //退款
	}

	onLoad((options) => {
		if (options.type) {
			tabsActive.value = +options.type;
			swiperCurrent.value = +options.type;
			searchOn();
		}
		if (options.back) back = options.back;

		uni.$on('reLoadOrderList', reloadAll);
	})

	onUnload(() => {
		uni.$off('reLoadOrderList', reloadAll)
	})
</script>

<style lang="scss">
	.wrap {
		display: flex;
		flex-direction: column;
		height: calc(100vh - var(--window-top));
		width: 100%;
	}

	.swiper-box {
		flex: 1;
	}

	.swiper-item {
		height: 100%;
	}

	.page-box {
		margin: 20rpx;
	}

	.address-popup {
		padding: 30rpx;

		.head-title {
			font-weight: bold;
			text-align: center;
			margin-bottom: 20rpx;
		}

		.list-admin {
			display: flex;
			justify-content: space-between;
			margin-bottom: 20rpx;

			.admin-btn {
				display: flex;
				color: #20B128;

				.btn {
					margin-left: 20rpx;
					display: flex;
					align-items: center;

					&:active {
						color: rgba(#20B128, 0.8);
						transition: background-color 0.5s;
						animation: disappear 0.5s 0.5s forwards;
					}
				}
			}
		}

		.row {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding-bottom: 20rpx;
			border-bottom: 1rpx solid #f6f6f6;
			margin-bottom: 20rpx;

			&:last-child {
				border-bottom: none;
				margin-bottom: 0;
			}

			.content {
				.top {
					display: flex;

					view {
						margin-right: 20rpx;
					}
				}

				.bottom {}
			}

			image {
				width: 40rpx;
				height: 40rpx;
				flex-shrink: 0;
			}
		}
	}

	@keyframes disappear {
		to {
			opacity: 0;
			/* 渐隐 */
			transform: scale(0);
			/* 缩小 */
		}
	}
</style>