<template>
	<div id="pendingOrderBox">
		<van-dialog id="contactBTN" />
		<van-toast id="van-toast" />
		<van-toast id="custom-selector" />
		<div class="switTab">
			<div :class="activeTab==1?'active':''" @click="changeTab(1);">待支付</div><span style='color:#EEEEEE;'>|</span>
			<div :class="activeTab==2?'active':''" @click="changeTab(2);">还款历史</div>
			<p :style="activeTab==2?'left:70vw;':''" class="underLine"></p>
		</div>
		<div class="orderListBox">
			<ul v-if="activeTab == 1" class="ulList" v-for="(item,index) in orderList" :key="index">
				<li class="titileName" style="border-bottom:1rpx solid #EEEEEE;">订单时间：{{item.ordertime}}</li>
				<li class="liCenter" @click="getChecked(index,item)">
					<div style="width:66%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;">
						<span>
							<!-- <img class="checkImg" v-if="item.checked" src="@static/images/choice.png" alt="" /> -->
							<!-- <span class="noChoice" v-else></span> -->
						</span>
						<span style="color:#000;font-size:30rpx;">{{item.businessname}}</span>
					</div>
					<div style="text-align:right;padding-right:30rpx;width:30%;">
						￥<span style="color:#000;font-size:53rpx;">{{item.realPay}}</span>
					</div>
				</li>
				<li class="titileName" style="color:#04B871;text-align:center;" @click="toDetailFun(item)">查看订单详情</li>
			</ul>
			<div v-if='activeTab == 1 && orderList.length==0&&manualrepay==1' class="noCostInfo">
				<image :src="ImgUrl+'xzf/noData-01.png'" mode='widthFix' />
				<p>没有欠款订单~</p>
			</div>
			<div v-if="activeTab==1 && orderList.length>0 && manualrepay==1" class="bottomFixed">
				<div @click="CheckedAllFun" v-if="false">
					<img v-if="isAllChecked" class="checkImg" src="@static/images/choice.png" alt="" />
					<span v-else class="noChoice"></span>
					<span style="font-weight:bold;font-size:30rpx;">全选</span>
				</div>
				<div style="color:#888888;font-size:28rpx;text-align:right;width:50vw;">合计支付金额：<span
						style='color:#FF1722;font-size:35rpx;'>￥{{totalAmount}}</span></div>
				<button style="margin-top:30rpx;font-size:32rpx;" @click="ToPayOrderFun">支付</button>
			</div>
			<scroll-view v-if="activeTab == 2" class="sc" scroll-y="true">
				<ul class="ulList" v-for="(item,index) in orderHistory" :key="index">
					<li class="titileName" style="display:flex;border-bottom:1rpx solid #EEEEEE;">
						<div style="text-align:left;width:70%;">扣款时间：{{item.pay_time}}</div>
						<div style="text-align:right;width:30%;margin-right:30rpx;"
							:style="item.handle_status==1?'color:#04B872;':'color:red;'">
							{{item.handle_status==1?'还款成功':'还款失败'}}
						</div>
					</li>
					<li class="liCenter">
						<div style="width:66%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;">
							<span style="color:#000;font-size:30rpx;">商户：{{item.bus_name}}</span>
						</div>
						<div style="text-align:right;padding-right:30rpx;width:30%;">
							￥<span style="color:#000;font-size:53rpx;">{{item.amount}}</span>
						</div>
					</li>
					<li class="titileName" style="color:#04B871;text-align:center;" @click="toDetailFun(item)">查看详情</li>
				</ul>
			</scroll-view>
			<div v-if='activeTab == 2 && orderHistory.length==0' class="noCostInfo">
				<image :src="ImgUrl+'xzf/noData-05.png'" mode='widthFix' />
				<p>暂无还款历史~</p>
			</div>
		</div>
	</div>
