<template>
	<view class="content">
		<view class="nav">
			<view class="nav-item" v-for="item in navList" :key="item.ctype" :class="{'action': ctype == item.ctype}"
				@click="getYjList('re',item.ctype)">
				{{item.name}}
			</view>

		</view>
		<view class="" style="height: 20rpx;">

		</view>
		<view class="search-box flex">
			<input type="text" v-model="phone" placeholder="输入手机号码" />
			<view class="search-btn" @click="goCz()">
				充值
			</view>
		</view>
		<template v-if="ctype == 2 || ctype == 3">
			<picker @change="bindPickerChange" :value="chooseId" :range="provinces" range-key="label">
				<view class="search-box sf-wrap flex" v-if="ctype == 3">
					<view class="">
						省份
					</view>
					<view class="">{{province || '请选择省份'}}</view>
				</view>

			</picker>
			<view class="search-box sf-wrap flex" v-if="ctype == 2">
				<view class="">
					省市
				</view>
				<view class="" style="width: 150px;height: 100%;text-align: right;">
				 <qiaoSelect :keyId="1" :dataList="dataList" phText="选择省市" phColor="#999999" showField="name" searchKey="name"
				        :showObj="showObj" :showBorder="false" :disabled="false" @change="selectChange" @input='inputChange'></qiaoSelect>
				</view>
			</view>
			<view class="search-box sf-wrap flex">
				<view class="">
					姓名
				</view>
				<input type="text" placeholder="请输入户主姓名" class="name-inp" v-model="userName" />
			</view>
			<!-- 户号 -->
			<view class="search-box sf-wrap flex">
				<view class="">
					户号
				</view>
				<input type="text" placeholder="请输入户号" class="name-inp" v-model="rechargeno" />
			</view>
			<view class="search-box sf-wrap flex" v-if="ctype == 3">
				<view class="">
					金额
				</view>
				<input type="text" placeholder="请输入充值金额" class="name-inp" v-model="sbjzt" />
			</view>
			<!-- jfjg -->
			<view class="search-box sf-wrap flex" v-if="ctype == 3">
				<view class="">
					缴费机构
				</view>
				<input type="text" placeholder="请输入缴费机构" class="name-inp" v-model="jfjg" />
			</view>
		</template>

		<view class='search-box sf-wrap flex' v-if="userInfo.integral > 0">
			<view>积分抵扣</view>
			<view class='discount acea-row row-middle'>
				<view style="margin-right: 10rpx;"> 当前积分
					<text class='num font-color'>{{userInfo.integral || 0}}</text>
				</view>
				<view class="cb" @click="changeUseIntegral">
					<view v-show="useIntegral" class="cb-in">
					</view>
				</view>
			</view>
		</view>
		<view v-if="ctype != 3" class="item-wrap" v-for="item in info">
			<view class="tit">
				{{item.cname}}
			</view>
			<view class="item-list flex">
				<view class="item " v-for="itemt in item.goods" :class="{'action': itemt.goods_id == choose.goods_id}"
					@click="chooseGood(itemt)">
					<view class="num">
						{{itemt.num}}元
					</view>
					<!-- <view class="base-price">
						{{itemt.price}}
					</view> -->
				</view>
			</view>
			<template v-if="item.area">
				<view class="tit-area">
					地区：
				</view>
				<view class="area-item">
					<text v-for="area in item.area">{{area}}</text>
				</view>
			</template>

		</view>
		<view class="item-wrap" v-if="content && ctype == 1 && info.length > 0">
			<view class="tit">
				注意事项
			</view>
			<view class="tip" v-html="content">

			</view>
		</view>
		<uni-popup ref="popup" type="bottom">
			<view class="cz-model">
				<view class="price">
					{{priceInfo.payPrice}}
				</view>
				<view class="">
					{{choose.goods_name}}
				</view>
				<view class="">
					到账时间：1-96小时 （高峰期96小时内）
				</view>
				<view class="">
					充值号码：<text class="tip">{{phone}}</text>
				</view>
				<view class="tip tips">
					请仔细核对号码。输错号码后果自负
				</view>
				<view class="pay-type-list ">
				</view>
				<!-- <view class='item acea-row row-between-wrapper' v-if="userInfo.integral > 0"> -->

				<view class="btn" @click="goNew">
					立即充值
				</view>
			</view>
		</uni-popup>
		<payment :payMode="cartArr" :pay_close="pay_close" :isCall="true" :totalPrice="totalPrice"
			@changePayType="changePayType" @onChangeFun="onChangeFun"></payment>
	</view>

