<template>
	<view class="order-search">
		<tui-skeleton v-if="isRequest" loadingType="2"></tui-skeleton>
		<!-- 搜索框 -->
		<view class="order-top">
			<cm-search
				v-model="keyword"
				@search="handleSearch"
				placeholder="请输入搜索关键字"
				:keywordVisible="keywordVisible"
				:keywordList="keywordList"
				@focus="keywordVisible = true"
				@clear="keywordVisible = true"
				@remove="removeKeywordModal = true"
			></cm-search>
		</view>

		<!-- orderList.length === 0 -->
		<view class="order-empty" v-if="orderList.length === 0">
			<cm-empty :image="emptyInfo.image" :message="emptyInfo.message" :offset="100"></cm-empty>
		</view>
		<view class="order-list" v-else>
			<template v-for="(orderInfo, orderIndex) in 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'].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>
		</view>
		<!-- loading -->
		<view class="loading-more" v-if="orderList.length > 0">
			<tui-loadmore :index="3" :visible="loadmore"></tui-loadmore>
			<tui-nomore :text="loadMoreText" :visible="!loadmore" backgroundColor="#f7f7f7"></tui-nomore>
		</view>

		<!-- 操作弹窗 -->
		<tui-modal
			:show="modal"
			:content="modalText"
			:size="32"
			:maskClosable="false"
			color="#333"
			shape="circle"
			@click="handleModalConfirm"
		></tui-modal>
		<!-- 加载框 -->
		<cm-loading :visible="isSubLoading" :text="loadingText"></cm-loading>
		<!-- 失效商品列表 -->
		<cm-order-invalid-modal
			:goodsList="invalidList"
			:visible="buyAgainModal"
			@confirm="buyAgainModalClick"
			@cancel="buyAgainModalHide"
		></cm-order-invalid-modal>
		<!-- 操作弹窗 -->
		<tui-modal
			:show="removeKeywordModal"
			content="确认清空搜索历史记录？"
			:size="32"
			:maskClosable="false"
			color="#333"
			shape="circle"
			@click="clearSearchRecord"
		></tui-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 CmLoading from '@/components/cm-module/cm-loading/cm-loading.vue'
import CmEmpty from '@/components/cm-module/cm-empty/cm-empty.vue'
import CmSearch from '@/components/cm-module/cm-search/cm-search.vue'

import { debounce } from '@/common/common.js'
import orderMixins from './mixins/orderList.js'
import wechatPay from './mixins/wechatPay.js'
import { mapGetters } from 'vuex'

export default {
	mixins: [orderMixins, wechatPay],
	components: {
		CmSearch,
		CmOrderProdcut,
		CmOrderControlNav,
		CmOrderInvalidModal,
		CmEmpty,
		CmLoading
	},
	data() {
		return {
			isRequest: false,
			keywordVisible: true,
			keywordList: [],
			keyword: '',
			pageNum: 1,
			hasMore: false,
			loadmore: false, // 正在加载更多
			orderList: [],

			refresh: false,
			removeKeywordModal: false
		}
	},
	computed: {
		...mapGetters(['userId', 'userIdentity']),
		// 当前用户是否为协销
		isDealer() {
			return this.userIdentity === 2
		},
		// 上拉加载文案
		loadMoreText() {
			if (this.orderList.length === 0) return '没有更多了'
			return this.hasMore ? '上拉加载更多' : '没有更多了'
		},
		// 列表为空
		emptyInfo() {
			const info = {}
			info.image = `${this.$Static}icon-empty-address.png`
			info.message = '未找到相关订单~_~'
			
			if(this.keywordList.length <= 0){
				info.message = '暂无任何搜索历史记录~_~'
			}
			
			return info
		}
	},
	watch: {
		keywordVisible(nVal){
			if(!nVal) return
			this.fetchSerachRecord()
			this.orderList = []
		}
	},
	onReachBottom() {
		if (!this.hasMore) return
		this.fetchOrderData()
	},
	onLoad() {
		setTimeout(() => {
			this.fetchSerachRecord()
		}, 2000)
		this.$on('orderAction', () => {
			this.resetOrderList()
		})
	},
	beforeDestroy() {
		this.$off('orderAction')
	},
	methods: {
		handleSearch() {
			this.keywordVisible = false
			this.isRequest = true
			this.resetOrderList()
		},
		// 跳转详情
		handleToDetail(orderInfo) {
			this.$api.navigateTo('/pages/order/order-detail?orderId=' + orderInfo.orderId)
		},
		// 获取订单列表 使用防抖函数封装
		fetchOrderData: debounce(function() {
			this.loadmore = true

			const params = {
				searchWord: this.keyword,
				// orderState: 0,
				// orderType: 0,
				userId: this.userId,
				pageNum: this.pageNum,
				pageSize: 10
			}

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

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

		// 分销者获取订单列表
		// queryOrderDealerList(params) {
		// 	this.OrderService.QueryOrderDealerList(params)
		// 		.then(res => {
		// 			if (this.refresh) this.orderList = []
		// 			this.updateOrderList(res)
		// 		})
		// 		.catch(err => {
		// 			console.log(err)
		// 		})
		// 		.finally(() => {
		// 			this.refresh = false
		// 			this.loadmore = false
		// 			this.isRequest = false
		// 		})
		// },
		
		// 机构搜索订单列表
		searchOrderInfo(params){
			this.OrderService.SearchOrderInfo(params)
				.then(res => {
					if (this.refresh) this.orderList = []
					this.updateOrderList(res)
				})
				.catch(err => {
					console.log(err)
				})
				.finally(() => {
					this.refresh = false
					this.loadmore = false
					this.isRequest = false
				})
		},
		
		// 更新订单列表
		updateOrderList(response) {
			this.pageNum++
			this.orderList = this.orderList.concat(response.data.list)
			this.hasMore = response.data.hasNextPage
		},
		// 重置订单列表
		resetOrderList() {
			this.refresh = true
			this.pageNum = 1
			this.fetchOrderData()
		},
		// 获取搜索历史
		async fetchSerachRecord() {
			try {
				const res = await this.OrderService.SearchOrderHistory({ userId: this.userId })
				this.keywordList = res.data
			} catch (error) {
				this.$util.msg(error.msg, 2000)
			}
		},
		// 清空搜索历史
		async clearSearchRecord(e) {
			if (!e.index) return (this.removeKeywordModal = false)
			try {
				await this.OrderService.ClearOrderHistory({ userId: this.userId })
				await this.fetchSerachRecord()
				this.removeKeywordModal = false
				this.$util.msg('已清空搜索历史记录', 2000)
			} catch (error) {
				this.$util.msg(error.msg, 2000)
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.order-search {
	min-height: 100vh;
	background: #f7f7f7;
	overflow: hidden;
	padding-top: 90rpx;
	box-sizing: border-box;
}

.order-top {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	z-index: 100000;
}

.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>
