<template>
	<view class="order-list">
		<tui-skeleton v-if="isRequest" loadingType="2"></tui-skeleton>
		<cm-header-nav
			@leftClick="handleLeftClick"
			@rightClick="handleRightClick"
			@init="headerNavInit"
			:leftButtonGroup="leftButtonGroup"
			title="订单列表"
		></cm-header-nav>

		<!-- 滑块 tabs -->
		<view class="tabs">
			<tui-tabs
				:tabs="tabs"
				:currentTab="currentTab"
				@change="tabChange"
				:sliderWidth="48"
				color="#333333"
				selectedColor="#FF457B"
				sliderBgColor="#FF457B"
			></tui-tabs>
		</view>

		<!-- 协销筛选订单 -->
		<cm-order-filter-control
			@click="handleFilter"
			:buttonGroup="screenTabBar"
			v-if="isDealer"
		></cm-order-filter-control>
        
        <!-- 订单列表 -->
		<swiper
			:indicator-dots="false"
			:autoplay="false"
			class="swiper"
			:style="[swiperHeight]"
			:current="currentTab"
			@change="swiperChange"
		>
			<swiper-item v-for="tab in tabs" :key="tab.state">
				<!-- tab.orderList.length === 0 -->
				<view class="order-empty" v-if="tab.orderList.length === 0">
					<cm-empty :image="emptyInfo.image" :message="emptyInfo.message" :offset="100"></cm-empty>
				</view>
				<scroll-view scroll-y="true" v-else class="scroll-box" @scrolltolower="scrollBottom">
					<template v-for="(orderInfo, orderIndex) in tab.orderList">
						<view class="grid" :key="orderIndex"></view>
						<view class="order-section" :key="orderIndex" @click="handleToDetail(orderInfo)">
							<!-- 订单信息 -->
							<view class="order-info">
								<view class="order-num">
									<text class="label">订单编号：</text>
									<text>{{ orderInfo.orderNo }}</text>
								</view>
								<view class="order-time">
									<text class="label">下单时间：</text>
									<text>{{ orderInfo.orderTime }}</text>
								</view>
								<view class="status">{{ stateExpFormat(orderInfo.status) }}</view>
							</view>
							<view class="line"></view>
							<view
								class="shop-order"
								v-for="(shopOrder, shopOrderIndex) in orderInfo.shopOrderList"
								:key="shopOrderIndex"
							>
								<!-- 供应商 -->
								<view class="origin">
									<image class="cover" :src="shopOrder.shopLogo"></image>
									<view class="name">{{ shopOrder.shopName }}</view>
								</view>
								<!-- 商品列表 -->
								<view class="goods-list">
									<!-- 商品信息 -->
									<view
										class="order-goods"
										v-for="goods in shopOrder.orderProductList"
										:key="goods.productId"
									>
										<cm-order-prodcut :goods-data="goods"></cm-order-prodcut>
									</view>
								</view>
							</view>
							<!-- 统计 -->
							<view class="total">
								<view class="count">共{{ orderInfo.productCount }}件商品</view>
								<view class="status">
									<template v-if="['31', '32', '33', '82', '83'].includes(orderInfo.status)">
										<text class="label">已支付：</text>
										<text>￥{{ orderInfo.receiptAmount | formatPrice }}</text>
									</template>
									<template v-else>
										<text class="label">待付总额：</text>
										<text>￥{{ orderInfo.pendingPayments | formatPrice }}</text>
									</template>
								</view>
							</view>
							<!-- 操作 -->
							<cm-order-control-nav
								v-if="orderInfo.userId == userId"
								:orderInfo="orderInfo"
								@confirm="handleConfirmClick"
							></cm-order-control-nav>
						</view>
					</template>
					<!-- loading -->
					<view class="loading-more">
						<tui-loadmore :index="3" :visible="loadmore"></tui-loadmore>
						<tui-nomore :text="loadMoreText" :visible="!loadmore" backgroundColor="#f7f7f7"></tui-nomore>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
        
        <!-- 加载框 -->
        <cm-loading :visible="isSubLoading" :text="loadingText"></cm-loading>
        
		<!-- 操作弹窗 -->
		<tui-modal
			:show="modal"
			:content="modalText"
			:size="32"
			:maskClosable="false"
			color="#333"
			shape="circle"
			@click="handleModalConfirm"
		></tui-modal>
		
		<!-- 失效商品列表 -->
		<cm-order-invalid-modal
			:goodsList="invalidList"
			:visible="buyAgainModal"
			@confirm="buyAgainModalClick"
			@cancel="buyAgainModalHide"
		></cm-order-invalid-modal>
	</view>
