<template>
	<view class="app-container">
		<view class="tab-container">
			<view class="item" :class="tabCurrent == '' ? 'current':''" @tap="changeTab('')"><text>全部</text></view>
			<view class="item" :class="tabCurrent == 'NOPAY' ? 'current':''" @tap="changeTab('NOPAY')"><text>待付款</text></view>
			<view class="item" :class="tabCurrent == 'DFH' ? 'current':''" @tap="changeTab('DFH')"><text>待发货</text></view>
			<view class="item" :class="tabCurrent == 'YFH' ? 'current':''" @tap="changeTab('YFH')"><text>待收货</text></view>
			<view class="item" :class="tabCurrent == 'OVER' ? 'current':''" @tap="changeTab('OVER')"><text>已完成</text></view>
			<view class="item" :class="tabCurrent == 'REFUND' ? 'current':''" @tap="changeTab('REFUND')"><text>售后中</text></view>
		</view>
		
		<view class="list-container">
			<block v-for="(item, index) in orderList" :key='index'>
				<view class="item" @tap="toOrderDetail(item.orderId, item.orderRefundId)">
					
					<!-- 普通订单 -->
					<block v-if="tabCurrent != 'REFUND'">
						<view class="top">
							<view class="left">{{item.orderId}}</view>
							<view class="right">{{item.orderStatus | statusFilter}}</view>
						</view>
						
						<block v-for="(goodsItem, goodsIndex) in item.orderDetails" :key='goodsIndex'>
							<view class="goods" :class="'goods'+goodsIndex">
								<image :src="goodsItem.imgUrl" mode="aspectFill"></image>
								<view class="main">
									<view class="row1">
										<view class="name ellipsis-2">{{goodsItem.goodsName}}</view>
										<view class="price">￥{{goodsItem.price}}</view>
									</view>
									<view class="row2">
										<view>{{goodsItem.goodsSpecValue}}</view>
										<view>x{{goodsItem.num}}</view>
									</view>
								</view>
							</view>
						</block>
						
						<view class="bottom">
							<view class="left">{{item.createTime}}</view>
							<view class="total">共{{item.totalNum}}件 订单总额：<text>￥{{item.payAmount | numToFixed}}</text></view>
						</view>
					</block>
					
					<!-- 售后订单 -->
					<block v-if="tabCurrent == 'REFUND'">
						<view class="top">
							<view class="left">{{item.orderId}}</view>
							<view class="right">{{item.orderStatus | statusFilter2}}</view>
						</view>
						
						<!-- 拒绝申请 -->
						<block v-if="item.examineStatus === 'FAIL'">
							<block v-for="(goodsItem, goodsIndex) in item.orderDetails" :key='goodsIndex'>
								<view class="goods" :class="'goods'+goodsIndex">
									<image :src="goodsItem.imgUrl" mode="aspectFill"></image>
									<view class="main">
										<view class="row1">
											<view class="name ellipsis-2">{{goodsItem.goodsName}}</view>
											<view class="price">￥{{goodsItem.price}}</view>
										</view>
										<view class="row2">
											<view>{{goodsItem.goodsSpecValue}}</view>
											<view>x{{goodsItem.refundNum}}</view>
										</view>
									</view>
								</view>
							</block>
							<view class="bottom">
								<view class="left">{{item.createTime}}</view>
								<view class="total">共{{item.totalNum}}件 {{item.orderStatus == 'NOPAY' ? '应付':'实付'}}总额：<text>￥{{item.payAmount | numToFixed}}</text></view>
							</view>
						</block>
						<!-- 其他 -->
						<block v-else>
							<block v-for="(goodsItem, goodsIndex) in item.orderDetails" :key='goodsIndex'>
								<view class="goods" :class="'goods'+goodsIndex" v-if="goodsItem.refund">
									<image :src="goodsItem.imgUrl" mode="aspectFill"></image>
									<view class="main">
										<view class="row1">
											<view class="name ellipsis-2">{{goodsItem.goodsName}}</view>
											<view class="price">￥{{goodsItem.price}}</view>
										</view>
										<view class="row2">
											<view>{{goodsItem.goodsSpecValue}}</view>
											<view>x{{goodsItem.refundNum}}</view>
										</view>
									</view>
								</view>
							</block>
							<view class="bottom">
								<view class="left">{{item.createTime}}</view>
								<view class="total">共{{getRefundNum(item.orderDetails)}}件 {{item.orderStatus == 'OVER' ? '实退':'应退'}}总额：<text>￥{{item.refundAmount | numToFixed}}</text></view>
							</view>
						</block>
					</block>
					
					
					<!-- 按钮：待付款 -->
					<view class="btn-group btn-group2" v-if="item.orderStatus == 'NOPAY'">
						<div class="tips">请在30分钟内付款</div>
						<div class="btns">
							<div class="button gray" @tap.stop="cancelOrder(item.orderId)">取消订单</div>
							<div class="button red" @tap.stop="payOrder(item.orderId)">立即付款</div>
						</div>
					</view>
					<!-- 按钮：待发货 -->
					<view class="btn-group" v-if="item.orderStatus == 'DFH'">
						<div class="button white" @tap.stop="remindShipment(item.orderId)">提醒发货</div>
						<div class="button white" v-if="checkCanReturn(item.orderShareStatus)" @tap.stop="toApplyReturn(item.orderId)">申请售后</div>
					</view>
					<!-- 按钮：待收货 -->
					<view class="btn-group" v-if="item.orderStatus == 'YFH'">
						<div class="button gray" @tap.stop="toLogistics(item.companyCode, item.logisticsNo)">查看物流</div>
						<div class="button red" @tap.stop="clickConfirmReceipt(item.orderId)">确认收货</div>
						<div class="button white" v-if="checkCanReturn(item.orderShareStatus)" @tap.stop="toApplyReturn(item.orderId)">申请售后</div>
					</view>
					<!-- 按钮：已完成 -->
					<view class="btn-group" v-if="item.orderStatus == 'OVER' && tabCurrent != 'REFUND'">
						<div class="button gray" @tap.stop="toLogistics(item.companyCode, item.logisticsNo)">查看物流</div>
						<div class="button white" v-if="checkCanReturn(item.orderShareStatus)" @tap.stop="toApplyReturn(item.orderId)">申请售后</div>
					</view>
					<!-- 按钮：已关闭 -->
					<view class="btn-group" v-if="item.orderStatus == 'CLOSE'">
						<div class="button gray">查看详情</div>
					</view>
					<!-- 按钮：超时未支付 -->
					<view class="btn-group" v-if="item.orderStatus == 'TIMEOUT'">
						<div class="button gray">查看详情</div>
					</view>
					<!-- 按钮：售后中 -->
					<view class="btn-group" v-if="item.orderStatus == 'REFUND'">
						<div class="button gray">查看详情</div>
					</view>
					<!-- 按钮：售后中 待商家处理 -->
					<view class="btn-group" v-if="item.orderStatus == 'DSJCL'">
						<div class="button gray" @tap.stop="toReturnDetail(item.orderRefundId)">售后详情</div>
					</view>
					<!-- 按钮：售后中 待买家处理 -->
					<view class="btn-group" v-if="item.orderStatus == 'DMJCL'">
						<div class="button red" @tap.stop="toReturnDetail(item.orderRefundId)" v-if="item.examineStatus == 'OK'">提交资料</div>
						<div class="button white" @tap.stop="toApplyReturn(item.orderId)" v-if="item.examineStatus == 'FAIL'">重新申请</div>
					</view>
					<!-- 按钮：售后中 待商家收货 -->
					<view class="btn-group" v-if="item.orderStatus == 'DSJSH'">
						<div class="button gray" @tap.stop="toReturnDetail(item.orderRefundId)">售后详情</div>
					</view>
					<!-- 按钮：售后中 退款成功 -->
					<view class="btn-group" v-if="item.orderStatus == 'OVER' && tabCurrent == 'REFUND'">
						<div class="button gray" @tap.stop="toReturnDetail(item.orderRefundId)">售后详情</div>
					</view>
				</view>
			</block>
		</view>
		<no-data v-if="!orderList.length" :showText="'暂无订单'"></no-data>
		<loading-text v-if="orderList.length"  :loading="loading" :noMore="noMore" ></loading-text>
		
		<!-- 取消订单 -->
		<modal-dialog showText="确定要取消订单吗？" :isShowDialog="isCancelDialog" @cancel="isCancelDialog = false" @confirm="confirmCancelOrder"></modal-dialog>
		
		<!-- 确认收货 -->
		<modal-dialog showText="确定要确认收货吗？" :isShowDialog="isConfirmDialog" @cancel="isConfirmDialog = false" @confirm="confirmReceipt"></modal-dialog>
	</view>
