<template>
	<view class="digitShelf-pagesCons">
		<view class="tab-body">
			    <view>
					<u-tabs-swiper ref="uTabs" :list="tabList" :offset="[5,40]" bar-width='100' active-color="#1283d4" name="dispName" :current="current" @change="tabsChange" :is-scroll="false"
					 swiperWidth="750"></u-tabs-swiper>
				</view>
				<swiper class="check-list" :current="swiperCurrent" @transition="transition" @change="swiperChange" @animationfinish="animationfinish">
					<swiper-item class="swiper-item" style="height: 100%;width: 100%;overflow: hidden;" v-for="(tabs, indexs) in tabList" :key="indexs">
						<scroll-view scroll-y style="height: 100%;width: 100%;overflow: auto;" @scrolltolower="onreachBottom" v-if="swiperCurrent == indexs">
							<view  
							class="check-order-list" 
							v-for="(item,index) in list" 
							:key="item.id" 
							 @click="viewRow(item)"
							>
								<view class="check-row align_center justify_between">
									<view class="orderNo">{{item.purchaseNo}}</view>
									<view class="times">
										<span v-if="item.billStatus == 'WAIT_AUDIT'&&item.payOnlineFlag==0">待审核</span>
										<view v-if="item.billStatus == 'WAIT_PAY'" class="waitPay">
											<text>待付款</text>
											<view style="padding:0 5px;">
												<u-count-down separator="zh" :separator-size="24" bg-color="none" :timestamp="item.timestamp" :show-days="false" :show-hours="false"></u-count-down>
											</view>
										</view>
										<span v-if="item.billStatus == 'AUDIT_REJECT'">审核不通过</span>
										<span v-if="item.billStatus == 'WAIT_OUT_WAREHOUSE' || item.billStatus == 'WAIT_RECEIVE'">待收货</span>
										<span v-if="item.billStatus == 'FINISH'">已完结</span>
										<span v-if="item.billStatus == 'CANCEL'">已取消</span>
									</view>
								</view>
								 <view class="check-row">
									 <view v-if="item.totalCategory>1" class="check-row-left">
										 <scroll-view style="width: 100%;white-space: nowrap;" scroll-x="true">
											 <view class="img-item" v-for="item in item.productList" :key="item.id">
											 	 <image :src="item.images||'/static/def_imgs.png'" style="width: 100%;height: 100%;"></image>
											 </view>
										 </scroll-view>
									 </view>
									 <view v-else class="check-row-left">
										 <view class="img-item">
										 	 <image :src="item.productList&&item.productList[0].images||'/static/def_imgs.png'" style="width: 100%;height: 100%;"></image>
										 </view>
										 <view class="product-info">
											<text class="ellipsis-two">{{item.productList&&item.productList[0].productName ||'--'}}</text>
											<text class="ellipsis-one">{{item.productList&&item.productList[0].code||''}}</text>
											<text class="ellipsis-one">{{item.productList&&item.productList[0].origCode||''}}</text>
										 </view>
									 </view>
									 <view :class="item.totalCategory>1?'check-row-right check-row-right-fixed':'check-row-right'">
										 <view>￥<text class="price">{{priceStr(item.totalAmount)[0]}}</text>.{{priceStr(item.totalAmount)[1]}}</view>
										 <view><text class="nums">共{{item.totalQty}}件</text></view>
									 </view>
								 </view>
								 <view class="check-row">
									 <view class="times">
										 {{item.createDate}}
									 </view>
									 <view style="text-align: right;color: #999;">
										 <u-button style="margin-left: 10px;" v-if="item.billStatus == 'WAIT_AUDIT'" size="mini" shape="round" type="default" plain @click="cancelOrder(item)">取消订单</u-button>
										 <u-button style="margin-left: 10px;" v-if="item.billStatus == 'WAIT_PAY'" size="mini" shape="round" type="error" plain @click="payOrder(item)">立即支付</u-button>
										 <!-- <u-button style="margin-left: 10px;" v-if="item.billStatus == 'CANCEL'" size="mini" shape="round" type="error" plain @click="buyAgain(item)">再次购买</u-button> -->
										 <u-button style="margin-left: 10px;" v-if="item.billStatus == 'WAIT_RECEIVE'" size="mini" shape="round" type="error" plain @click="receiveOrder(item)">确认收货</u-button>
									 </view>
								 </view>
							 </view>
							 <view style="padding: 20upx;">
								 <u-empty :src="`/static/nodata.png`" icon-size="180" :text="noDataText" img-width="120" v-if="list.length==0 && status!='loading'" mode="list"></u-empty>
								 <u-loadmore v-if="(total>=list.length&&list.length)||status=='loading'" :status="status" />
							 </view>
						</scroll-view>
					</swiper-item>
				</swiper>
		</view>
		<!-- 付款弹框 -->
		<payModal :showPopu="showPopu" :payInfo="payInfo" :payData="payData" @close="showPopu=false" @payComplete="payComplete"></payModal> 
	</view>
</template>

