<template>
	<view>
		<cu-custom class="main-totextbar bg-main-oil" :isBack="true" bgColor="bg-main-oil">
			<block slot="backText">返回</block>
			<block slot="content">清正源油收银台</block>
		</cu-custom>
		<view class="">
			<view class="padding-xl text-center">
				<text class="text-xxl text-bold oil-main-color">
					{{order.realAmount>0?order.realAmount:'xxx.x'|moneyFormat}}
				</text>
				<view class="text-gray">
					支付剩余时间 <time-down :is-day="false" :is-hour="false" :tip-text="' '" :day-text="' '" :hour-text="':'"
						:minute-text="':'" :second-text="' '" :datatime="datatime"></time-down>
				</view>
			</view>
			<view class=" radius my-shadow solid-top margin margin-top-0">
				<view class="cu-list menu" v-if="!isCompany">
					
					<view class="cu-item" v-if="order.wxPayStatus && order.dispatchPaymentMethod !== 'JIAOLIANPAY'" @tap="selWX">
						<view class="content">
							<view class="text-left">
								<view class="site-icon-sm">
									<image :src="imgURL+'pay-wx.png'" mode="widthFix" width="100upx"></image>
								</view>
								<text class="padding-left-sm">微信支付</text>
							</view>
						</view>
						<view class="action">
							<view class="site-icon-sm check-icon">
								<image :src="imgURL+(checked == 'weixin'?'pay-xz.png':'pay-qx.png') " mode="widthFix"
									width="100upx"></image>
								<!-- <image :src="imgURL+'pay-qx.png'" mode="widthFix" width="100upx"></image> -->
							</view>
						</view>
					</view>
					
					
					
					
					<!-- <view class="cu-item" v-show="order.personalStatus" @tap="selectPersonCard(order.personalAccount)">
						<view class="content">
							<view class="text-left">
								<view class="site-icon-sm">
									<image :src="imgURL+'pay-gr.png'" mode="widthFix" width="100upx"></image>
								</view>
								<text
									class="padding-left-sm">星油豆支付（余额：{{order.personalAccount.balance|moneyFormat}}个）</text>
							</view>
						</view>
						<view class="action">
							<view class="site-icon-sm">
								<image :src="imgURL+ (checked == 'person'?'pay-xz.png':'pay-qx.png')" mode="widthFix"
									width="100upx"></image>
								 <image :src="imgURL+'pay-qx.png'" mode="widthFix" width="100upx"></image> 
							</view>
						</view>
					</view> -->


				</view>
				<view class="cu-list menu" v-if="isCompany">
					<view class="cu-item" v-show="order.companyStatus" @tap="selectCompanyCard(item)"
						v-for="item in companyList" :key="item.id">
						<view class="content padding-tb-sm">
							<view class="text-left">
								<view class="site-icon-sm">
									<image :src="imgURL+'pay-qy.png'" mode="widthFix" width="100upx"></image>
								</view>
								<text class="padding-left-sm">自营企业油卡支付 <text
										v-if="item.shareCompanyQuota==0">（余额：{{item.balance|moneyFormat}}）</text></text>
								<!-- <text class="padding-left-sm">企业油卡支付</text> -->
							</view>
							<view class="text-sm padding-left-xl margin-left-xs">
								{{item.companyName}} {{item.shareCompanyQuota==1?'共享额度':'非共享'}}
							</view>
							<view class="text-sm padding-left-xl margin-left-xs">
								<text class="">
									(单次金额上限{{item.orderAmountToplimit}}元;单笔加油升数上限{{item.orderVolumeToplimit}}L)</text>
							</view>
						</view>
						<view class="action">
							<view class="site-icon-sm">
								<image :src="imgURL+(checked  == item.accountCardCode?'pay-xz.png':'pay-qx.png')"
									mode="widthFix" width="100upx"></image>
								<!-- <image :src="imgURL+'pay-qx.png'" mode="widthFix" width="100upx"></image> -->
							</view>
						</view>
					</view>
					<view class="cu-item" v-show="order.companyStatus" @tap="selectCompanyCard(itemx)"
						v-for="itemx in companyOtherList" :key="itemx.id">
						<view class="content padding-tb-sm">
							<view class="text-left">
								<view class="site-icon-sm">
									<image :src="imgURL+'pay-qy.png'" mode="widthFix" width="100upx"></image>
								</view>
								<text class="padding-left-sm">外请油卡支付（余额：{{itemx.balance|moneyFormat}}）</text>
								<!-- <text class="padding-left-sm">企业油卡支付</text> -->

							</view>
							<view class="text-sm padding-left-xl margin-left-xs">
								{{itemx.companyName}}
							</view>
						</view>
						<view class="action">
							<view class="site-icon-sm">
								<image
									:src="imgURL+(card.accountCardCode == itemx.accountCardCode?'pay-xz.png':'pay-qx.png')"
									mode="widthFix" width="100upx"></image>
								<!-- <image :src="imgURL+'pay-qx.png'" mode="widthFix" width="100upx"></image> -->
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class=" radius my-shadow solid-top margin margin-top-0">
				<view class="bg-gray text-center padding-sm margin-bottom-sm">
					请提醒加油员使用
					<text class="oil-main-color">“{{showtitles}}”</text>
					进行订单核销
				</view>
				<view class="padding">
					<view class="padding-bottom-xs margin-bottom-xs dashed-bottom">
						<view class="padding-tb-xs text-left" @tap="onCopy(order.orderSerialNumber)">
							订单编号：
							<text class="fr">{{order.orderSerialNumber?order.orderSerialNumber:''}} <text
									class="cuIcon-copy padding-left-xs"></text></text>

						</view>
					</view>
					<view class="padding-tb-xs text-left">
						油站：
						<text class="fr">{{order.siteName?order.siteName:''}}</text>
					</view>
					<view class="padding-tb-xs text-left">
						油品油枪：
						<text
							class="fr nowrap">{{order.oilsCode?order.oilsCode+' ':''}}&{{order.oilsBar?order.oilsBar+'号枪':'未选择油枪'}}</text>
					</view>
					<view class="padding-tb-xs  text-left">
						加油升数：
						<text class="fr">{{order.volume?order.volume :'未输入' | moneyFormath}}L</text>
					</view>
					<view class="dashed-top margin-top-xs padding-top-sm">
						<view class="padding-tb-xs text-left">
							加油金额：<text class="fr">{{moneyIntercept(order.xoilAmountGun) }}</text>
							<!-- <text
								class="fr">{{order.oilDiscountAmount>0?order.realAmount+order.oilDiscountAmount:order.realAmount|moneyFormat}}</text> -->
						</view>
					</view>
					<view class="padding-tb-xs text-left">
						星油优惠：
						<text
							class="text-red fr">{{order.oilDiscountAmount>0?order.oilDiscountAmount:'xxx.x'|moneyFormat}}</text>
					</view>
					<view class="padding-tb-xs text-left">
						优惠券：
						<text
							class="text-red fr">{{order.couponDiscountAmount>0?order.couponDiscountAmount:'xxx.x'|moneyFormat}}</text>
					</view>
					<view class="padding-tb-xs text-left">
						合计：
						<text class="text-red text-bold text-lg  fr">
							￥{{order.realAmount>0? moneyIntercept(order.realAmount) :'xxx.x' }}</text>
					</view>
				</view>
			</view>
		<!-- 	<view class="padding placeholder-hidden">
				<button class="cu-btn block lg bg-main-oil" @tap="payOrder">立即支付</button>
				<button class="cu-btn margin-top block lg " @tap="cancelOrder(order.orderSerialNumber)">取消订单</button>
			</view> -->
			<view class="padding fixed-bar-bottom">
				<jl-pay v-if="order.dispatchPaymentMethod === 'JIAOLIANPAY'" :orderNo="order.orderNo" :amount="order.resultAmount" :returnUrl="order.pagePath" @navigateTo="navigateTo">
				  <button class="cu-btn block lg bg-main-oil" >立即支付</button>
				</jl-pay>
				<button v-else  class="cu-btn block lg bg-main-oil" @tap="payOrder">立即支付</button>
				<button class="cu-btn margin-top block lg " @tap="cancelOrder(order.orderSerialNumber)">取消订单</button>
			</view>
		</view>
	</view>