</template>

<script>
	import {mapState} from 'vuex';
	import modalDialog from '@/components/modalDialog.vue';
	
	export default {
		components:{
			modalDialog
		},
		filters: {
			statusFilter(val) {
				const statusMap = {
					NOPAY: '待付款',
					DFH: '待发货',
					YFH: '待收货',
					OVER: '已完成',
					CLOSE: '已关闭',
					REFUND: '售后中',
					TIMEOUT: '超时未支付'
				 }
				 return statusMap[val]
			},
			statusFilter2(val) {
				const statusMap = {
					DSJCL: '待商家处理',
					DSJSH: '待商家收货',
					DMJCL: '待买家处理',
					OVER: '退款成功',
					CANCEL: '已取消',
				 }
				 return statusMap[val]
			},
		},
		data() {
			return {
				configInfo: uni.getStorageSync('configInfo'),
				tabCurrent: '', // 当前tab状态
				orderList: [], // 订单列表
				pageNum: 1,
				pageSize: 8,
				noMore: false,
				loading: false,
				isCancelDialog: false, // 是否显示取消订单弹窗
				cancelOrderId: null, // 取消订单id
				isConfirmDialog: false, // 是否显示确认收货弹窗
				confirmReceiptId: null, // 确认收货id
				autoDetailId: null, // 自动跳转到详情页id
				canRemindShipment: true, // 能否点击提醒发货
			}
		},
		
		computed:{
			...mapState(['userInfo', 'isLogin', 'userId'])
		},
		
		onLoad({tab, orderId}) {
			this.tabCurrent = tab;
			console.log(this.tabCurrent);
			if(orderId) {
				this.autoDetailId = orderId;
			}
			this.getOrderList();
			
			uni.$on('refreshOrderList',(data) => {
				if(data) {
					this.tabCurrent = 'REFUND';
				}
				this.getOrderList();
			})
		},
		
		// 下拉刷新
		onPullDownRefresh() {
			this.pageNum = 1;
			this.getOrderList();
		},
		
		// 上拉加载
		onReachBottom() {
			this.getOrderList(1);
		},
		
		methods: {
			getOrderList(loadMore) {
				if(this.noMore && loadMore)return;
				this.noMore = false
				if(!loadMore){
					this.pageNum = 1;
				}else{
					this.loading = true;
				}
				let url = '';
				let orderStatus = '';
				if(this.tabCurrent == 'REFUND') {
					url = '/order/refund/list';
					orderStatus = '';
				}else {
					url = '/order/my/order';
					orderStatus = this.tabCurrent;
				}
				this.$axios({
					url: url,
					method: 'get',
					params: {
						pageNo: this.pageNum,
						pageSize: this.pageSize,
						orderStatus: orderStatus,
						userId: this.userId
					},
					isLoading: !loadMore
				}).then(res => {
					let _list = res.data.records;
					let pageTotal = res.data.pages;
					if(this.pageNum >= pageTotal){
						this.noMore = true;
					}
					if (_list.length) {
						this.pageNum += 1
					}
					if (loadMore) {
						this.orderList = this.orderList.concat(_list);
						this.loading = false;
					} else {
						this.orderList = _list;
					}
					
					uni.stopPullDownRefresh();
					
					
					if(this.autoDetailId) {
						this.toOrderDetail(this.autoDetailId);
					}
				})
			},
			
			getRefundNum(orderDetails) {
				let refundNum = 0;
				orderDetails.forEach(item => {
					if(item.refund) {
						refundNum = refundNum + item.refundNum;
					}
				})
				return refundNum;
			},
			
			// 检查是否可以申请售后（根据orderShareStatus）
			checkCanReturn(status) {
				if(!status || status === 'OVER' || status === 'CANCEL') {
					return false;
				}else {
					return true;
				}
			},
			
			// 切换类型
			changeTab(current) {
				this.orderList = [];
				this.tabCurrent = current;
				this.pageNum = 1;
				this.getOrderList();
			},
			
			// 申请退款
			toApplyReturn(orderId) {
				uni.navigateTo({
					url:'/pages/mine/order/return/apply?orderId=' + orderId
				})
			},
			
			// 去订单详情
			toOrderDetail(orderId, orderRefundId) {
				this.autoDetailId = null;
				if(orderRefundId) {
					return uni.navigateTo({
						url:'/pages/mine/order/return/detail?orderRefundId=' + orderRefundId
					})
				}
				uni.navigateTo({
					url:'/pages/mine/order/detail?orderId=' + orderId + '&orderRefundId=' + orderRefundId
				})
			},
			
			// 取消订单
			cancelOrder(orderId) {
				this.cancelOrderId = orderId;
				this.isCancelDialog = true;
			},
			
			// 确认取消订单
			confirmCancelOrder() {
				this.$axios({
					url: '/order/cancel',
					method: 'get',
					params: {
						orderId: this.cancelOrderId
					}
				}).then(res => {
					this.isCancelDialog = false;
					this.pageNum = 1;
					this.getOrderList();
					this.$successToast('取消订单成功');
				})
			},
			
			// 确认收货
			clickConfirmReceipt(orderId) {
				this.confirmReceiptId = orderId;
				this.isConfirmDialog = true;
			},
			
			// 确定 确认收货
			confirmReceipt() {
				this.$axios({
					url: '/order/ack',
					params: {
						orderId: this.confirmReceiptId
					}
				}).then(res => {
					this.isConfirmDialog = false;
					this.pageNum = 1;
					this.getOrderList();
					this.$successToast('确认收货成功');
				})
			},
			
			// 立即付款
			payOrder(orderId) {
				let that = this;
				this.$axios({
					url: '/order/wait/pay',
					params: {
						userId: this.userId,
						orderId: orderId,
					},
					isLoading: 1,
				}).then(res => {
					uni.getProvider({
						service: 'payment',
						success: (e) => {
							uni.requestPayment({
								provider: e.provider[0],
								orderInfo: res.data,
								timeStamp: res.data.timeStamp,
								nonceStr: res.data.nonceStr,
								package: res.data.payPackage,
								signType: 'MD5',
								paySign: res.data.paySign,
								success: (res) => {
									that.$successToast('支付成功');
									that.pageNum = 1;
									that.getOrderList();
									that.requestMessage();
								},
								fail: (err) => {
									that.$toast('支付失败');
								}
							})
						}
					})
				})
			},
			
			// 消息推送
			requestMessage() {
				let that = this;
				uni.showModal({
					title: '温馨提示',
					content: '为更好的促进您与买家的交流，需要在您的订单成交时向您发送消息',
					confirmText: "同意",
					cancelText: "拒绝",
					success: function (res) {
						if (res.confirm) {
							let tmplIds = [that.configInfo.template];
							uni.requestSubscribeMessage({
								tmplIds: tmplIds,
								success (res) {
									let status = null;
									tmplIds.map((item, index) => {
										if(res[item] == 'accept') {
											status = 'accept';
										}
									})
									if(status == 'accept') {
										that.$successToast('订阅成功');
									}else {
										that.$toast('订阅取消');
									}
								},
								fail (res) {
									console.log(res);
									that.$toast('订阅失败');
								}
							})
						} else if (res.cancel) {
							uni.showModal({
								title: '温馨提示',
								content: '拒绝后您将无法获取实时的与卖家（买家）的交易消息',
								confirmText: "知道了",
								showCancel: false,
								success: function (res) {
									
								}
							});
						}
					}
				});
			},
			
			// 去售后详情
			toReturnDetail(orderRefundId) {
				uni.navigateTo({
					url:'/pages/mine/order/return/detail?orderRefundId=' + orderRefundId
				})
			},
			
			// 去查看物流
			toLogistics(companyCode, logisticsNo) {
				uni.navigateTo({
					url:'/pages/mine/order/logistics?companyCode=' + companyCode + '&logisticsNo=' + logisticsNo
				})
			},
			
			// 提醒发货
			remindShipment(orderId) {
				if (!this.canRemindShipment) {
					return this.$toast('请勿频繁操作');
				};
				this.canRemindShipment = false;
				setTimeout(() => { this.canRemindShipment = true }, 3000)
				
				this.$axios({
					url: '/order/notice',
					params: {
						orderId: orderId,
						userId: this.userId
					}
				}).then(res => {
					this.$successToast('提醒发货成功');
				})
			},
		}
	}
