<template>
	<view>
		<lf-nav title="支付收银台" :showIcon="true" bgColor="#fff"></lf-nav>
		<view class="content">
			<view class="card lf-flex-column lf-row-center">
				<view class="lf-font-28 lf-color-222">需要支付</view>
				<view class="lf-m-t-10 lf-m-b-10">
					<text class="symbol">￥</text>
					<text class="price">{{ amount }}</text>
				</view>
				<view class="tips">
					<view>剩余支付时间：</view>
					<view>
						<countdown-timer :time="time" :autoStart="true" @finish="dateFinish">
							<template v-slot="{minute, second}">
								<!-- <view>{{minute}}:{{second}}</view> -->
								<view class="lf-flex">
									<view>{{ minute >= 10 ? minute : "0" + minute }}</view>
									<view>:</view>
									<view>{{ second >= 10 ? second : "0" + second }}</view>
								</view>
							</template>
						</countdown-timer>
					</view>
				</view>
			</view>
			<view class="card lf-row-between" v-for="(item, index) in pay_list" :key="index">
				<view>
					<text class="lf-iconfont" :class="item.icon"></text>
					<text class="lf-m-l-10 lf-font-28 lf-color-222">{{ item.name }}</text>
				</view>
				<radio-group @change="checkChange($event, index)">
					<radio :checked="item.checked"></radio>
				</radio-group>
			</view>
		</view>
		<view class="fixed-btn" hover-class="lf-opacity" @click="confirm">立即支付</view>
		<view class="fixed-agreement">《购买须知》</view>
		<lf-pay-password v-if="show_pw" @comfirm="payComfirm" title="请输入支付密码"></lf-pay-password>
	</view>
</template>

