<template>
	<view class="digitShelf-pagesCons">
		<view class="tab-body">
			    <view>
					<u-tabs-swiper 
					ref="uTabs" 
					:list="tabList" 
					:offset="[5,5]" 
					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'">待审核</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" @end="countDownEnd(item)"></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="pitem in item.productList" :key="pitem.id">
											 	 <image :src="pitem.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'||item.billStatus == 'WAIT_PAY'" 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 v-if="(item.billStatus == 'CANCEL'||item.billStatus == 'AUDIT_REJECT')&&item.payInfo">
											<u-tag type="success" size="mini" v-if="item.payInfo.refundState=='FINISH'" mode="plain" text="已退款" shape="square"/>
											<u-tag type="primary" size="mini" v-else-if="item.payInfo.refundState=='WAIT'" text="退款中" shape="square" mode="plain"/>
											<u-tag type="error" size="mini" v-else text="退款失败" shape="square" mode="plain"/>
										 </view>
									 </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,
				current: 0,
				swiperCurrent: 0,
				// 查询条件
				pageNo: 1,
				pageSize: 10,
				list: [],
				total: 0,
				payData: null
			}
		},
		computed: {
			// 货架经销商信息
			shelfInfo(){
				return this.$store.state.vuex_storeShelf
			},
			//是否开启线上支付
			hasPay(){
				const shelfInfo = this.shelfInfo
				return shelfInfo&&shelfInfo.payOnlineFlag&&shelfInfo.payOnlineFlag=='1'
			},
			// 付款信息
			payInfo(){
				return this.$store.state.vuex_tempOrderData
			},
			tabList(){
				const arr = [
					  {
						  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
					  },
				  ]
				// 如果没有开通支付  
				if(!this.hasPay){
					arr.splice(1,1)
				}  
				return arr
			}
		},
		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){
				// 其它列表，删除当前操作的订单
				const index = this.list.findIndex((key)=>key.purchaseSn == item.purchaseSn)
				// 全部列表，改变状态
				if(this.swiperCurrent==0){
					purchaseQueryPage({pageNo:1,pageSize:1,purchaseSn: item.purchaseSn}).then(res => {
						const data = res.data ? res.data.list[0] : null
						if(data){
							data.billStatus = data.billStatus == 'WAIT_AUDIT'&&data.payOnlineFlag==1&&data.payInfo&&data.payInfo.payState=='WAIT'?'WAIT_PAY':data.billStatus
							this.list.splice(index,1,data)
						}
					})
				}else{
					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: !item.payOk ? '确定取消订单吗？':'取消后订单金额将于1-3个工作日到账（原路返回）？',
					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){
				const _this = this
				this.$store.state.vuex_tempOrderData = item
				uni.showLoading({
					title: '加载中...'
				})
				purchasePay({
					bizSn:item.purchaseSn,
					bizNo:item.purchaseNo,
					bizType:'PURCHASE',
					payUserOpenId: this.$store.state.vuex_openid || uni.getStorageSync('openid')
				}).then(res=>{
					uni.hideLoading()
					if(res.status == 200){
						this.showPopu = true
						this.payData = res.data?res.data.payRequestRest:null
					}else{
						if(res.data.errorCode == 'VALIDATE_F_00001'){
							uni.showModal({
								showCancel:false,
								title: '提示',
								content: '下单人员与支付人员不一致，请在订单详情核实后再支付',
								success: function (res) {
									if (res.confirm) {
										_this.viewRow(item)
									}
								}
							});
						}
					}
				})
			},
			// 付款成功,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){
				 
			},
			// 订单超时
			countDownEnd(item){
				item.payInfo = null
				this.resetList(item,'CANCEL')
			},
			// 确认收货
			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 && this.hasPay){
				 params.billStatusList = ['WAIT_AUDIT']
			  }
			  const tab = this.hasPay ? this.swiperCurrent : this.swiperCurrent + 1
			  // 待收货
			  if(tab == 2){
				  params.billStatusList = ['WAIT_AUDIT','WAIT_OUT_WAREHOUSE','WAIT_RECEIVE']
			  }
			  // 已完成
			  if(tab == 3){
				  params.billStatusList = ['FINISH']
			  }
			  // 已取消
			  if(tab == 4){
			  	  params.billStatusList = ['CANCEL']
			  }
			  // 未审核通过
			  if(tab == 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 => {
					  item.billStatus = item.billStatus == 'WAIT_AUDIT'&&item.payOnlineFlag==1&&item.payInfo&&item.payInfo.payState=='WAIT'?'WAIT_PAY':item.billStatus
					  // 计算待付款剩余倒计时
					  if(item.billStatus== 'WAIT_PAY'){
					  	item.timestamp = (new Date(item.createDate.replace(/-/g,'/')).getTime() + 1800000 - new Date().getTime())/1000
					  }
					  item.payOk = item.payOnlineFlag==1&&item.payInfo&&item.payInfo.payState=='FINISH'
				  })
				  
				  // 只显示待付款
				  if(_this.hasPay&&this.swiperCurrent == 1){
					  list = list.filter(item => item.billStatus== 'WAIT_PAY')
				  }
				  // 待收货里去除待付款
				  if(_this.hasPay&&this.swiperCurrent == 2 || !_this.hasPay&&this.swiperCurrent == 1){
				  	  list = list.filter(item => item.billStatus!= 'WAIT_PAY')
				  }
				  
				  _this.list = _this.list.concat(list)
				  _this.total = res.data.count || 0
				  
				  // 待收货或待付款显示总数
				  if(_this.swiperCurrent == 1){
					  // _this.tabList[_this.swiperCurrent].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
				})
			}
		}
	}
</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;
						border: 1px solid #eee;
						overflow: hidden;
					}
					.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>