<script>
	import { purchaseQueryPage,purchaseCancel,purchaseReceive,purchasePay } from '@/api/purchase.js'
	import payModal from '../components/payModal.vue'
	export default {
		components:{
			payModal
		},
		data() {
			return {
				status: 'loading',
				noDataText: '暂无数据',
				showPopu: false,
				tabList: [
					  {
						  dispName: '全部',
						  typeId: 1,
						  count: 0
					   },
					   {
					     dispName: '待付款',
					   	typeId: 2,
					   	count: 0
					   },
					  {
					    dispName: '待收货',
					  	typeId: 3,
						count: 0
					  },
					  {
					    dispName: '已完结',
					  	typeId: 4,
						count: 0
					  },
					  {
					    dispName: '已取消',
					  	typeId: 5,
					  	count: 0
					  },
					  {
					    dispName: '审核不通过',
					  	typeId: 6,
					  	count: 0
					  },
				  ],
				current: 1,
				swiperCurrent: 1,
				// 查询条件
				pageNo: 1,
				pageSize: 10,
				list: [],
				total: 0,
				payData: null
			}
		},
		computed: {
			// 付款信息
			payInfo(){
				return this.$store.state.vuex_tempOrderData
			}
		},
		onLoad() {
			let _this = this
			_this.pageInit()
			uni.$on('refreshPurcaOrder',function(data, state){
				 _this.resetList(data,state)
			})
		},
		methods:{
			message(title){
				uni.showToast({
					icon:'none',
					title: title
				})
			},
			priceStr: function(value) {
				const str = Number(value).toFixed(2).split('.')
				return str;
			},
			// 刷新列表
			resetList(item,state){
				// 全部列表，改变状态
				if(this.swiperCurrent==0){
					item.billStatus = state
					this.list.splice()
				}else{
					// 其它列表，删除当前操作的订单
					const index = this.list.findIndex((key)=>key.purchaseSn == item.purchaseSn)
					if(index>-1){
						this.list.splice(index,1)
					}
				}
			},
			pageInit(){
				this.total = 0
				this.pageNo = 1
				this.getRow()
			},
			// tabs通知swiper切换
			tabsChange(index) {
				if(index != this.swiperCurrent && this.status !='loading'){
					this.list = []
					this.status = "loading"
					this.swiperCurrent = index;
				}
			},
			swiperChange(event){
				this.list = []
				this.status = "loading"
				this.swiperCurrent = event.detail.current
			},
			// swiper-item左右移动，通知tabs的滑块跟随移动
			transition(e) {
				let dx = e.detail.dx;
				this.$refs.uTabs.setDx(dx);
			},
			// 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
			// swiper滑动结束，分别设置tabs和swiper的状态
			animationfinish(e) {
				let current = e.detail.current;
				if(current != this.current){
					this.$refs.uTabs.setFinishCurrent(current);
					this.swiperCurrent = current;
					this.current = current;
					this.pageInit()
				}
			},
			// scroll-view到底部加载更多
			onreachBottom() {
				if(this.list.length < this.total){
					this.pageNo += 1
					this.getRow()
				}else{
					this.status = "nomore"
				}
			},
			// 取消订单
			cancelOrder(item){
				let _this = this
				uni.showModal({
					title: '提示',
					content: '确定取消订单吗？',
					success: function (res) {
						if (res.confirm) {
							purchaseCancel({purchaseSn:item.purchaseSn}).then(res => {
								if (res.status == 200) {
									_this.message('取消成功')
									_this.resetList(item,'CANCEl')
								} else {
									_this.message(res.message)
								}
							})
						}
					}
				});
			},
			// 立即支付
			payOrder(item){
				this.$store.state.vuex_tempOrderData = item
				purchasePay({
					bizSn:item.purchaseSn,
					bizNo:item.purchaseNo,
					bizType:'PURCHASE',
					payUserOpenId: this.$store.state.vuex_openid || uni.getStorageSync('openid')
				}).then(res=>{
					this.showPopu = true
					this.payData = res.data?res.data.payRequestRest:null
				})
			},
			// 付款成功,isOk: false 取消支付或支付失败，true 支付完成
			payComplete(item,isOk){
				this.showPopu = false
				if(isOk){
					item.payOnlineFlag = 0
					item.billStatus = 'WAIT_AUDIT'
					this.viewRow(item)
					setTimeout(()=>{
						this.resetList(item,'WAIT_AUDIT')
					},150)
				}
			},
			// 再次购买
			buyAgain(item){
				 
			},
			// 确认收货
			receiveOrder(item){
				let _this = this
				uni.showModal({
					title: '提示',
					content: '确定收货吗？',
					success: function (res) {
						if (res.confirm) {
							purchaseReceive({purchaseSn:item.purchaseSn}).then(res => {
								if (res.status == 200) {
									_this.message('收货成功')
									_this.resetList(item,'FINISH')
								} else {
									_this.message(res.message)
								}
							})
						}
					}
				});
			},
			// 查询列表
			getRow (pageNo) {
			  let _this = this
			  if (pageNo) {
			    this.pageNo = pageNo
			  }
			  let params = {
			    pageNo: this.pageNo,
			    pageSize: this.pageSize,
			  }
			  // 状态条件
			  // 待付款
			  if(this.swiperCurrent == 1){
				 params.billStatusList = ['WAIT_AUDIT']
			  }
			  // 待收货
			  if(this.swiperCurrent == 2){
				  params.billStatusList = ['WAIT_AUDIT','WAIT_OUT_WAREHOUSE','WAIT_RECEIVE']
			  }
			  // 已完成
			  if(this.swiperCurrent == 3){
				  params.billStatusList = ['FINISH']
			  }
			  // 已取消
			  if(this.swiperCurrent == 4){
			  	  params.billStatusList = ['CANCEL']
			  }
			  // 未审核通过
			  if(this.swiperCurrent == 5){
			  	  params.billStatusList = ['AUDIT_REJECT']
			  }
			  this.status = "loading"
			  purchaseQueryPage(params).then(res => {
				if (res.code == 200 || res.status == 204 || res.status == 200) {
				  let list = res.data.list || []
				  list.map(item => {
					  let now = new Date(item.purchaseDate)
					  now.setMilliseconds(now.getMilliseconds() + 30 * 60 * 1000)
					  item.timestamp = now.getTime()
					  item.billStatus = item.billStatus == 'WAIT_AUDIT'&&item.payOnlineFlag==1&&item.payInfo&&item.payInfo.payState=='WAIT'?'WAIT_PAY':item.billStatus
				  })
				  // 待收款
				  if(_this.swiperCurrent==1){
					  list = list.filter(item => {
						  return item.billStatus == 'WAIT_PAY'
					  })
				  }
				  if(_this.pageNo>1){
					  _this.list = _this.list.concat(list)
				  }else{
					  _this.list = list
				  }
				  
				  _this.total = res.data.count || 0
				  // 待收货
				  if(_this.swiperCurrent == 2){
					  _this.tabList[2].count = _this.total
				  }
				  
				} else {
				  _this.list = []
				  _this.total = 0
				  _this.noDataText = res.message
				}
				_this.status = _this.total>=_this.list.length ? "nomore" : 'loadmore'
			  })
			},
			// 详细页
			viewRow(item){
				this.$store.state.vuex_tempOrderData = item
				uni.navigateTo({
					url: "/pagesB/procureOrder/orderDetail?purchaseSn="+item.purchaseSn+"&state="+item.billStatus
				})
			}
		}
	}