</template>

<script>
	import qiaoSelect from '@/uni_modules/qiao-select/components/qiao-select/qiaoSelect.vue'
	import payment from '@/components/payment';
	import {
		getCzList,
		createCz,
		computedCz,
		getCity
	} from '@/api/three'
	import {
		getUserInfo
	} from '@/api/user.js'
	import {
		getCityData
	} from '@/api/api.js'
	// import { passUser } from '@/api/zero.js'
	export default {
		components: {
			payment,
			qiaoSelect
		},
		data() {
			return {
				dataList: [],
				jfjg: '',
				sbjzt: 0,
				rechargeno: '',
				toPay: false,
				paying: false,
				navList: [{
						name: '话费充值',
						ctype: 0
					},
					// {
					// 	name: '话费快充',
					// 	ctype: 1
					// },
					{
						name: '电费充值',
						ctype: 2
					},
					{
						name: '水费充值',
						ctype: 3
					}
				],
				useIntegral: false,
				phone: '',
				info: [],
				content: '',
				choose: {
					goods_id: 0
				},
				payType: 1,
				payName: 'weixin',
				userInfo: {},
				ctype: 0,
				province: '', //省份
				provinces: [],
				chooseId: 0,
				priceInfo: {},
				userName: '',
				totalPrice: 0,
				pay_close: false,
				cartArr: [{
						"name": "微信支付",
						"icon": "icon-weixin2",
						value: 'weixin',
						title: '使用微信快捷支付',
						payStatus: 1,
					},
					{
						"name": "余额支付",
						"icon": "icon-yuezhifu",
						value: 'yue',
						title: '可用余额:',
						payStatus: 1,
					},
				],
			}
		},
		onLoad() {
			this.getUserInfo()
			this.getCzList()
			this.getCityData()
			this.getCity()
		},
		onShow() {},
		onReachBottom() {

		},
		onReady() {

		},
		watch: {
			sbjzt(n, o) {
				// if(this.choos)
				if (n > this.userInfo.integral) {
					this.useIntegral = false
				}
			}
		},
		methods: {
			getCity() {
				getCity().then(res => {
					console.log(res)
					let arr = []
					res.data.forEach((item,index) => {
						arr.push({
							name: item,
							id: index
						})
					})
					this.dataList = arr
					console.log(this.dataList)
				})
			},
			selectChange(e) {
				console.log(e,'selectChange')
				if(e) {
					this.province = e.name
				}else {
					this.province = ''
				}
			},
			inputChange(e) {
				console.log(e,'inputChange')
			},
			changePayType(type) {
				console.log(type)
				// this.payType = type
			},
			getCityData() {
				getCityData().then(res => {
					console.log(res)
					this.provinces = res.data
				})
			},
			bindPickerChange(e) {
				console.log(e)
				this.province = this.provinces[e.detail.value].label
			},
			getYjList(tip, ctype) {
				this.ctype = ctype
				this.info = []
				this.choose = {}
				this.getCzList()
			},
			changeUseIntegral: function() {
				if (this.ctype == 3) {
					if (!this.sbjzt) {
						return this.$util.Tips({
							title: '请输入充值金额'
						});
					}
					if (this.sbjzt > this.userInfo.integral) {
						this.useIntegral = false
					} else {
						this.useIntegral = !this.useIntegral
						this.computedPrice();
					}
				} else {
					if (this.choose.price > this.userInfo.integral) {
						this.useIntegral = false
					} else {
						this.useIntegral = !this.useIntegral
					}
					if (this.choose.price) {
						this.computedPrice();
					}
				}

			},
			// 计算价格
			computedPrice(tit) {
				computedCz({
					integral: this.useIntegral ? 1 : 0,
					price: this.ctype == 3 ? this.sbjzt : this.choose.price,
					uid: this.userInfo.uid
				}).then(res => {
					this.priceInfo = res.data
					this.totalPrice = res.data.payPrice
					if(tit == 'open') {
						this.pay_close = true
					}
				})
			},
			getUserInfo: function() {
				let that = this;
				getUserInfo().then(res => {
					that.userInfo = res.data
					this.cartArr[1].number = res.data.now_money
				});
			},
			//选择支付方式
			changePayType(type) {
				this.payType = type;
				if (this.payType == 1) {
					this.payName = 'weixin';
				}
				if (this.payType == 2) {
					this.payName = 'ali';
				}
				if (this.payType == 3) {
					this.payName = 'yue';
				}
			},
			goCz() {
			
				if (!this.phone) {
					return this.$util.Tips({
						title: '请输入手机号'
					});
				}
				var pattern = /^1[0-9]{10}$/;
				if (!pattern.test(this.phone)) {
					return this.$util.Tips({
						title: '请输入正确的手机号'
					});
				}
				
				if (this.ctype == 2) {
					if (!this.choose.goods_id) {
						return this.$util.Tips({
							title: '请选择需要充值的套餐'
						});
					}
					if (!this.province) {
						return this.$util.Tips({
							title: '请选择省份'
						});
					}
					if (!this.userName) {
						return this.$util.Tips({
							title: '请输入姓名'
						});
					}
				} else if (this.ctype == 3) {
					if(!this.sbjzt) {
						return this.$util.Tips({
							title: '请输入充值金额'
						});
					}
					if(!this.jfjg) {
						return this.$util.Tips({
							title: '请输入缴费机构'
						});
					}
				} else {
					if (!this.choose.goods_id) {
						return this.$util.Tips({
							title: '请选择需要充值的套餐'
						});
					}
					// 校验手机
					let phoneType = this.getMobileOperator(this.phone)
					if (this.choose.goods_name.indexOf(phoneType) == -1) {
						this.choose = {}
						return uni.showModal({
							title: '温馨提醒',
							content: `您当前的手机号为${phoneType}号码，与充值套餐的运营商不一致，请重新选择套餐！`,
							showCancel: false
						})
					}
				}
				if(this.ctype == 3) {
					this.computedPrice('open')
				}else {
					this.pay_close = true
				}
				// this.$refs.popup.open()
			},
			getMobileOperator(phoneNumber) {
				// 移动号段
				var cmccPrefixes = ['134', '135', '136', '137', '138', '139', '150', '151', '152', '157', '158', '159',
					'182', '183', '184', '187', '188', '178', '147', '172', '198'
				];
				// 联通号段
				var cuccPrefixes = ['130', '131', '132', '155', '156', '185', '186', '145', '176', '175', '166'];
				// 电信号段
				var ctcPrefixes = ['133', '153', '180', '181', '189', '177', '173', '199'];
				// 虚拟运营商号段
				var virtualPrefixes = ['170', '171'];
				var prefix = phoneNumber.substring(0, 3);

				if (cmccPrefixes.includes(prefix)) {
					return '移动';
				} else if (cuccPrefixes.includes(prefix)) {
					return '联通';
				} else if (ctcPrefixes.includes(prefix)) {
					return '电信';
				} else if (virtualPrefixes.includes(prefix)) {
					return '虚拟运营商';
				} else {
					return '未知运营商';
				}
			},
			onChangeFun(e) {
				// 
				console.log(e)
				let that = this
				if (e.action == 'payClose') {
					this.pay_close = false
					return
				} else {
					if (e.value == 'yue') {
						if (that.priceInfo.payPrice * 1 > that.userInfo.now_money) {
							return this.$util.Tips({
								title: '当前余额不足'
							});
						}
					}

					let qdata = {
						goods_id: this.ctype== 3?"": this.choose.goods_id,
						rechargeno: this.phone,
						province: this.province,
						pay_type: e.value,
						num: this.ctype == 3? this.sbjzt: this.choose.num,
						pay_price: this.priceInfo.payPrice,
						store_id: 0,
						user_phone: this.phone,
						real_name: this.userName,
						deduction_price: this.priceInfo.deductionPrice,
						deduction_integral: this.priceInfo.usedIntegral,
						cid:this.ctype==3?"": this.choose.cid,
						goods_name:this.ctype==3?this.jfjg: this.choose.goods_name,
						type: this.ctype == 0? 1: this.ctype,
						// #ifdef MP
						'from': 'routine',
						// #endif
						// #ifdef H5
						'from': this.$wechat.isWeixin() ? 'weixin' : 'weixinh5',
						// #endif
					}
					if (this.ctype == 2) {
						qdata.rechargeno = this.rechargeno
					}
					if (that.paying) {
						return
					}
					that.paying = true
					createCz(qdata).then(res => {
						setTimeout(() => {
							that.paying = false
							that.getUserInfo()
						}, 2500)
						let status = res.data.status,
							// orderId = res.data.result.order_id,
							jsConfig = res.data.result.jsConfig
						// goPages = '/pages/goods/order_pay_status/index?order_id=' + orderId + '&msg=' + res
						// .msg +
						// '&type=6' + '&totalPrice=' + this.totalPrice + '&pay_type=' + e.value
						switch (status) {
							case 'ORDER_EXIST':
							case 'EXTEND_ORDER':
							case 'PAY_ERROR':
								uni.hideLoading();
								that.pay_close = false
								return that.$util.Tips({
									title: res.msg
								});
								break;
							case 'SUCCESS':
								uni.hideLoading();
								// if (that.BargainId || that.combinationId || that.pinkId || that.seckillId ||
								// 	that
								// 	.discountId)
								// 	return that.$util.Tips({
								// 		title: res.msg,
								// 		icon: 'success'
								// 	}, {
								// 		tab: 4,
								// 		url: goPages+ '&pay_end=SUCCESS'
								// 	});
								that.pay_close = false
								return that.$util.Tips({
									title: res.msg,
									icon: 'success'
								});
								break;
							case 'WECHAT_PAY':
								that.toPay = true;
								// #ifdef MP
								/* that.toPay = true; */
								let mp_pay_name = ''
								if (uni.requestOrderPayment) {
									mp_pay_name = 'requestOrderPayment'
								} else {
									mp_pay_name = 'requestPayment'
								}
								uni[mp_pay_name]({
									timeStamp: jsConfig.timestamp,
									nonceStr: jsConfig.nonceStr,
									package: jsConfig.package,
									signType: jsConfig.signType,
									paySign: jsConfig.paySign,
									success: function(res) {
										uni.hideLoading();
										return that.$util.Tips({
											title: '支付成功',
											icon: 'success'
										});
									},
									fail: function(e) {
										uni.hideLoading();
										return that.$util.Tips({
											title: '取消支付'
										});
									},
									complete: function(e) {
										uni.hideLoading();
										//关闭当前页面跳转至订单状态
										if (res.errMsg == 'requestPayment:cancel') return that
											.$util
											.Tips({
												title: '取消支付'
											});
									},
								})
								// #endif
								// #ifdef H5
								this.$wechat.pay(res.data.result.jsConfig).then(res => {
									return that.$util.Tips({
										title: '支付成功',
										icon: 'success'
									});
								}).catch(res => {
									if (!this.$wechat.isWeixin()) {
										// uni.redirectTo({
										// 	url: goPages +
										// 		'&msg=支付失败&status=2' + '&pay_end=SUCCESS'
										// })
									}
									if (res.errMsg == 'chooseWXPay:cancel') return that.$util.Tips({
										title: '取消支付'
									});
								})
								// #endif
								break;
							case 'PAY_DEFICIENCY':
								uni.hideLoading();
								//余额不足
								return that.$util.Tips({
									title: res.msg
								});
								break;
							case "WECHAT_H5_PAY":
								uni.hideLoading();
								that.$util.Tips({
									title: '订单创建成功!'
								});
								setTimeout(() => {
									location.href = res.data.result.jsConfig.mweb_url;
								}, 2000);
								break;

							case 'ALIPAY_PAY':
								//#ifdef H5
								if (this.from === 'weixin') {

								} else {
									uni.hideLoading();
									that.formContent = res.data.result.jsConfig;
									that.$nextTick(() => {
										document.getElementById('alipaysubmit').submit();
									})
								}
								//#endif
								// #ifdef MP
								uni.navigateTo({
									url: `/pages/users/alipay_invoke/index?id=${orderId}&link=${jsConfig.qrCode}`
								});
								// #endif
								// #ifdef APP-PLUS
								uni.requestPayment({
									provider: 'alipay',
									orderInfo: jsConfig,
									success: (e) => {
										uni.showToast({
											title: "支付成功"
										})
										let url = '/pages/goods/order_pay_status/index?order_id=' +
											orderId +
											'&msg=支付成功';
										setTimeout(res => {
											uni.redirectTo({
												url: url
											})
										}, 2000)

									},
									fail: (e) => {
										let url = '/pages/goods/order_pay_status/index?order_id=' +
											orderId +
											'&msg=支付失败';
										uni.showModal({
											content: "支付失败",
											showCancel: false,
											success: function(res) {
												if (res.confirm) {
													uni.redirectTo({
														url: url
													})
												} else if (res.cancel) {
													console.log('用户点击取消');
												}
											}
										})
									},
									complete: () => {
										uni.hideLoading();
									},
								});
								// #endif
								break;
						}

					}).catch(err => {
						that.paying = false
					})
				}

			},
			chooseGood(item) {
				this.choose = item
				if (this.choose.price > this.userInfo.integral) {
					this.useIntegral = false
				}
				// if(this.userInfo)
				this.computedPrice()
			},
			getCzList() {
				let that = this
				if (this.ctype == 3) return
				uni.showLoading({
					title: '加载中...'
				})
				getCzList({
					ctype: that.ctype
				}).then(res => {
					uni.hideLoading()
					this.info = res.data
					this.info.forEach(item => {
						if (item.goods.length > 0) {
							item.goods.forEach(itemt => {
								if (itemt.desc && itemt.desc.split('<p>').length > 1) {
									that.content = itemt.desc
								}
							})
						}
					})
				})
			},

		}
	}