</script>

<style lang="scss">
	.app-container {
		background: #F4F2F2;
		box-sizing: border-box;
	}
	.tab-container {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		background: #FFFFFF;
		display: flex;
		.item {
			width: 20%;
			text-align: center;
			text {
				display: inline-block;
				padding: 0 10rpx;
				line-height: 80rpx;
				padding-top: 8rpx;
			}
			&.current {
				text {
					color: #FF3F42;
					border-bottom: 6rpx solid #FF3F42;
				}
			}
		}
	}
	.list-container {
		padding: 110rpx 20rpx 0;
		.item {
			margin-bottom: 20rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 0 20rpx;
			.top {
				height: 70rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				.left {
					font-size: 28rpx;
					color: #666666;
				}
				.right {
					font-size: 28rpx;
					color: #FE781F;
				}
			}
			.goods {
				display: flex;
				justify-content: space-between;
				margin-top: 20rpx;
				&.goods0 {
					margin-top: 0;
				}
				image {
					width: 140rpx;
					height: 140rpx;
					display: block;
					flex-shrink: 0;
					margin-right: 20rpx;
				}
				.main {
					width: 510rpx;
					.row1 {
						display: flex;
						justify-content: space-between;
						.name {
							font-size: 28rpx;
							line-height: 36rpx;
						}
						.price {
							font-size: 28rpx;
							margin-left: 20rpx;
							color: #666666;
						}
					}
					.row2 {
						display: flex;
						justify-content: space-between;
						font-size: 28rpx;
						color: #999999;
						margin-top: 10rpx;
					}
				}
			}
			.bottom {
				display: flex;
				align-items: center;
				justify-content: space-between;
				height: 50rpx;
				.left {
					font-size: 24rpx;
					color: #999999;
				}
				.total {
					font-size: 24rpx;
					color: #666666;
					text {
						color: #FF3F42;
						font-size: 28rpx;
					}
				}
			}
			.btn-group {
				border-top: 1px solid #eaeaea;
				height: 100rpx;
				display: flex;
				justify-content: flex-end;
				align-items: center;
				&.btn-group2 {
					justify-content: space-between;
					.tips {
						font-size: 28rpx;
						color: #FF3F42;
					}
					.btns {
						display: flex;
					}
				}
				.button {
					width: 140rpx;
					height: 48rpx;
					border-radius: 48rpx;
					text-align: center;
					line-height: 48rpx;
					font-size: 24rpx;
					margin-left: 20rpx;
					flex-shrink: 0;
					&:first-child {
						margin-left: 0;
					}
					&.gray {
						color: #999999;
						border: 1px solid #999999;
					}
					&.white {
						color: #FF3F42;
						border: 1px solid #FF3F42;
					}
					&.red {
						color: #FFFFFF;
						border: 1px solid #FF3F42;
						background: #FF3F42;
					}
				}
			}
		}
	}
</style>
