<template>
	<view>
		<cu-custom class="main-totextbar bg-main-oil" :isPay='true' :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" v-if='type == "oil"'>
					{{order.realAmount>0?order.realAmount:'xxx.x'|moneyFormat}}
				</text>
				<text class="text-xxl text-bold oil-main-color" v-if='type == "urea"'>
					{{order.oldRealAmount>0?order.oldRealAmount:'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-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 class="cu-item" v-show="order.wxPayStatus" @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>
							</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="https://xoi-support.oss-cn-hangzhou.aliyuncs.com/星油运营小程序/gr.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 class="cu-item" v-if='type == "urea"' @tap="ureaSelectCompanyCard(itemx)"
						v-for="itemx in ureaCompanyOtherList" :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"
										v-if='itemx.companyNature =="0"'></image>
									<image src="https://xoi-support.oss-cn-hangzhou.aliyuncs.com/星油运营小程序/gr.png"
										mode="widthFix" width="100upx" v-if='itemx.companyNature =="1"'></image>
								</view>
								<text class="padding-left-sm"
									v-if='itemx.companyNature =="0"'>外请油卡支付(余额:{{itemx.balance|moneyFormat}})</text>
								<text class="padding-left-sm" v-if='itemx.companyNature =="1"'>企业油卡支付
									{{itemx.companyNature =="1" ? itemx.shareCompanyQuota==0? '(余额:'+itemx.balance+')' :'':''}}
								</text>
							</view>
							<view class="text-sm padding-left-xl margin-left-xs">
								{{itemx.name}} {{itemx.shareCompanyQuota==1?'共享额度':'非共享'}}
							</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" v-if='type == "oil"'>
					<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">
						油站
						<view class="fr">{{order.siteName?order.siteName:''}}
							<!-- <text v-if="order.siteLevel" class="cu-tag  text-xs tag-red" style="margin-left: 20px;">{{order.siteLevel}}级</text> -->
						</view>
					</view>
					<view class="padding-tb-xs text-left">
						油品油枪
						<text
							class="fr nowrap">{{order.oilsCode?order.oilsCode+' ':''}}&{{ order.gunName?order.gunName+'号枪': order.oilsBar?order.oilsBar+'号枪':'未选择油枪'}}</text>
					</view>
					<view class="padding-tb-xs  text-left">
						加油升数
						<text class="fr">约{{order.volume?order.volume :'xxx.x' | moneyFormath}} L</text>
					</view>
					<view class="dashed-top margin-top-xs padding-top-sm">
						<view class="padding-tb-xs text-left">
							加油金额
							<!-- <text
								class="fr">{{order.oilDiscountAmount>0?order.realAmount+order.oilDiscountAmount:order.realAmount|moneyFormat}}</text> -->
							<text class="fr">{{ moneyIntercept(order.xoilAmountGun )}}</text>
						</view>
					</view>
					<view class="padding-tb-xs text-left">
						星油优惠
						<!-- order.oilDiscountAmount>0?order.oilDiscountAmount:'xxx.x'|moneyFormat -->
						<text class="text-red fr">{{ moneyIntercept(order.oilDiscountAmount)}}</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? '¥'+ order.realAmount:'xxx.x'|}}</text>
					</view>
				</view>
				<view class="padding" v-if='type == "urea"'>
					<view class="padding-bottom-xs margin-bottom-xs dashed-bottom">
						<view class="padding-tb-xs text-left" @tap="onCopy(order.orderId)">
							订单编号
							<text class="fr">{{order.orderId?order.orderId:''}} <text
									class="cuIcon-copy padding-left-xs"></text></text>
						</view>
					</view>
					<view class="padding-tb-xs text-left">
						油站
						<view class="fr">{{order.siteName?order.siteName:''}}
							<!-- <text v-if="order.siteLevel" class="cu-tag  text-xs tag-red" style="margin-left: 20px;">{{order.siteLevel}}级</text> -->
						</view>
					</view>
					<view class="padding-tb-xs text-left">
						加注类型
						<text class="fr nowrap">{{order.formats | ureaFormats }}</text>
					</view>
					<view class="padding-tb-xs formats_box" v-if='order.formats == "2"'>
						<view class="formats_box_list" v-for="(list,i) in order.xoilUreaOrderRelations " :key='i'>
							<view class="formats_box_list_left w30">
								{{list.brandName}}
							</view>
							<view class="formats_box_list_main w30">{{list.options}}/桶<text
									style="color: red;">X{{list.goodsQuantity}}</text> </view>
							<view class="formats_box_list_right w30">&#165;{{list.totalPrice}}</view>
						</view>
					</view>
					<view class="padding-tb-xs  text-left" v-if='order.formats != "2"'>
						加注量
						<text class="fr">{{order.oldRealLiter?order.oldRealLiter :'xxx.x'  }}</text>
					</view>
					<view class="padding-tb-xs text-left">
						合计
						<text
							class="text-red text-bold text-lg  fr">{{order.oldRealAmount>0? '¥'+ order.oldRealAmount:'xxx.x'|}}</text>
					</view>
				</view>
			</view>
			<view class="padding placeholder-hidden">
				<button class="cu-btn block lg bg-main-oil" :disabled='isdisabled' @tap="payOrder">立即支付</button>
				<button class="cu-btn margin-top block lg " @tap="cancelOrder(order.orderSerialNumber)">取消订单</button>
			</view>
			<view class="padding fixed-bar-bottom">
				<button class="cu-btn block lg bg-main-oil" :disabled='isdisabled' @tap="payOrder">立即支付</button>
				<button class="cu-btn margin-top block lg " @tap="cancelOrder(order.orderSerialNumber)">取消订单</button>
			</view>
			<view class="padding fixed-bar-bottom" v-if='type == "urea"'>
				<button class="cu-btn block lg bg-main-oil" :disabled='isdisabled' @tap="payOrder">立即支付</button>
				<button class="cu-btn margin-top block lg " @tap="ureaCancelOrder(order.orderId)">取消订单</button>
			</view>
		</view>
		<AbnormalPopup :types='PopupType' :checkType='checkType' @hidenPopup='hidenPopup' :PopupShows='PopupShow'
			@getureaFinanceApi='getureaFinanceApi'></AbnormalPopup>
	</view>