</template>

<script>
	import timeDown from '@/components/xw-CountDown'
	import oilOrderApi from '@/api/oil-order.js'
	import oilFinanceApi from '@/api/oil-finance.js'
	import oilPayApi from '@/api/pay.js'
	export default {
		components: {
			timeDown
		},
		data() {
			return {
				userIp: null,
				showtitles: "",
				imgURL: this.global.imgURL,
				order: uni.getStorageSync('orderMade'),
				activePay: 0,
				isCompany: uni.getStorageSync('accountStatus'),
				accountCardCode: '',
				card: {},
				datatime: "",
				checked: '',
				cooling: false

			}
		},
		computed: {
			companyList() {
				if (this.isCompany) {
					return this.order.companyAccounts
				}
			},
			companyOtherList() {
				if (this.isCompany) {
					return this.order.otherAccounts
				}
			}
		},
		onLoad(option) {
			let oilItem = uni.getStorageSync('oilItem')
			this.showtitles = oilItem.listTag
			console.log(option.payMethod)
			if (option.payMethod) {
				this.payMethod = option.payMethod
			} else {
				this.payMethod = oilItem.payMethod
			}
			
			console.log('orderinfo',this.order)
			if(this.order.dispatchPaymentMethod === 'JIAOLIANPAY') {
				this.order.resultAmount = this.order.realAmount * 100
			}
			
			console.log('fafafdfadsfasdf',this.order.wxPayStatus && this.order.dispatchPaymentMethod !== 'JIAOLIANPAY')

		},
		onShow() {
			this.datatime = this.timF(this.order.createTime);
			const that = this
			wx.request({
				url: 'http://ip-api.com/json',
				success: function(e) {
					// console.log(e.data.query);
					that.userIp = e.data.query
				}
			})
		},
		onReady() {
			if (this.isCompany) {
				this.card = this.order.companyAccounts[0]
				this.checked = this.card.accountCardCode
				this.accountCardCode = this.card.accountCardCode
			} else {
				this.selWX()
				// this.card = this.order.personalAccount
				// this.checked = 'weixin'
				// this.accountCardCode = this.card.accountCardCode
			}
		},
		methods: {
			navigateTo(e) {
				if (e.detail.success) {
				    // 支付成功操作
					uni.redirectTo({
						url: '/BagStation/pages/makeOrder/payResult?status=success&&payMethod=' +
							this.payMethod
					})
				  } else {
				   uni.showToast({
				   	title: '支付失败，请重试',
				   	icon: 'none'
				   })
				  }
			},
			timF(date) {
				date = date.substring(0, 19)
				date = date.replace(/-/g, '/')
				var timestampDeadline = (new Date(date).getTime()) / 1000 + 60 * 10
				return timestampDeadline
			},
			cancelOrder(id) {
				oilOrderApi.cancelOrder(id).then(res => {
					if (res.code == 20000) {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 1000
						})
						setTimeout(() => {
							uni.navigateBack(2)
						}, 1000)

					}
				})
			},
			selWX() {
				this.activePay = 2
				this.checked = 'weixin'
			},
			selectPersonCard(card) {
				this.activePay = 0
				this.card = card
				this.checked = 'person'
			},
			selectCompanyCard(card) {
				// console.log(card)
				this.card = card
				this.checked = card.accountCardCode
				this.accountCardCode = card.accountCardCode
			},
			payOrder() {
				if (!this.cooling) {
					this.cooling = true
					setTimeout(() => {
						this.cooling = false
					}, 5000);
					if (this.activePay == 0) {
						this.selfCardPay()
					} else if (this.activePay == 2) {
						this.selfWxPay()
					}
				} else {
					uni.showToast({
						title: '操作频繁',
						icon: 'none'
					})
				}

			},
			selfWxPay() {
				let payData = {
					// payChannel: 'WECHAT_MINIAPPS_PAYMENT', //微信小程序支付 WECHAT_APP_PAYMENT微信APP支付
					// openId: uni.getStorageSync('openid'),
					// unionId: uni.getStorageSync('unionid'),
					// appId: 'wxf3d6c15e3b087447',
					// payCode: 'WECHAT_ORDER_PAY_WECHAT', //APP填WECHAT_ORDER_PAY_APP，小程序填
					// orderId: this.order.orderSerialNumber,
					// payClient: 'XOIL_DRIVER_WECHAT_APPLET' //"支付端。安卓XOIL_DRIVER_ANDROID，小程序
					payChannel: 'WECHAT_MINIAPPS_PAYMENT', //微信小程序支付 WECHAT_APP_PAYMENT微信APP支付
					openId: uni.getStorageSync('openid'),
					unionId: uni.getStorageSync('unionid'),
					appId: 'wxf3d6c15e3b087447',
					payCode: 'WECHAT_ORDER_PAY_WECHAT', //APP填WECHAT_ORDER_PAY_APP，小程序填
					orderId: this.order.orderSerialNumber,
					payClient: 'XOIL_DRIVER_WECHAT_APPLET', //"支付端。安卓XOIL_DRIVER_ANDROID，小程序
					userIp: (this.userIp ? this.userIp : "36.57.160.59"),
					merchantNo: '10090808247'
				}

				oilPayApi.aggregatePay(payData).then(res => {
					if (res.code == 20000) {
						uni.requestPayment({
							provider: 'wxpay',
							...res.data.baseWxOrderVo,
							success: (_res) => {
								uni.showToast({
									title: res.msg
								})
								oilPayApi.wxPayIntegral({
									appId: 'wxf3d6c15e3b087447',
									orderId: this.order.orderSerialNumber
								})
								uni.redirectTo({
									url: '/BagStation/pages/makeOrder/payResult?status=success&&payMethod=' +
										this.payMethod
								})
							}
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}

				})
			},
			selfCardPay() {
				if (!this.card.accountCardCode) {
					uni.showToast({
						title: '请选择支付油卡',
						icon: 'none'
					})
					return false
				}
				if (this.card.balance < this.order.realAmount) {
					uni.showToast({
						title: '该油卡余额不足',
						icon: 'none'
					})
					return false
				}
				let payData = {
					...this.card,
					"orderSerialNumber": this.order.orderSerialNumber, //类型：String  必有字段  备注：订单编号
					"payChannel": "BALANCE_PAYMENT", //类型：String  必有字段  备注：支付渠道（BALANCE_PAYMENT：余额支付）
					"orderMethod": "CUSTOMER_ACTIVE", //类型：String  必有字段  备注：订单产生方式（CUSTOMER_ACTIVE：客户扫码支付：客户扫描油站二维码完成支付）
					"createSource": "XOIL_DRIVER_WECHAT_APPLET",
				}
				oilOrderApi.payOrder(payData).then(res => {
					if (res.code == 20000) {
						uni.showToast({
							title: res.msg
						})
						setTimeout(() => {
							uni.redirectTo({
								url: '/BagStation/pages/makeOrder/payResult?status=success&&payMethod=' +
									this.payMethod,
								fail: (err) => {
									// console.log(err)
								}
							})
						}, 1000)

					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
						setTimeout(() => {
							let msg = res.msg
							uni.redirectTo({
								url: `/BagStation/pages/makeOrder/payResult?status=fail&&errMsg=${msg}&&payMethod=` +
									this.payMethod
							})
						}, 1000)
					}

				})
			},
			onCopy(id) {
				uni.setClipboardData({
					data: id,
					success: () => {
						uni.showToast({
							icon: 'none',
							title: '订单号复制成功'
						})
					}
				})
			}
		},
		filters: {
			moneyFormath(value) {
				// console.log(value)
				if (value != 'xxx.x') {
					let number = value.toFixed(2)
					return number
				} else {
					return value
				}
			},
			moneyFormat(value) {
				if (value != 'xxx.x') {
					return (parseInt(value * 100) / 100).toFixed(2)
				} else {
					return value
				}
			}
		}
	}
</script>

<style scoped>
	.site-icon-sm {
		width: 40upx;
		vertical-align: middle;
		display: inline-block;
		margin-top: 5px;
		height: 40upx;
	}

	.action .site-icon-sm {
		width: 30upx;
		/* display: inline-block; */
	}

	.fixed-bar-bottom {
		width: 750upx;
		position: fixed;
		bottom: 0;
	}
</style>