</template>
<script>
	import {
		Dialog,
		Toast
	} from 'vant';
	export default {
		data() {
			return {
				bindUserInfo: {},
				activeTab: 1, // 1 还款  2 历史
				isAllChecked: false, //是否全选
				checkedLength: 0, //选中的多少条订单
				totalAmount: 0, //合计支付金额
				walletAmount: 0, //钱包余额
				toPayAmount: 0, //选择支付的金额
				toPayOrderNum: [], //支付的订单流水合集
				orderList: [],
				orderHistory: [],
				totalCount: 0, //总条数
				pagenum: 1,
				ImgUrl: this.$ImgUrl,
				// 20220113
				manualrepay: 1 //手动还款开关(0-关闭 1-开启)
			}
		},
		onShow() {
			let self = this;
			// self.orderList = [];
			// self.activeTab = 1;
			// self.orderHistory = [];
			// self.totalAmount = 0;
			// self.toPayOrderNum = [];
			// self.pagenum = 1;
			// self.totalCount = 0;
			// wx.getStorage({
			// 	key: 'bindUserInfo',
			// 	success(res) {
			// 		self.bindUserInfo = res.data;
			// 		// 20220113
			// 		self.getUserInfo(res.data.userinfo.id)
			// 	}
			// })
			// self.getOrderListInfo();
			// self.queryUserWallet();
		},
		methods: {
			//获取用户信息
			async getUserInfo(id) {
				try {
					const toast = Toast.loading({
						duration: 0, // 持续展示 toast
						forbidClick: true, // 禁用背景点击
						loadingType: 'spinner',
						selector: '#custom-selector'
					});
					let res = await this.$httpWX.post({
						url: "/wechat/svweapp/QueryPersonalInfo",
						data: {
							userid: id,
						}
					})
					toast.clear();
					if (res.code == 10000) {
						this.manualrepay = res.results.manualrepay
					} else {
						Toast(res.message)
					}
				} catch (err) {
					toast.clear();
					Toast(err.message);
				}
			},
			//支付
			ToPayOrderFun: function() {
				if (this.globalData.limitBtnSend) {
					// Toast('操作太频繁啦~')
					return
				} else {
					this.globalData.limitBtnSend = true;
					setTimeout(() => {
						this.globalData.limitBtnSend = false;
					}, 2000);
				}
				if (this.checkedLength == 0) {
					Toast('请先选择要支付的订单哦~')
					return
				}
				let self = this;
				const toast = Toast.loading({
					duration: 0, // 持续展示 toast
					forbidClick: true, // 禁用背景点击
					loadingType: 'spinner',
					selector: '#custom-selector'
				});
				self.toPayAmount = (self.totalAmount * 100).toFixed(0);
				console.log('钱包余额：' + self.walletAmount + '； 支付金额：' + self.toPayAmount)
				if (self.walletAmount > self.toPayAmount || self.walletAmount == self.toPayAmount) { //直接钱包平账
					toast.clear();
					self.CustomDeductionFun();
				} else { // 充值后平账
					toast.clear();
					self.$httpWX.post({ //
						url: "/wechat/svweapp/CustomDeductionPayCharge",
						data: {
							amount: (self.toPayAmount) * 1,
							devflownos: JSON.stringify(self.toPayOrderNum),
						}
					}).then(resp => {
						if (resp.code == "10000") {
							self.ordernumber = resp.results.ordernumber;
							var resorder = resp.results.orderdata;
							self.$httpWX.post({
								url: "/wechat/svweapp/Wechatunifiedorder",
								data: {
									owid: resorder.id,
									ipaddress: '127.0.0.1'
								}
							}).then(respv2 => {
								toast.clear()
								if (respv2.code == "10000") {
									var reqdata = respv2.results;
									wx.requestPayment({
										timeStamp: reqdata.timeStamp,
										nonceStr: reqdata.nonceStr,
										package: reqdata.packagestr,
										signType: reqdata.signType,
										paySign: reqdata.paySign,
										success(res) {
											const toast = Toast.loading({
												duration: 0, // 持续展示 toast
												forbidClick: true, // 禁用背景点击
												loadingType: 'spinner',
												selector: '#custom-selector'
											});
											setTimeout(res => {
												self.$httpWX.post({
													url: "/wechat/svweapp/QueryFinanceCharge",
													data: {
														ownumber: self
															.ordernumber + '',
													}
												}).then(res => {
													if (res.results) {
														toast.clear();
														self
															.CustomDeductionFun();
													} else {
														toast.clear();
														Toast(res.message);
													}
												}).catch(res => {
													toast.clear();
													Toast(res.message);
												})
											}, 2000)

										},
										fail(res) {
											if (res.errMsg == "requestPayment:fail cancel") {
												// Toast('用户取消支付');
												return;
											} else {
												Toast("请求付款失败..[" + res.errMsg + "]");
												return;
											}
										}
									})
								} else {
									Toast(respv2.message);
									return;
								}
							})
						} else {
							toast.clear()
							Toast(resp.message);
							return;
						}
					})
				}
			},
			changeTab: function(num) {
				console.log(111111111111111111111111)
				if (num == 1) {
					this.activeTab = 1;
				} else {
					this.activeTab = 2;
					this.orderHistory = [];
					this.pagenum = 1;
					this.totalCount = 0;
					this.getHistory();
				}
			},
			//自定义补扣
			CustomDeductionFun: function() {
				console.log(this.orderList)
				let self = this;
				let ordernosList = [];
				self.orderList.forEach(res => {
					if (res.checked) {
						ordernosList.push(res.devflowno);
					}
				})
				const toast = Toast.loading({
					duration: 0, // 持续展示 toast
					forbidClick: true, // 禁用背景点击
					loadingType: 'spinner',
					selector: '#custom-selector'
				});
				self.$httpWX.post({
					url: "/wechat/svweapp/CustomDeduction",
					data: {
						ordernos: JSON.stringify(ordernosList),
					}
				}).then(res => {
					toast.clear();
					if (res.code == 10000) {
						Dialog.alert({
							message: '系统已受理，预计1分钟左右还款成功，可前往“还款历史”查看还款状态，期间请勿重复提交还款订单。',
							confirmButtonText: '完成',
							selector: '#contactBTN'
						}).then(() => {
							const toast = Toast.loading({
								duration: 0,
								forbidClick: true,
								loadingType: 'spinner',
								selector: '#custom-selector'
							});
							setTimeout(res => {
								toast.clear();
								var url = `/pages/UserMain/main`;
								wx.reLaunch({
									url
								});
							}, 1000)
						});
					} else {
						Toast(res.message)
					}
				})
			},
			//查询用户钱包
			queryUserWallet: function() {
				const toast = Toast.loading({
					duration: 0, // 持续展示 toast
					forbidClick: true, // 禁用背景点击
					loadingType: 'spinner',
					selector: '#custom-selector'
				});
				this.$httpWX.post({
					url: "/wechat/svweapp/QueryPayAccwallInfo",
					data: {}
				}).then(res => {
					toast.clear();
					if (res.code == 10000) {
						this.walletAmount = res.results.walletinfo.amount;
					} else {
						Toast(res.message);
					}
				}).catch(response => {
					toast.clear();
					Toast(response.message)
				})
			},
			//单选
			getChecked: function(ind, item) {
				this.totalAmount = 0;
				this.toPayOrderNum = [];
				let judgeAllCheck = true;
				this.checkedLength = 0;
				this.orderList.forEach((res, index) => {
					if (ind == index) {
						this.orderList[index].checked = !this.orderList[index].checked;
					}
					if (this.orderList[index].checked) {
						this.totalAmount += this.orderList[index].realPay * 1;
						this.toPayOrderNum.push(this.orderList[index].devflowno);
						this.checkedLength += 1;
					}
					if (this.orderList[index].checked == false) {
						judgeAllCheck = false;
					}
				})
				this.totalAmount = this.totalAmount.toFixed(2);
				judgeAllCheck ? this.isAllChecked = true : this.isAllChecked = false;
			},
			//全选点击
			CheckedAllFun: function() {
				this.totalAmount = 0;
				this.toPayOrderNum = [];
				this.checkedLength = 0;
				if (this.isAllChecked) { //已经全选,取消全选
					this.orderList.forEach((res, index) => {
						this.orderList[index].checked = false;
					})
					this.isAllChecked = false;
				} else { //没有全选，全选
					this.orderList.forEach((res, index) => {
						this.orderList[index].checked = true;
						if (this.orderList[index].checked) {
							this.totalAmount += this.orderList[index].realPay * 1;
							this.toPayOrderNum.push(this.orderList[index].devflowno)
						}
					})
					this.checkedLength = this.orderList.length;
					this.totalAmount = this.totalAmount.toFixed(2);
					this.isAllChecked = true;
				}
			},
			//获取历史订单
			getHistory: function() {
				let self = this;
				const toast = Toast.loading({
					duration: 0, // 持续展示 toast
					forbidClick: true, // 禁用背景点击
					loadingType: 'spinner',
					selector: '#custom-selector'
				});
				self.$httpWX.post({
					url: "/wechat/svweapp/QueryDeductionRecordPage",
					data: {
						pageindex: self.pagenum,
						pagesize: 10
					}
				}).then(res => {
					toast.clear();
					if (res.code == 10000) {
						self.totalCount = res.results.count;
						res.results.backdata.forEach((res, index) => {
							res.dealtime = self.$Utils.GMTToStr(res.deal_time);
							res.amount = (res.amount / 100).toFixed(2);
							res.id = res.dev_flow_id; //欠款订单id转为订单id  详情页查询用
							res.pay_time = self.$Utils.GMTToStr(res.pay_time);
						})
						self.orderHistory = self.orderHistory.concat(res.results.backdata);
					} else {
						Toast(res.message)
					}
				})
			},
			//获取订单详情
			// getOrderInfo: function() {
			//     const toast = Toast.loading({
			//         duration: 0, // 持续展示 toast
			//         forbidClick: true, // 禁用背景点击
			//         loadingType: 'spinner',
			//         selector: '#custom-selector'
			//     });
			//     this.$httpWX.post({
			//         url: "/wechat/svweapp/QueryPaymentDetailById",
			//         data: {
			//             id: this.globalData.outerOrderInfo.id,
			//             year:this.globalData.outerOrderInfo.year
			//         }
			//     }).then(res => {
			//         toast.clear();
			//         if (res.code == 10000) {
			//             this.orderList.push(res.results);
			//             this.orderList.forEach((res,index)=>{
			//                 this.$set(this.orderList[index],'checked',true);
			//                 this.$set(this.orderList[index],'ordertime',res.dealtime);
			//                 this.$set(this.orderList[index],'realPay',((res.amount)/100).toFixed(2));
			//                 res.amount = (res.amount/100).toFixed(2);
			//                 // this.orderList[index].dealtime = res.dealtime.split('T')[0]+' '+(res.dealtime.split('T')[1]).split('+')[0];
			//                 this.totalAmount+=res.realPay*1;
			//             })
			//             this.checkedLength = this.orderList.length;
			//             this.totalAmount = this.totalAmount.toFixed(2);
			//             this.isAllChecked = true;
			//         }else{
			//             Toast(res.message)
			//         }
			//     })
			// },
			//跳转详情
			toDetailFun: function(item) {
				item.year = item.dealtime.split('-')[0];
				this.globalData.outerOrderInfo = item;
				this.globalData.tabTag = this.activeTab;
				var url = '/pages/consumeData/main';
				wx.navigateTo({
					url
				})
			},
			//获取订单列表
			getOrderListInfo: function() {
				const toast = Toast.loading({
					duration: 0, // 持续展示 toast
					forbidClick: true, // 禁用背景点击
					loadingType: 'spinner',
					selector: '#custom-selector'
				});
				this.$httpWX.post({
					url: "/wechat/svweapp/QueryToDoRepayment",
					data: {}
				}).then(res => {
					toast.clear();
					if (res.code == 10000) {
						this.orderList = res.results.backdata;
						this.orderList.forEach((res, index) => {
							this.$set(this.orderList[index], 'checked', true);
							this.$set(this.orderList[index], 'realPay', ((res.amount) / 100).toFixed(
								2));
							this.$set(this.orderList[index], 'ordertime', this.$Utils.GMTToStr(res
								.dealtime));
							res.amount = (res.amount / 100).toFixed(2);
							// this.orderList[index].dealtime = this.$Utils.GMTToStr(res.dealtime);
							this.totalAmount += res.realPay * 1;
							this.toPayOrderNum.push(res.devflowno);
						})
						this.checkedLength = this.orderList.length;
						this.totalAmount = this.totalAmount.toFixed(2);
						this.isAllChecked = true;
					} else {
						Toast(res.message)
					}
				})
			},
		},
		// 上拉加载，拉到底部触发
		onReachBottom() {
			// 到这底部在这里需要做什么事情
			if (this.activeTab == 2) {
				if (this.orderHistory.length < this.totalCount) {
					this.pagenum++;
					this.getHistory();
				} else if (this.orderHistory.length == this.totalCount) {
					Toast('没有更多了~');
				} else {
					console.log('数据错了！！！')
				}
			}

		},
		//下拉刷新
		onPullDownRefresh: function() {
			if (this.activeTab == 2) { //还款历史
				this.pagenum = 1;
				this.totalCount = 0;
				this.orderHistory = [];
				this.getHistory();
			} else { // 还款订单
				this.orderList = [];
				this.toPayOrderNum = [];
				this.totalAmount = 0;
				this.getOrderListInfo();
				this.queryUserWallet();
			}
			wx.stopPullDownRefresh()
		},
		onShareAppMessage: function() {
			return {
				path: `pages/index/main`
			}
		},
	}
