<template>
	<view>
		<view class="box">
			<view class="top" style="padding-top: 50rpx;">
				<text class="title">缴纳费用</text>
			</view>
			<u-search placeholder="输入车牌号查询" shape="square" v-model="p.carNo" @search="searchFn()" @change="searchFn"
				:height="80" style="margin: 30rpx;">
			</u-search>
		</view>
		<view class="list" v-show="list.length>0">
			<u-radio-group placement="column" @change="groupChange">
				<u-radio :customStyle="{marginBottom: '6px',borderBottom: '1px solid #e5e5e5',paddingBottom:'5px'}"
					v-for="(item, index) in list" :key="index" :label="item.carNo" :name="item.id">
				</u-radio>
			</u-radio-group>
		</view>
		<view class="car-list" v-show="cars.length>0">
			<view class="card">
				<view class="title">
					停车费:
				</view>
				<u-checkbox-group v-model="carsSelect" placement="column">
					<view v-for="(item,index) in cars" :key="index">
						<label class="c-item">
							<view class="l">
								<u-checkbox :customStyle="{marginBottom: '8px'}" :name="item.id"
									:disabled="item.price==0">
								</u-checkbox>
							</view>
							<view class="c">{{item.carNo}}</view>
							<view class="r" v-if="item.price>0">{{item.price}}元</view>
							<view class="r" v-else>无需缴费</view>
						</label>
					</view>
				</u-checkbox-group>
			</view>

			<view class="card" v-if="item.itemsPrice">
				<view class="title">
					<u-checkbox-group placement="column" v-model="businessSelect" @change="businessChange">
						<u-checkbox :disabled="businessAble" :customStyle="{color: 'black'}"
							:label="'业务费:'+item.itemsPrice+'元'" :name='1'>
						</u-checkbox>
					</u-checkbox-group>
				</view>
				<u-checkbox-group placement="column" v-model="itemSelect">
					<view v-for="(item,index) in item.list" :key="index">
						<label class="c-item">
							<view class="l">
								<u-checkbox :customStyle="{marginBottom: '8px'}" disabled :name="item.id">
								</u-checkbox>
							</view>
							<view class="c">{{item.name}}</view>
							<view class="r">{{item.price}}元</view>
						</label>
					</view>
				</u-checkbox-group>
			</view>
		</view>

		<view class="bottom bgc-f bottom-safety" v-if="total>0">
			<view class="box">
				<view class="l">
					<text class="t1">金额：</text>
					<text class="t2">¥{{total}}元</text>
				</view>
				<view class="r" v-if="showPay">
					<view class="btn" @click="confirmPayFn()">立即支付</view>
				</view>
				<view class="r" v-else>
					<view class="btn" @click="showMsg">存在待录入业务</view>
				</view>
			</view>
		</view>
	</view>

</template>

