<template>

	<view class="min-body" v-if="isShow">
		<u-notice-bar v-if="notification" :text="notification"></u-notice-bar>
		<!-- 充值服务商 -->
		<rechargeService :logo="InforData['spec'][0]['b_goods_img']" :title="InforData['spec'][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="title-box flbtn">
				<view class="big-333 bold">
					请选择充值运营商
				</view>
			</view>
			<view class="goods-type" style="padding-top: 20rpx;">
				<view :class="'title '+ (activeName == key?'active':'')" v-for="(item,key,index) in SkuList" :key="index"
					@tap="activeName = key">
					{{key}}
				</view>
			</view>
		</view>
		<!-- 充值面额 -->
		<view class="white-box" v-if="activeName">
			<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" v-if="InforData['spec'][index]['deduction_prop'] > 0">
			<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>
		</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">
			<view class="bd-box flbtn">
				<view class="">
					<view class="big-666 bold">
						应付金额：<text style="color: #FF2A30;">￥{{needPay}}</text>
					</view>
					<view class="lit-666">
						获得佣金：￥{{yongjin}}
					</view>
					<view class="lit-666">
						消费补贴卡抵扣：￥{{FormData['is_deduction']?backAmount:0}}
					</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="rechargeNow">
						立即充值
					</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: '',
				// 当前运营商下所选的规格
				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: ''
			}
		},
		computed: {
			dikou() {
				try {
					if (this['InforData']['spec']['length'] == 0) {
						return 0
					};
					let data = this['SkuList'][this['activeName']][this['activeSku']];
					return (data.price - data.buying_price) * (data.deduction_prop / 100)
				} catch (e) {
					//TODO handle the exception
				}
			},

			needPay: {
				get() {
					try {
						if (!this['FormData']['is_deduction']) {
							return this['SkuList'][this['activeName']][this['activeSku']]['price'] / 100
						}
						return (this['InforData']['spec']['length'] > 0 ? ((this['SkuList'][this['activeName']][this[
								'activeSku']][
								'price'
							] - this.backAmount *
							100) / 100) : 0)
					} catch (e) {
						//TODO handle the exception
					}
				}
			},
			yongjin: {
				get() {
					try {
						return this['InforData']['spec']['length'] > 0 ? (this['SkuList'][this['activeName']][this[
							'activeSku']][
							'self_commission'
						]) : 0
					} catch (e) {
						//TODO handle the exception
					}
				}
			},
		},
		methods: {
			/**
			 * @充值下单
			 * */
			rechargeNow() {
				uni.showLoading({
					title: '加载中'
				})
				if (this['FormData']['account'] == '') {
					return this.$u.toast('请输入充值帐号')
				};

				this['FormData']['spec_id'] = this['SkuList'][this['activeName']][this['activeSku']]['b_sku_id'];
				// 判断用户是否抵扣
				if (this['FormData']['is_deduction']) {
					this['FormData']['deduction_amount'] = this['backAmount'];
				} else {
					this['FormData']['deduction_amount'] = 0;
				}
				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();
						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;
			},

			/**
			 * @是否抵扣
			 * */
			checkedFunc(e) {
				this['FormData']['is_deduction'] = (+e);
			},

			/**
			 * @地区选择
			 * */
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e;
				if (this['columnData']['length'] <= 0) return
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.columnData[index])
				}
			},
			/**
			 * @回调参数为包含columnIndex、value、values
			 * */
			confirm(e) {
				// console.log('confirm', e);

				this['area'] = `${e['value'][0]['short_name']}`;
				// 因为南网充值与国网充值提交参数不一样,前者需要两个参数,后者接口只需要area字段所以在此处判断是否存在
				this['city'] = e['value'][1] ? e['value'][1]['short_name'] : '';

				this['FormData']['city'] = e['value']['length'] >= 2 ? e['value'][1]['code'] : e['value'][0]['code'];
				// this[] = e['value'][1]['city_name'];
				this.show = false;

			},

			/**
			 * @输入账号组件返回赋值
			 * */
			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;
	}

	.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: #fff;
		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: #F7F5EF;
		// width: 90%;
		text-align: center;
		// margin: 0 5%;
		padding: 40rpx 0;
	}

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