<template>

	<view class="min-body" v-if="isShow">
		<u-notice-bar v-if="notification" :text="notification"></u-notice-bar>
		<!-- 充值服务商 -->
		<rechargeService :logo="InforData['spec'][0][0]['b_goods_img']" :title="InforData['spec'][0][0]['b_goods_name']">
		</rechargeService>
		<!-- 间隔槽 -->
		<u-gap height="20rpx"></u-gap>
		<!-- 充值账号 -->
		<rechargeUser placeholder="手机号" inputtype="number" v-model="FormData['account']" @input="input">
		</rechargeUser>
		<view class="white-box">
			<view class="goods-type">
				<view class="Operator" v-for="(item,index) in InforData['spec']" :key="index">
					<!-- {{item}} -->
					<image class="logo" :src="item[0]['logoimg']" mode="aspectFit"></image>
					<view class="goods-item">
						<view :class="'title '+ (activeGid == _item['b_sku_id']?'active':'')"
							@tap="activeName = index;activeGid = _item['b_sku_id']" v-for="_item,_index in item"
							:key="_item['b_sku_id']">
							<text class="money">{{_amount(_item['price'])}}</text>
							<text class="channel">({{_item['b_sku_name']}})</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 充值面额 -->
		<!-- <view class="white-box" v-if="activeName != -1">
			<view class="title-box flbtn">
				<view class="big-333 bold">
					面额
				</view>
			</view>
			<view class="goods-type" style="padding-top: 20rpx;">
				<view :class="'title '+(activeSku == index ?'active':'')" v-for="(item,index) in SkuList[activeName]"
					:key="item['b_sku_id']" @click="activeSku = index">
					<view class="big-333 bold" style="color: #6C3D05;">
						{{item['b_sku_time']}}
					</view>
					<view class="sjjg">
						售价：￥{{item['price']/100}}
					</view>
					<view class="big-333 bold" style="color: #6C3D05;text-decoration: line-through;">
						原价：￥{{item['original_price']/100}}
					</view>
				</view>
			</view>
		</view> -->
		<!-- 优惠 -->
		<view class="white-box">
			<view class="title-box flbtn">
				<view class="big-333 bold">
					优惠
				</view>
			</view>
			<!-- <card-checked @GitData="GitData" @checked="checkedFunc" :price="dikou" ref="card-checked"></card-checked> -->
			<deduction @change="deductionchange"  v-if="activeName != -1 && activeGid" :price="Selected['price']" :DeductionAmount="Selected['deduction_prop']" :buyingPrice="Selected['buying_price']" ></deduction>
		</view>
		<view class="white-box">
			<view class="title-box flbtn">
				<view class="big-333 bold">
					温馨提示
				</view>
			</view>
			<rich-text class="big-666" style="font-size: ;" :nodes="InforData['xuzhi']"></rich-text>
		</view>
		<u-gap height="205rpx"></u-gap>
		<view class="bottom"   v-if="activeName != -1 && activeGid">
			<view class="bd-box flbtn">
				<view class="">
					<view class="big-666 bold">
						应付金额：<text style="color: #FF2A30;">￥{{needPay}}</text>
					</view>
					<view class="lit-666" v-if="Selected['self_commission']">
						获得佣金：￥{{Selected['self_commission'] || 0}}
					</view>
					<view class="lit-666">
						消费补贴卡抵扣：￥{{this['FormData']['deduction_amount']}}
					</view>
				</view>

				<view class="right">
					<view class="service" @tap="service">
						<u-icon labelPos="bottom" labelSize="20rpx" name="kefu-ermai" label="客服"></u-icon>
					</view>
					<view class="rc-now" @click="$u.debounce(rechargeNow, 1000,true)">
						立即充值
					</view>
				</view>
			</view>

		</view>
		<!-- <u-picker :show="show" ref="uPicker" :columns="columns" @cancel="show = false" @confirm="confirm"
			@change="changeHandler" keyName="short_name"></u-picker> -->
		<!-- 历史记录弹框 -->
		<u-modal :show="historyshow" title="历史记录" :showCancelButton="false" confirmText="暂不选择"
			@confirm="historyshow = false">
			<template v-slot:default>
				<view class="slot-content" style="width:100%;">
					<u-cell-group>
						<template v-for="(item, index) in historylist">
							<u-cell icon=" " :title="item" clickable :key="index" @click="CellClick(item)"></u-cell>
						</template>
					</u-cell-group>
				</view>
			</template>
		</u-modal>
	</view>

</template>