</script>

<style lang="scss" scoped>
	.flex {
		display: flex;
		align-items: center;
		// justify-content: space-between;
	}

	.content {
		// padding-top: 20rpx;
		padding-bottom: 20rpx;
	}

	.phone {
		width: 690rpx;
		height: 80rpx;
		background-color: #fff;
		border-radius: 220rpx;
		margin: 0 auto 20rpx;
	}

	.item-wrap {

		width: 690rpx;
		background-color: #fff;
		margin: 0 auto 20rpx;
		padding: 20rpx 34rpx;
		border-radius: 20rpx;

		.tip {
			width: 620rpx;
			margin: auto;
			background-color: #e9f1fe;
			padding: 20rpx;
			border-radius: 20rpx;
			margin-top: 40rpx;

		}

		.tit {
			font-size: 30rpx;
			font-weight: bold;
		}

		.item-list {
			justify-content: flex-start;
			padding-top: 40rpx;

			.item {
				// width: 192rpx;
				border-radius: 20rpx;
				margin-right: 20rpx;
				background-color: #e9f1fe;
				text-align: center;
				padding: 40rpx;

				.num {
					color: #409EFF;
					font-weight: bold;
					font-size: 28rpx;
				}

				.base-price {
					padding-top: 10rpx;
					font-size: 22rpx;
				}

				.price {
					font-size: 28rpx;
					color: #f3253a;
					padding-top: 10rpx;
				}
			}

			.action {
				border: 1px solid #f3253a;
			}
		}
	}



	.top-search {
		height: 80rpx;
		padding: 0 20rpx;
		width: 100%;
		height: 116rpx;
		z-index: 99;

		.search {
			width: 24rpx;
			margin-right: 20rpx;
		}

	}

	.search-box {
		justify-content: flex-start;
		width: 690rpx;
		height: 72rpx;
		background: rgb(255, 255, 255);
		border-radius: 30rpx;
		padding: 0 10rpx 0 20rpx;
		margin: 0 auto 20rpx;

		input {
			flex-grow: 1;
			height: 72rpx;
			line-height: 72rpx;
		}

		.search-btn {
			flex-shrink: 0;
			width: 110rpx;
			height: 52rpx;
			text-align: center;
			line-height: 50rpx;
			color: #fff;
			background-color: #409EFF;
			border-radius: 26rpx;

		}
	}

	.cz-model {
		width: 750rpx;
		background-color: #fff;
		padding: 60rpx 0 30rpx;
		text-align: center;
		border-radius: 25rpx 25rpx 0 0;

		view {
			padding: 10rpx 0;
		}

		.price {
			color: #409eff;
			font-size: 48rpx;
			font-weight: bold;
		}

		.tip {
			color: #409eff;
		}

		.tips {
			padding-bottom: 20rpx;
		}

		.btn {
			width: 690rpx;
			text-align: center;
			line-height: 60rpx;
			color: #fff;
			background-color: #409eff;
			border-radius: 40rpx;
			margin: auto;
		}
	}

	.pay-type-list {
		margin-top: 20upx;
		background-color: #fff;
		padding-left: 60upx;

		.type-item {
			height: 120upx;
			padding: 20upx 0;
			display: flex;
			justify-content: flex-start;
			align-items: center;
			padding-right: 60upx;
			font-size: 30upx;
			position: relative;
		}

		.icon {
			width: 100upx;
			font-size: 52upx;
		}

		.iconyue {
			color: #fe8e2e;
		}

		.iconweixin {
			color: #36cb59;
		}

		.iconzhifubao {
			color: #01aaef;
		}

		.tit {
			font-size: 28rpx;
			color: #000;
			margin-bottom: 4upx;
		}

		.con {
			flex: 1;
			display: flex;
			flex-direction: column;
			font-size: 26rpx;
			color: #000;
		}
	}

	.tit-area {
		font-size: 26rpx;
		padding: 20rpx 0;
	}

	.area-item {
		padding-left: 20rpx;
		font-size: 24rpx;
	}

	.nav {
		display: flex;
		justify-content: space-evenly;

		.nav-item {
			width: 50%;
			line-height: 60rpx;
			text-align: center;
			color: #1890FF;
			border: 1px solid #1890FF;
			font-size: 28rpx;
			background-color: #fff;
		}

		.action {
			background-color: #1890FF;
			color: #fff;
			font-weight: bold;
		}
	}

	.sf-wrap {
		justify-content: space-between;
		padding: 0 20rpx;
	}

	.cb {
		width: 30rpx;
		border-radius: 50%;
		height: 30rpx;
		border: 1px solid #1890FF;
		// position: absolute;
		display: flex;
		justify-content: center;
		align-items: center;

		.cb-in {
			width: 20rpx;
			height: 20rpx;
			border-radius: 50%;
			background-color: #1890FF;
		}
	}

	.name-inp {
		// width: ;
		flex-grow: 1;
		text-align: right;
	}
</style>