<script>
	var jweixin = require('@/components/jweixin-module/index.js');
	export default {
		data() {
			return {
				p: {
					carNo: ''
				},
				code: '',
				selectNo: '',
				openid: '',
				carsSelect: [],
				itemSelect: [],
				businessSelect: [],
				state: '',
				list: [],
				cars: [],
				type: 0,
				businessAble: true,
				showPay: false,
				item: {
					itemsPrice: 0,
					businessId: '',
					list: []
				},
				payTypeList: [{
					name: '微信支付',
					value: 3
				}],
				form: {
					partMoney: 0,
					payType: 3
				},

			}
		},
		onLoad(options) {
			this.code = options.code;
			this.state = options.state;
			this.getOpenidByCode();
		},
		onShow() {
			this.$common.hidingLoading();
		},
		created() {},
		mounted() {
			this.getChannelCar();
			this.getWxConfig();
		},
		beforeDestroy() {
			this.$common.hidingLoading()
		},
		computed: {
			total() {
				let carIds = this.carsSelect;
				let carMoney = this.cars.filter(obj => carIds.indexOf(obj.id) !== -1)
					.map(obj => obj.price).reduce(function(pre, cur) {
						return pre + cur;
					}, 0);
				let itemIds = this.itemSelect;
				let itemMoney = this.item.list ? this.item.list.filter(obj => itemIds.indexOf(obj.id) !== -1)
					.map(obj => obj.price).reduce(function(pre, cur) {
						return pre + cur;
					}, 0) : 0;
				return (carMoney + itemMoney).toFixed(2);
			}
		},
		methods: {
			showMsg() {
				this.$common.toast('请先完善相关业务录入');
			},
			businessChange(value) {
				this.itemSelect = value.length == 0 ? this.itemSelect = [] : this.item.list.map(obj => obj.id)
			},
			getChannelCar() {
				if (this.state !== 'STATE') {
					this.$api.getPartCarByChannel({
						channel: this.state
					}).then(resp => {
						let data = resp.data;
						if (data.cars && data.cars.length > 0) {
							this.cars = data.cars;
							let carId = [data.cars[0].id];
							this.carsSelect = carId;
							this.groupChange(carId)
						}
					})
				}
			},
			getWxConfig() {
				let url = window.location.href;
				this.$api.getWxConfig({
					url: url
				}).then(resp => {
					jweixin.config({
						// debug: true,
						appId: resp.data.appId,
						timestamp: resp.data.timestamp, // 必填，生成签名的时间戳
						nonceStr: resp.data.noncestr, // 必填，生成签名的随机串
						signature: resp.data.sign, // 必填，签名
						jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表
					});
					jweixin.ready(function() {

					});
					jweixin.error(function(res) {
						console.log(res)
					});
				})
			},
			confirmPayFn() {
				let carIds = this.carsSelect
				let cars = this.cars.filter(obj => carIds.indexOf(obj.id) !== -1);
				let carNos = this.cars.map(obj => obj.carNo).join('、');
				let type = this.type;
				let p = {
					b: this.businessSelect.length > 0 ? this.item.businessId : '',
					c: JSON.stringify(cars.map(obj => {
						return {
							id: obj.id,
							p: obj.price
						}
					})),
					money: this.total,
					tradeType: "JSAPI",
					openid: this.openid,
					type: type
				}
				let con = 'A1-停车费';
				let tradeType = 'PORT_PARKING_FEE';
				if (type == 2) {
					con = 'A1-整车业务';
					tradeType = 'PORT_OPERATION_FEE';
				} else if (type == 1) {
					let itemSelect = this.itemSelect;
					let itemStr = this.item.list
						.filter(obj => itemSelect.indexOf(obj.id) !== -1).map(obj => obj.name.substr(0,obj.name.indexOf('(')))
						.join('、');
					console.log(itemStr)
					con = 'A1-' + itemStr;
					tradeType = 'PORT_OPERATION_FEE';
				}
				p.desc = con + '-' + carNos;
				p.businessType = tradeType;
				this.$common.showLoading('正在请求...');
				let that = this;
				that.$api.getPrePay(that.$common.removeNull(p)).then(resp => {
					let data = resp.data;
					if (resp.code !== 200) {
						that.$common.toast(resp.msg);
						return;
					}
					jweixin.chooseWXPay({
						timestamp: data
							.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
						nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位
						package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
						signType: data.signType, // 微信支付V3的传入RSA,微信支付V2的传入格式与V2统一下单的签名格式保持一致
						paySign: data.paySign, // 支付签名
						success: function(res) {
							if (res.errMsg === "chooseWXPay:ok") {
								that.$common.toast('支付成功')
								//that.checkPayResult(data.outTradeNo);
								that.cars = [];
								that.item.list = [];
								that.total = 0
							}
						},
						complete: function(res) {
							//that.checkPayResult(data.outTradeNo);
						}
					});
				})
			},
			checkPayResult(outTradeNo) {
				this.$common.showLoading('正在查询结果...')
				this.$api.checkPayResult({
					outTradeNo: outTradeNo
				}).then(resp => {
					let data = resp.data;
					if (data.orderStatus == 'SUCCESS' || data.orderStatus == 'FINISH') {
						this.$common.toast('支付成功')
					} else {
						this.$common.toast('支付失败')
					}
				})
			},
			payTypeChange(value) {

			},
			getOpenidByCode() {
				let storeOpenid = uni.getStorageSync('openid');
				this.$api.getOpenidByCode({
					code: this.code,
					openid: storeOpenid
				}).then(resp => {
					let openid = resp.data;
					this.openid = openid;
					if (openid) {
						uni.setStorageSync('openid', openid)
					}

				})
			},
			groupChange(carId) {
				this.$api.getBusinessMoney({
					carId: carId,
					state: this.state
				}).then(resp => {
					let data = resp.data;
					this.cars = data.carList;
					this.showPay = data.showPay;
					this.type = data.type;
					let list = data.itemList;
					this.carsSelect = this.cars.filter(obj => obj.id == carId && obj.price > 0).map(obj => obj.id)
					Object.assign(this.item, {
						itemsPrice: data.itemsPrice,
						businessId: data.businessId,
						list: list
					})
					this.businessAble = list.filter(obj => obj.pay == 1).length == list.length;
					let selectCar = this.list.filter(obj => obj.id == carId).pop();
					let carNo = selectCar.carNo;
					this.itemSelect = data.itemList.filter(obj => obj.pay == 0).map(obj => obj.id)
					this.businessSelect = this.itemSelect.length == 0 ? [] : [1]
					this.list = [];
				})
			},
			searchFn() {
				this.list = [];
				this.cars = [];
				this.carsSelect = [];
				this.itemSelect = [];
				this.businessSelect = []
				this.item = {
					itemsPrice: '',
					businessId: '',
					list: []
				}
				this.$api.searchPartCar(this.p).then(resp => {
					this.list = resp.data;
				})
			}

		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.list {
		margin: 40rpx;
	}

	.card {
		.title {
			padding: 30rpx;
			box-sizing: border-box;
			font-size: 34rpx;
			font-weight: bold;
		}
	}

	.content {
		display: flex;
		flex-direction: column;
		padding: 30rpx;
		box-sizing: border-box;
		color: #999;
	}

	.c-item {
		display: flex;
		align-items: center;
		margin: 15rpx 30rpx;
		padding: 18rpx 30rpx;
		border-radius: 10rpx;
		background-color: #fff;
		border: 1rpx solid #f5f5f5;

		.l {}

		.c {
			font-size: 30rpx;
			color: #191919;
			font-weight: bold;
			margin-left: 20rpx;
		}

		.r {
			font-size: 30rpx;
			color: #ff4200;
			font-weight: bold;
			margin-left: auto;
		}
	}

	.bottom {
		min-height: 100rpx;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;

		.box {
			display: flex;
			width: 100%;
			min-height: 100rpx;
			align-items: center;

			.l {
				padding-left: 30rpx;
				flex: 2;

				.t1 {
					color: #333;
				}

				.t2 {
					color: #ff4200;
					font-size: 38rpx;
					font-weight: bold;
				}
			}

			.r {
				flex: 1;

				.btn {
					background-color: #ff4200;
					min-height: 100rpx;
					display: flex;
					color: #fff;
					font-size: 30rpx;
					align-items: center;
					justify-content: center;
				}
			}
		}
	}

	@import '@/common/common.scss'
</style>