<script>
	/**
	 * @该渠道中该页面为话费充值，慢充
	 * */
	// 客服链接
	import {
		SERVICEELECTRICITY
	} from '@/static/js/serviceurl.js'
	// 引入混入
	import mixin from '@/static/js/mixin/mixin.js'
	// 服务商组件
	import rechargeService from '@/components/recharge/recharge-Service.vue';
	// 充值账号组件
	import rechargeUser from '@/components/recharge/recharge-User.vue';
	// 充值类型
	import rechargeType from '@/components/recharge/recharge-Type.vue';
	import {
		createOrderMobileAPI,
		createOrderMobileRDAPI,
		getNyMobileAPI,
		goodsSkuListAPI
	} from '@/request/pay/index.js'
	let self;
	// buying_price 进价--渠道商给我的价格
	// price  售价 -- 
	// original_price	划线价格、
	// 条件1 可以抵扣
	// 1.(售价('price') - 进价('buying_price')) / 100  = 利润
	// 2.利润 * (可优惠价格('deduction_prop') / 100) = 最大可抵扣金额
	// 3.获取用户当前余额，检查是否足够抵扣，
	// 条件1（余额足够抵扣）
	// 余额足够抵扣则将最大抵扣金额传给后台（deduction_amount）
	// 条件2 （余额不足够抵扣）
	// 余额不够抵扣则将用户余额的最大抵扣价格穿给后台（deduction_amount）
	// 用户余额为0则穿给后台（deduction_amount）为0
	// 条件2 商品不可抵扣
	// deduction_amount 传入0

	export default {
		components: {
			rechargeService,
			rechargeUser,
			rechargeType
		},
		mixins: [mixin],
		data() {
			return {

				// 分类ID
				b_id: 0,
				InforData: {},
				area: '',
				// 因为南网充
				city: '',
				// 运营商/规格数据
				SkuList: {},
				// 当前所选运营商
				activeName: -1,
				// 当先所选充值金额
				activeGid: 0,
				// 当前运营商下所选的规格
				activeSku: 0,
				// 下单提交接口
				FormData: {
					// 充值账号
					account: '',
					// 商品ID
					g_id: 0,
					// 规格ID
					spec_id: 0,
					// 是否抵扣
					is_deduction: 1,
					// 抵扣金额
					deduction_amount: 0,
				},
				// 因为页面接口请求时间过长
				isShow: false,
				// 地址选择
				show: false,
				loading: false,
				// 面额点击索引
				index: 0,
				backAmount: 0,
				// 用户是否需要优惠
				discount: 0,
				// 历史记录弹框
				historyshow: false,
				// 历史记录列表
				historylist: [],
				// 维护地区
				notification: '',
				// 应付金额
				needPay:0
			}
		},
		computed: {
			Selected(){
				try{
					return this['InforData']['spec'][this['activeName']].find(item=>item['b_sku_id'] == this['activeGid'])
				}catch(e){
					return {}
					//TODO handle the exception
				}
			}
		},
		methods: {
			deductionchange(e){
				console.log(e,this['Selected']['b_sku_id']);
				this['needPay'] = this._amount(e['_price'])
				// 是否抵扣
				this['FormData']['is_deduction'] = Number(e['status']);
				// 抵扣金额
				this['FormData']['deduction_amount'] = this._amount(e['_Deduction_Amount']);
				this['FormData']['spec_id'] = this['Selected']['b_sku_id'];
			},
			/**
			 * @充值下单
			 * */
			rechargeNow() {
				uni.showLoading({
					title: '加载中'
				})
				if (this['FormData']['account'] == '') {
					return this.$u.toast('请输入充值帐号')
				};
			
				createOrderMobileRDAPI(this['FormData']).then(payres => {
					uni.hideLoading();
					const {
						pay_price,
						order_sn,
						type,
						openid
					} = payres['data'];
					this.$Payment.H5_Payment({
						pay_price,
						order_sn,
						type,
						openid,
						return_url: `/pages/pages-recharge/order/index`
					});
					console.log(payres, 'payres');
					// self.payment({
					// 	order_sn:payres['data']['order_sn'],
					// 	type:payres['data']['type'],
					redirect_url: '/pages/pages-recharge/order/index'
					// })
				})
			},

			// getBackAmount() {
			// 	this.$nextTick(e => {
			// 		this.backAmount = this['$refs']['card-checked'].GetP();
			// 	})
			// },
			/**
			 * @获取充值信息
			 * */
			getGoodsInfo() {
				goodsSkuListAPI({
					b_goods_id: this['FormData']['g_id'],
					b_id: this['b_id'],
					// uu_id:17551
					// TODO 正式删除
					// t:1
				}).then(res => {
					// 获取历史手机号
					getNyMobileAPI().then(Mobile => {
						if (Mobile['data']['length'] > 0) {
							self['historylist'] = Mobile['data'];
							self['historyshow'] = true;
						};
						uni.hideLoading();
						console.log(JSON.stringify(res['data']['spec'],null,5), '---------');
						// 将后台给的数据分别区分为三大运营商
						{
							let arr = JSON.parse(JSON.stringify(res['data']['spec']));
							res['data']['spec'] = [
								[],
								[],
								[]
							];
							for (let i = 0; i < arr['length']; i++) {
								let item = arr[i];
								// item['deduction_prop'] = 20
								item['title'] = item['b_sku_name'].replace(/[0-9]/g, "");
								if (item['b_sku_name'].includes('电信')) {
									item['logoimg'] = 'https://img.agrimedia.cn/chwl/v2/dianxin.png';
									res['data']['spec'][0].push(item);
									continue;
								};
								if (item['b_sku_name'].includes('移动')) {
									item['logoimg'] = 'https://img.agrimedia.cn/chwl/v2/yidong.png';
									res['data']['spec'][1].push(item);
									continue;
								};
								if (item['b_sku_name'].includes('联通')) {
									item['logoimg'] = 'https://img.agrimedia.cn/chwl/v2/liantong.png';
									res['data']['spec'][2].push(item);
								}
							}
						}
						console.log(res['data']['spec'], 'spec'); {
							self['InforData'] = res['data']
						};
						self['isShow'] = true;
						// self['FormData']['code'] = 
						if (!res['data']?.spec) {
							res['data']['spec'] = []
						}
						// 格式话规格数据
						let SkuList = {};
						for (let i = 0; i < res['data']['spec']['length']; i++) {
							let item = res['data']['spec'][i];
							if (typeof SkuList[item['b_sku_name']] == "undefined") {
								SkuList[item['b_sku_name']] = [];
							}
							SkuList[item['b_sku_name']].push(item);
						};
						this['SkuList'] = SkuList;
						// self.getBackAmount();
					})
				})
			},

			/**
			 * @跳转客服
			 * */
			service() {
				window.location.href = SERVICEELECTRICITY;
			},

			GitData(d) {
				// console.log('git data', d)
				this['backAmount'] = d;
			},
			/**
			 * @输入账号组件返回赋值
			 * */
			input(value) {
				this['FormData']['account'] = value;
				// console.log(this['account']);
			},

			CellClick(item) {
				this.$set(this['FormData'], 'account', item)
				this['historyshow'] = false;
			}

		},
		onLoad(openitn) {
			// console.log(openitn,'openitno');
			self = this;
			this['FormData']['g_id'] = openitn['goods_id'] || getApp()['globalData']['parameters']['goods_id'];
			this['b_id'] = openitn['b_id'] || getApp()['globalData']['parameters']['b_id'];
			uni.showLoading({
				title: "正在加载中..."
			})
			this.getGoodsInfo();
		}
	}