</template>

<script>
import CmOrderProdcut from '@/components/cm-module/cm-order-prodcut/cm-order-prodcut.vue'
import CmOrderControlNav from '@/components/cm-module/cm-order-control-nav/cm-order-control-nav.vue'
import CmOrderInvalidModal from '@/components/cm-module/cm-order-invalid-modal/cm-order-invalid-modal.vue'
import CmOrderFilterControl from '@/components/cm-module/cm-order-filter-control/cm-order-filter-control.vue'
import CmLoading from '@/components/cm-module/cm-loading/cm-loading.vue'
import CmEmpty from '@/components/cm-module/cm-empty/cm-empty.vue'
import CmHeaderNav from '@/components/cm-module/cm-header-nav/cm-header-nav.vue'
import { debounce } from '@/common/common.js'
import orderList from './mixins/orderList.js'
import wechatPay from './mixins/wechatPay.js'
import { mapGetters } from 'vuex'
export default {
	mixins: [wechatPay, orderList],
	components: {
		CmOrderProdcut,
		CmOrderControlNav,
		CmOrderInvalidModal,
		CmOrderFilterControl,
		CmLoading,
		CmEmpty,
		CmHeaderNav
	},
	data() {
		return {
			tabs: [
				{
					name: '全部',
					state: 0,
					pageNum: 1,
					orderList: []
				},
				{
					name: '待付款',
					state: 1,
					pageNum: 1,
					orderList: []
				},
                {
                	name: '待分享',
                	state: 5,
                	pageNum: 1,
                	orderList: []
                },
				{
					name: '待发货',
					state: 2,
					pageNum: 1,
					orderList: []
				},
				{
					name: '已发货',
					state: 3,
					pageNum: 1,
					orderList: []
				},
				{
					name: '退货/款',
					state: 4,
					pageNum: 1,
					orderList: []
				}
			],
			currentTab: 0,
			screenTabBar: [{ id: 0, name: '全部订单' }, { id: 1, name: '用户订单' }, { id: 2, name: '自身订单' }],
			screenTab: 0,
			refresh: false,
			loadmore: false, // 正在加载更多
			isRequest: true,
			leftButtonGroup: [
				{
					icon: 'icon-daohangfanhui',
					color: '#333'
				}
			],
			headerNavHeight: 0
		}
	},
	computed: {
		...mapGetters(['userId', 'userIdentity']),
		// 当前用户是否为协销
		isDealer() {
			return this.userIdentity === 2
		},
		tabInfo() {
			return this.tabs[this.currentTab]
		},
		loadMoreText() {
			if (this.tabInfo.orderList.length === 0) return '没有更多了'
			return this.tabInfo.hasMore ? '上拉加载更多' : '没有更多了'
		},
		emptyInfo() {
			const info = {}
			info.image = `${this.$Static}icon-empty-address.png`

			if (this.tabInfo.state === 0) {
				info.message = '您还没有任何的订单哟~_~'
			} else {
				info.message = '您还没有相关的订单哟~_~'
			}

			return info
		},
		swiperHeight(){
			let offset  = 44
			if(this.isDealer){
				offset = 84
			}
			return {
				height: `calc(100vh - ${offset}px - ${this.headerNavHeight}px);`
			}
		}
	},
	onLoad(options) {
		this.currentTab = options.state
		this.fetchOrderData()
		this.$on('orderAction', () => {
			this.resetOrderList()
		})
	},
	// 下拉刷新
	onPullDownRefresh() {
		this.resetOrderList()
	},
	beforeDestroy() {
		this.$off('orderAction')
	},
    
    
	methods: {
		// 导航栏初始化
		headerNavInit(info){
			this.headerNavHeight = info.height
		},
		// 导航栏点击事件
		handleLeftClick(e) {
			if (e.index) {
				uni.switchTab({ url: '/pages/tabBar/index/index' })
			} else {
				uni.navigateBack({ delta: 1 })
			}
		},
		handleRightClick() {
			uni.navigateTo({ url: '/pages/order/order-search' })
		},

		// 重置订单列表
		resetOrderList() {
			this.refresh = true
			this.tabInfo.pageNum = 1
			this.fetchOrderData()
		},

		// 更新订单列表
		updateOrderList(response) {
			const { name, state, pageNum } = this.tabInfo
			this.$set(this.tabs, this.currentTab, {
				name,
				state,
				pageNum: pageNum + 1,
				orderList: this.tabInfo.orderList.concat(response.data.list),
				hasMore: response.data.hasNextPage
			})
		},

		// 获取订单列表 使用防抖函数封装
		fetchOrderData: debounce(function() {
			this.loadmore = true

			const params = {
				orderState: this.tabs[this.currentTab].state,
				userId: this.userId,
				orderType: this.screenTab,
				pageNum: this.tabInfo.pageNum,
				pageSize: 10
			}

			if (this.isDealer) {
				this.queryOrderDealerList(params)
			} else {
				this.queryOrderList(params)
			}
		}, 500),

		// 普通用户获取订单列表
		queryOrderList(params) {
			this.OrderService.QueryOrderList(params)
				.then(res => {
					if (this.refresh) this.tabInfo.orderList = []
					this.updateOrderList(res)
				})
				.catch(err => {
					console.log(err)
				})
				.finally(() => {
					uni.stopPullDownRefresh()
					this.refresh = false
					this.loadmore = false
					this.isRequest = false
				})
		},

		// 分销者获取订单列表
		queryOrderDealerList(params) {
			console.log(params)
			this.OrderService.QueryOrderDealerList(params)
				.then(res => {
					if (this.refresh) this.tabInfo.orderList = []
					this.updateOrderList(res)
				})
				.catch(err => {
					console.log(err)
				})
				.finally(() => {
					uni.stopPullDownRefresh()
					this.refresh = false
					this.loadmore = false
					this.isRequest = false
				})
		},

		// 筛选订单
		handleFilter(e) {
			console.log(e.index)
			this.screenTab = e.index
			this.resetOrderList()
			this.fetchOrderData()
		},

		// 跳转详情
		handleToDetail(orderInfo) {
            // 如果是拼单商品订单
            // do something
            // 如果是普通订单
			this.$api.navigateTo('/pages/order/order-detail?orderId=' + orderInfo.orderId)
		},

		// 滚动到底部
		scrollBottom() {
			if (!this.tabInfo.hasMore) return
			this.fetchOrderData()
		},

		// tab切换
		tabChange(e) {
			this.currentTab = e.index
		},

		// 轮播切换
		swiperChange(e) {
			this.currentTab = e.detail.current
			if (this.tabInfo.pageNum !== 1) return
			this.isRequest = true
			this.fetchOrderData()
		}
	}
}
</script>