</template>

<script>
	import timeDown from '@/components/xw-CountDown'
	import oilOrderApi from '@/api/oil-order.js'
	import oilFinanceApi from '@/api/oil-finance.js'
	import ureaFinanceApi from '../../../api/urea_finance.js'
	import AbnormalPopup from '../../../components/AbnormalPopup.vue'
	export default {
		components: {
			timeDown,
			AbnormalPopup
		},
		data() {
			return {
				checkType: false,
				PopupType: null,
				PopupShow: false,
				ureaInfo: {
					accountCardCode: '',
					companyId: ''
				},
				isdisabled: false,
				showtitles: "",
				imgURL: this.global.imgURL,
				order: {},
				activePay: 0,
				isCompany: uni.getStorageSync('accountStatus'),
				accountCardCode: '',
				card: {},
				datatime: "",
				checked: '',
				cooling: false,
				payMethod: 0,
				user: uni.getStorageSync('user'),
				type: '',
				ureaCompanyOtherList: [],
				companyNature: '',
				shareCompanyQuota: '',
				secondChannelCode: ''
			}
		},
		onLoad(option) {

			if (option.type == 'urea') {
				this.order = uni.getStorageSync('ureaOrderMade')
				this.order.companyStatus = true
				this.type = 'urea'
				this.findUreaAccount()
			} else {
				let oilItem = uni.getStorageSync('oilItem')
				this.order = uni.getStorageSync('orderMade')
				this.type = 'oil'
				this.showtitles = oilItem.listTag
				this.secondChannelCode = oilItem.secondChannelCode
				if (option.payMethod == null) {
					this.payMethod = oilItem.payMethod
				} else {
					this.payMethod = option.payMethod
				}
			}
		},
		computed: {
			companyList() {
				if (this.isCompany) {
					let companyAccounts = this.order.companyAccounts || []
					let filterData = companyAccounts.filter(item => item.companyType != 5)
					return filterData
				}
			},
			companyOtherList() {
				if (this.isCompany) {
					// return this.order.otherAccounts
					let otherAccounts = this.order.otherAccounts || []
					let filterData = otherAccounts.filter(item => item.companyType != 5)
					let target = this.sortParticulars(filterData, 'balance')
					return target
				}
			}
		},
		onShow() {
			this.datatime = this.timF(this.order.createTime)
		},
		onReady() {
			if (this.isCompany) {
				this.card = this.order.companyAccounts[0]
				this.checked = this.card.accountCardCode
				this.accountCardCode = this.card.accountCardCode
			} else {
				this.card = this.order.personalAccount
				this.checked = 'person'
				this.accountCardCode = this.card.accountCardCode
			}
		},
		methods: {
			sortParticulars(arr, field) {
				let map = new Map()
				let keys = [],
					values = [],
					target = []
				arr.forEach(item => {
					map.set(item, item[field])
				})
				for (let key of map.keys()) {
					keys.push(key)
				}
				for (let value of map.values()) {
					values.push(value)
				}
				values.sort((a, b) => {
					return a - b
				})
				values.reverse()
				values.forEach(value => {
					keys.forEach(key => {
						if (map.get(key) == value) {
							target.push(key)
							map.set(key, new Date().getTime())
						}
					})
				})
				return target
			},
			getureaFinanceApi() {
				ureaFinanceApi.queryWhetherToHangUp(this.order.orderId).then(res => {
					if (res.data == '2') {
						this.checkType = true
					}
				})
			},
			hidenPopup(e) {
				this.PopupShow = e
			},
			findUreaAccount() {
				ureaFinanceApi.findUreaAccount(this.order.driverId).then(res => {
					this.ureaCompanyOtherList = res.data
				})
			},
			timF(date) {
				date = date.substring(0, 19)
				date = date.replace(/-/g, '/')
				var timestampDeadline = (new Date(date).getTime()) / 1000 + 60 * 10
				return timestampDeadline
			},
			ureaCancelOrder(id) {
				ureaFinanceApi.cancelTheOrder(id).then(res => {
					if (res.code == 20000) {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 1000
						})
						setTimeout(() => {
							uni.navigateBack(2)
						}, 1000)

					}
				})
			},
			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'
			},
			ureaSelectCompanyCard(card) {
				this.ureaInfo.accountCardCode = card.accountCardCode
				this.ureaInfo.companyId = card.companyId
				this.card = card
				this.checked = card.accountCardCode
				this.accountCardCode = card.accountCardCode
				this.companyNature = card.companyNature
				this.shareCompanyQuota = card.shareCompanyQuota
			},
			selectCompanyCard(card) {
				this.card = card
				this.checked = card.accountCardCode
				this.accountCardCode = card.accountCardCode
			},
			payOrder() {
				this.isdisabled = true
				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: '操作频繁,请5s后再试',
						icon: 'none'
					})
					this.isdisabled = false
				}
			},
			selfWxPay() {
				let payData = {
					payChannel: 'WECHAT_MINIAPPS_PAYMENT', //微信小程序支付 WECHAT_APP_PAYMENT微信APP支付
					openId: uni.getStorageSync('openid'),
					unionId: uni.getStorageSync('unionid'),
					appId: 'wx7a939c19b270cc3d',
					payCode: 'WECHAT_ORDER_PAY_WECHAT', //APP填WECHAT_ORDER_PAY_APP,小程序填
					orderId: this.order.orderSerialNumber,
					payClient: 'XOIL_DRIVER_COMPANY_WECHAT_APPLET' //"支付端。安卓XOIL_DRIVER_ANDROID,小程序
				}
				oilFinanceApi.aggregatePay(payData).then(res => {
					if (res.code == 20000) {
						uni.requestPayment({
							provider: 'wxpay',
							...res.data.baseWxOrderVo,
							success: (res) => {
								this.isdisabled = false
								// this.getPayStatus(this.outTradeNo)
								// this.getLastMoney()
								// this.getCards()
								uni.showToast({
									title: res.msg
								})
								uni.redirectTo({
									url: '/BagStation/pages/makeOrder/payResult?status=success&&payMethod=' +
										this.payMethod,
									fail: (err) => {
										// console.log(err)
									}
								})
							},
							fail: function(err) {
								// console.log('fail:' + JSON.stringify(err));
							}
						})
						// uni.showToast({
						// 	title: res.msg
						// })
						// uni.redirectTo({
						// 	url: '/BagStation/pages/makeOrder/payResult?status=success',
						// 	fail: (err) => {
						// 		console.log(err)
						// 	}
						// })
					} else {
						// uni.redirectTo({
						// 	url: '/BagStation/pages/makeOrder/payResult?status=fail'
						// })
					}

				})
			},
			selfCardPay() {
				let _that = this
				if (!this.card.accountCardCode) {
					uni.showToast({
						title: '请选择支付油卡',
						icon: 'none'
					})
					this.isdisabled = false
					return false
				}
				if (this.card.balance < this.order.realAmount && this.card.shareCompanyQuota != 1) {
					if (this.type == 'urea') {
						this.PopupShow = true
						this.PopupType = 2
						this.isdisabled = false
						return
					} else if (this.type == 'oil') {
						uni.showToast({
							title: '该油卡余额不足',
							icon: 'none'
						})
						this.isdisabled = false
						return false
					}

				}
				let payData
				if (this.type == 'oil') {
					payData = {
						...this.card,
						"orderSerialNumber": this.order.orderSerialNumber, //类型:String  必有字段  备注:订单编号
						"payChannel": "BALANCE_PAYMENT", //类型:String  必有字段  备注:支付渠道(BALANCE_PAYMENT:余额支付)
						"orderMethod": "CUSTOMER_ACTIVE", //类型:String  必有字段  备注:订单产生方式(CUSTOMER_ACTIVE:客户扫码支付:客户扫描油站二维码完成支付)
						"createSource": "XOIL_DRIVER_COMPANY_WECHAT_APPLET"
					}
					oilOrderApi.payOrder(payData).then(res => {
						this.isdisabled = false
						if (res.code == 20000) {
							this.isdisabled = false
							uni.showToast({
								title: res.msg
							})
							setTimeout(() => {
								if (this.secondChannelCode == 'JX_INVEST') {
									uni.redirectTo({
										url: '/BagStation/pages/makeOrder/JXPayResult?status=success&&payMethod=' +
											this.payMethod,
										fail: (err) => {
											// console.log(err)
										}
									})
								} else {
									uni.redirectTo({
										url: '/BagStation/pages/makeOrder/payResult?status=success&&payMethod=' +
											this.payMethod,
										fail: (err) => {
											// console.log(err)
										}
									})								}

							}, 1000)

						} else {
							this.isdisabled = false
							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)
						}

					})
				} else if (this.type = 'urea') {
					payData = {
						belongCompanyId: this.ureaInfo.companyId,
						driverId: this.user.id,
						accountCardCode: this.ureaInfo.accountCardCode,
						driverPhone: this.user.userPhone,
						oldRealAmount: this.order.oldRealAmount,
						vehicleNo: this.order.vehicleNo,
						orderId: this.order.orderId,
						driverName: this.order.driverName,
						userSource: 'urea',
						formats: this.order.formats,
						oilCardNature: this.companyNature,
						companyShared: this.shareCompanyQuota
					}
					ureaFinanceApi.orderPay(payData).then(res => {
						if (res.code == 20000) {
							uni.setStorageSync('ureaOrderMade', res.data)
							if (res.data.formats == '2') {
								uni.redirectTo({
									url: '/BagStation/orderDetail/orderDetailUrea?type=orderPay',
									fail: (err) => {}
								})
								return
							}
							_that.PopupShow = true
							_that.PopupType = 5
							this.isdisabled = false
						} else if (res.code == 40000 && res.msg == '余额不足') {
							_that.PopupShow = true
							_that.PopupType = 2
							this.isdisabled = false
						}
					})
				}
			},
			onCopy(id) {
				uni.setClipboardData({
					data: id,
					success: () => {
						uni.showToast({
							icon: 'none',
							title: '订单号复制成功'
						})
					}
				})
			}
		},
		filters: {
			ureaFormats(value) {
				if (value == 1) {
					return '加注站'
				} else {
					return '桶装'
				}
			},
			moneyFormath(value) {
				if (value != 'xxx.x') {
					let number = value.toFixed(2)
					return number
				} else {
					return value
				}
			},
			moneyFormat(value) {
				if (value != 'xxx.x') {
					let realAmount = Math.round(value * 100) / 100;
					return realAmount
				} else {
					return value
				}
			}
		}
	}
</script>

<style scoped>
	.w30 {
		width: 30%;
		flex: 0 0 auto;
		text-align: center;
		font-weight: 700;
		font-size: 28rpx;
	}

	.formats_box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 2%;
		box-sizing: border-box;
		flex-direction: column;
	}

	.formats_box_list {
		display: flex;
		justify-content: space-around;
		align-items: center;
		margin-bottom: 3%;
		font-size: 30rpx;
		color: #333;
		align-items: center;
		width: 100%;
	}

	.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>