<script>
	import countdownTimer from '@/components/countdown-timer/countdown-timer';
	import lfPayPassword from '@/components/lf-payPassword/lf-payPassword.vue'
	export default {
		components: {
			countdownTimer,
			lfPayPassword
		},
		data(){
			return {
				pay_list: [{
					name: '余额支付',
					icon: 'icon--',
					type: 'balance',
					checked: false
				},{
					name: '微信支付',
					icon: 'icon--1',
					type: 'wx_lite',
					checked: true
				}],
				time: new Date('2021/09/8 14:15:00').getTime() - new Date('2021/09/8 14:10:00').getTime(),
				is_date_finish: false,
				amount: '',
				order_no: '',
				token: '',
				balance_sum: 0,
				show_pw: false,
				user_pw: ''
			}
		},
		onLoad(options){
			this.token = this.$cookieStorage.get('user_token');
			this.amount = options.amount;
			this.order_no = options.order_no;
			this.getBalanceSum();
		},
		methods: {
			// 获取余额
			getBalanceSum(){
				this.$http.get({
					api: 'api/users/balance/sum',
					header: {
						Authorization: this.token
					}
				}).then(res => {
					this.balance_sum = res.data.data.sum;
				})
			},
			// 改变支付方式
			checkChange(event, current){
				let list = this.pay_list.map((item, index) => {
					if(index == current){
						item.checked = true;
					}else{
						item.checked = false;
					}
					return item;
				})
				this.pay_list = list;
			},
			// 倒计时结束
			dateFinish(){
				console.log("倒计时结束");
				this.is_date_finish = true;
				this.$msg('订单超时', {icon: 'error'}).then(() => {
					this.$toBack();
				})
			},
			// 支付密码输入完成
			payComfirm(event){
				this.user_pw = event;
				this.show_pw = false;
				this.confirm();
			},
			// 支付
			confirm(){
				if(this.is_date_finish) return this.$msg('订单超时未支付');
				let channel = '';
				this.pay_list.map(item => {
				   if(item.checked){
					   channel = item.type;
				   }
				})
				if(channel == 'balance' && !this.user_pw){
					this.show_pw = true;
					return;
				}
				
				this.getOpenid().then(res => {
				  var data = {
				    channel: 'wx_lite',
				    openid: res,
				    order_no: this.order_no,
				    balance: 0
				  };
				  if(channel == 'balance'){
					  data.pay_pwd = this.user_pw;
					  data.balance = Number(this.amount);
					  data.channel = 'wx_lite';
				  }
					
				  this.$http.post({
				    api: `api/shopping/order/charge`,
				    data: data,
				    header: {
				      Authorization: this.token
				    }
				  }).then(res => {
					  console.log("-------------------", res)
				    res = res.data;
				    if (res.status) {
				      // this.formId =  e.detail.formId || '';
				     if (res.data.name == 'balance') {
				        this.balanceCharge();
				      } else {
				        this.newcharge(true, res.data.charge);
							 
				      }
				    } else {
				      this.newcharge(false, res.message);
							
				    }
				  })
				}).catch(() => {
				  this.setData({
				    loading: false
				  });
				  wx.showModal({
				    content: '支付失败',
				    showCancel: false
				  });
				});
			},
			// 获取openid
			getOpenid() {
			  return new Promise((resolve, reject) => {
			    wx.login({
			      success: res => {
			        this.$http.get({
			          api: `api/oauth/miniprogram/openid`,
			          data: {
			            code: res.code
			          }
			        }).then(res => {
			          res = res.data;
			          resolve(res.data.openid);
			        }).catch(() => {
			          reject('获取openid失败');
			        });
			      },
			      fail: () => {
			        wx.showModal({
			          content: "接口请求失败",
			          showCancel: false
			        });
			      }
			    });
			  });
			},
			// 新版支付
			newcharge(success, charge) {
			  if (success) {
			    var that = this;
			    if (charge.pay_scene == 'test') {
			      wx.showModal({
			        content: '不支持模拟支付',
			        showCancel: false
			      });
			      this.setData({
			        loading: false
			      });
			    } else {
			      wx.requestPayment({
			        "timeStamp": charge.credential.wechat.timeStamp,
			        "nonceStr": charge.credential.wechat.nonceStr,
			        "package": charge.credential.wechat.package,
			        "signType": charge.credential.wechat.signType,
			        "paySign": charge.credential.wechat.paySign,
			        success: res => {
			          if (res.errMsg == 'requestPayment:ok') {
			            this.setData({
			              loading: false
			            });
			            // wx.redirectTo({
			            //   url: `/pages/store/success/success?order_no=${that.order_no}&amount=${that.amount}&channel=${that.channel}&formId=${this.formId}` //&charge_id=${charge.charge_id} charge_id 支付测试使用
			            // });
						uni.redirectTo({
							url: '/pages/aboutpay/paystate?payState=1&amount='+ that.amount
						})
			          } else {
			            wx.showModal({
			              content: '调用支付失败！',
			              showCancel: false
			            });
			          }
			        },
			        fail: err => {
			          this.setData({
			            loading: false
			          });
			
			          if (err.errMsg == 'requestPayment:fail cancel') {
			            // wx.redirectTo({
			            //   url: `/pages/order/detail/detail?no=${that.order_no}`
			            // });
						uni.redirectTo({
							url: '/pages/order/index/onlineorder'
						})
			          } else {
			            wx.showModal({
			              content: '调用支付失败！',
			              showCancel: false
			            });
			          }
			        }
			      });
			    }
			  } else {
			    this.setData({
			      loading: false
			    });
			    wx.showModal({
			      content: charge || '请求支付失败，请重试！',
			      showCancel: false
			    });
				this.user_pw = '';
			  }
			},
			// 纯余额支付
			balanceCharge() {
			  this.setData({
			    loading: false
			  });
			  // wx.redirectTo({
			  //   url: `/pages/store/success/success?order_no=${this.order_no}&amount=${this.amount}&channel=${this.channel}&formId=${this.formId}`
			  // });
			  uni.redirectTo({
			  	url: '/pages/aboutpay/paystate?payState=1&amount='+ this.amount
			  })
			},
			setData: function (obj) {
			  let that = this;
			  let keys = [];
			  let val, data;
			  Object.keys(obj).forEach(function (key) {
			    keys = key.split('.');
			    val = obj[key];
			    data = that.$data;
			    keys.forEach(function (key2, index) {
			      if (index + 1 == keys.length) {
			        that.$set(data, key2, val);
			      } else {
			        if (!data[key2]) {
			          that.$set(data, key2, {});
			        }
			      }
			
			      data = data[key2];
			    });
			  });
			}
		}
	}
</script>

<style>
	page{
		background-color: #F8F8F8;
	}
</style>
<style lang="scss" scoped="scoped">
	.content{
		padding: 30rpx 32rpx;
		width: 750rpx;
		height: max-content;
		box-sizing: border-box;
		.card{
			width: 100%;
			height: max-content;
			padding: 30rpx 40rpx;
			background-color: #FFFFFF;
			border-radius: 20rpx;
			&:nth-child(n+2){
				margin-top: 30rpx;
			}
			.symbol{
				color: #15716E;
				font-size: 32rpx;
			}
			.price{
				font-size: 72rpx;
				color: #15716E;
				font-weight: bold;
			}
			.tips{
				font-size: 24rpx;
				color: #FF9D9D;
				display: flex;
			}
		}
	}
	
	.fixed-agreement {
		position: fixed;
		bottom: 5vh;
		font-size: 28rpx;
		color: #15716E;
		left: calc(50% - 84rpx);
		width: 168rpx;
	}
	
	.fixed-btn{
		position: fixed;
		bottom: 10vh;
		left: calc(50% - 275rpx);
		width: 550rpx;
		height: 100rpx;
		background-color: #15716E;
		color: #FFFFFF;
		text-align: center;
		line-height: 100rpx;
		font-size: 32rpx;
		border-radius: 50rpx;
	}
</style>