</script>

<style lang="scss">
	page{
		height: 100%;
	}
	.digitShelf-pagesCons{
		height: 100%;
		display: flex;
		flex-direction: column;
		.tab-body{
			.check-list{
				height: calc(100vh - 44px);
			}
			.check-order-list{
				background: #ffffff;
				padding: 10upx 20upx;
				margin: 20upx;
				border-radius: 20upx;
				box-shadow: 1px 1px 3px #EEEEEE;
				.check-row{
					display: flex;
					font-size: 28upx;
					position: relative;
					&:first-child{
						color: #666E75;
						font-size: 24upx;
						padding: 20upx 0;
						.orderNo{
							font-size: 28upx;
							color: #222222;
							margin-top: -6upx;
							flex-grow: 1;
						}
					}
					&:last-child{
						align-items: center;
						justify-content: space-between;
						padding: 20upx 0;
					}
					.times{
						text-align: right;
						font-size: 24upx;
					}
					> view{
						 .price{
							 color: #666;
							 font-size: 28upx;
							 font-weight: bold;
						 }
						 .nums{
						 	font-size: 24upx;
						 	color: #666;
						 }
						 .waitPay{
						 	background: #f9e4e4;
						 	border-radius: 30px;
							display: flex;
							align-items: center;
						 	text{
						 		color: #fff;
								padding: 3px 5px;
						 		&:first-child{
						 			background: #ff0000;
									border-radius: 30rpx 0 20rpx 30rpx;
									font-size: 24rpx;
						 		}
						 		&:last-child{
						 			font-size: 20rpx;
									color: #ff0000;
						 		}
						 	}
						 }
					}
					.check-row-left{
						display: flex;
						align-items: center;
						flex-grow:1;
						width: 50%;
					}
					.img-item{
						display: inline-block;
						width: 160rpx;
						height: 160rpx;
						background: #f8f8f8;
						border-radius: 5px;
						margin-right: 5px;
					}
					.product-info{
						flex-grow: 1;
						width: 60%;
						padding:0 5px;
						> text{
							&:last-child{
								margin-top: 5px;
								display: inline-block;
								color: #2196F3;
								width: 100%;
							}
						}
					}
					.check-row-right-fixed{
						position: absolute;
						top: 0;
						right:0;
					}
					.check-row-right{
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: flex-end;
						padding:0 5px;
						height: 160rpx;
						min-width: 100rpx;
						text-align: right;
						font-size: 10px;
						background: rgba(255,255,255,0.9);
					}
					.finish{
						background-color: #2d8cf0;
					}
					.del{
						color: #666;
						border:2rpx solid #EDEDED;
						background: none;
					}
				}
			}
		}
	}
</style>