<style lang="scss" scoped>
.order-list {
	min-height: 100vh;
	background: #f7f7f7;

	.tabs {
		position: relative;
		z-index: 100000;
	}

	.swiper {
		&.swiper-hegiht1 {
			height: calc(100vh - 44px);
		}

		&.swiper-hegiht2 {
			height: calc(100vh - 84px);
		}

		.scroll-box {
			height: 100%;
		}
	}

	.grid {
		height: 20rpx;
		background: #f7f7f7;
	}

	.order-section {
		padding: 38rpx 0;
		background-color: #fff;

		.line {
			width: 702rpx;
			height: 1px;
			background: #f7f7f7;
		}

		.order-info {
			position: relative;
			padding: 0 24rpx;
			margin-bottom: 32rpx;
			line-height: 1.6;

			.order-num,
			.order-time {
				font-size: 26rpx;
				color: #333333;

				.label {
					color: #999999;
				}
			}

			.status {
				position: absolute;
				font-size: 26rpx;
				color: #ff457b;
				right: 24rpx;
				bottom: 0;
			}
		}

		.origin {
			padding: 0 24rpx;
			margin-top: 24rpx;
			margin-bottom: 16rpx;
			display: flex;
			justify-content: flex-start;
			align-items: center;

			.cover {
				width: 56rpx;
				height: 56rpx;
				border-radius: 4rpx;
				border: 1px solid #f7f7f7;
				box-sizing: border-box;
			}

			.name {
				margin-left: 16rpx;
				font-size: 30rpx;
				color: #333333;
				font-weight: bold;
			}
		}

		.goods-list {
			.order-goods {
				padding-top: 32rpx;
				&:first-child {
					padding-top: 0;
				}
			}
		}

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

			padding: 0 24rpx;
			margin: 32rpx 0;

			font-size: 26rpx;
			color: #333333;

			.count {
				font-weight: bold;
			}

			.status {
				color: #ff457b;

				.label {
					color: #333333;
				}
			}
		}
	}
}
</style>