</script>
<style lang="scss">
	#pendingOrderBox {
		.underLine {
			position: fixed;
			width: 40rpx;
			border-bottom: 5rpx solid #01BC73;
			top: 115rpx;
			border-radius: 5rpx;
			left: 21vw;
		}

		.checkImg {
			width: 32rpx;
			height: 32rpx;
			vertical-align: -5rpx;
			margin-right: 15rpx;
		}

		.noChoice {
			display: inline-block;
			width: 28rpx;
			height: 28rpx;
			margin-right: 15rpx;
			border-radius: 50%;
			background: #fff;
			vertical-align: -5rpx;
			border: 2rpx solid #01BC73;
		}

		.active {
			color: #01BC73;
			font-weight: bold;
		}

		.noCostInfo {
			width: 500rpx;
			margin: 10vh auto;
			text-align: center;
			color: #484C54;
			font-size: 30rpx;

			image {
				width: 500rpx;
				height: 255rpx;
				margin-bottom: 3vh;
			}
		}

		.switTab {
			height: 118rpx;
			width: 100vw;
			position: fixed;
			background: #fff;
			z-index: 99;
			top: 0;

			div {
				display: inline-block;
				width: 48%;
				line-height: 118rpx;
				font-size: 32rpx;
				text-align: center;
			}
		}

		.orderListBox {
			background: #F7F7FA;
			min-height: calc(100vh - 287rpx);
			padding-top: 40rpx;
			padding-bottom: 130rpx;
			margin-top: 118rpx;

			.ulList {
				width: 90vw;
				height: 274rpx;
				border: 2rpx solid #EEEEEE;
				border-radius: 6rpx;
				margin: 0 5vw 40rpx 5vw;

				.liCenter {
					height: 133rpx;
					padding-left: 30rpx;
					line-height: 133rpx;
					font-size: 24rpx;
					background: #FAFAFC;
					border-bottom: 1rpx solid #EEEEEE;
					display: flex;
				}
			}

			.titileName {
				color: #888888;
				padding-left: 30rpx;
				background: #fff;
				height: 70.5rpx;
				line-height: 70.5rpx;
				font-size: 26rpx;
			}

			.bottomFixed {
				position: fixed;
				bottom: 0;
				width: 100vw;
				height: 128rpx;
				background: #fff;
				line-height: 128rpx;
				display: flex;
				padding: 0 30rpx;

				button {
					width: 150rpx;
					height: 70rpx;
					line-height: 70rpx;
					border-radius: 35rpx;
					background: #04B871;
					color: #fff;
					font-size: 32rpx;
				}
			}
		}
	}
</style>