</script>

<style lang="scss">
	// 维护通知
	.Maintenance-notification {
		width: 100%;
	}

	/deep/ .u-input__content__field-wrapper__field {
		height: 70rpx;
	}

	/deep/ .u-cell__body {
		padding: 20rpx 0 !important;
	}

	.cardid {
		padding: 20rpx 9rpx;
		font-size: 30rpx;
	}

	.goods-type {

		// display: grid;
		// grid-template-columns: auto auto;
		// grid-gap: 20rpx;
		.Operator {
			.logo {
				width: 200rpx;
				height: 50rpx;
				margin: 32rpx 0;
			}

			.goods-item {
				display: grid;
				grid-template-columns: auto auto;
				grid-gap: 20rpx;

				.money {
					font-size: 46rpx;
					color: rgba(51, 51, 51, 1);
					position: relative;

					&::after {
						content: '元';
						// position: absolute;
						// bottom: 0;
						// right: 0;
						font-size: 16rpx;
						margin-left: 8rpx;
					}
				}

				.channel {
					font-size: 19rpx;
					color: rgba(153, 153, 153, 1);
				}

				// .unit{
				// 	font-size: 23rpx;
				// }
			}
		}
	}

	.bottom {
		background-color: #ededed;
		position: fixed;
		bottom: 0;
		width: 100vw;

		border-radius: 20rpx 20rpx 0 0;

		.bd-box {
			padding: 20rpx;
			background-color: #fff;
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
			height: 145rpx;

		}

		.right {
			display: flex;
			align-items: center;

			.service {
				margin-right: 20rpx;
			}

			.rc-now {
				background-color: #E7C86D;
				border-radius: 20rpx;
				color: #fff;
				height: 85rpx;
				line-height: 85rpx;
				padding: 0 40rpx;
				font-size: 28rpx;
			}
		}

	}

	.sjjg {
		color: #D3A219;
		font-size: 36rpx;
		margin: 10rpx 0;
	}


	.white-box {
		background-color: rgba(245, 245, 245, 1);
		padding: 20rpx;
		margin-top: 20rpx;

		.title-box {
			padding-bottom: 20rpx;
			border-bottom: 2rpx solid #EDEDED;
		}
	}

	.title {
		font-size: 32rpx;
		color: #6B3D05;
		border-radius: 20rpx;
		font-weight: bold;
		background-color: #FFFFFF;
		// width: 90%;
		text-align: center;
		// margin: 0 5%;
		padding: 40rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.active {
		background-color: #F7E7BA;
	}
</style>
