<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="InforData['account_type']" 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="Arer">
				<u-cell-group :border="false">
					<u-cell @click="show = true" icon=" " :title="Areatext"></u-cell>
				</u-cell-group>
			</view>
			<view class="cardid" v-if="FormData['g_id'] == 10">
				<input maxlength="6" type="text" v-model="FormData['idcard']" placeholder="请输入身份证号后六位">
			</view>
		</view>
		<!-- 充值面额 -->
		<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 '+(index == i ?'active':'')" v-for="(v,i) in InforData['spec']" :key="i"
					@click="index = i">
					<view class="big-333 bold" style="color: #6C3D05;">
						{{v.b_sku_time}}
					</view>
					<view class="sjjg">
						售价：￥{{v.price/100}}
					</view>
					<view class="big-333 bold" style="color: #6C3D05;text-decoration: line-through;">
						原价：￥{{v.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">
			<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" @confirm="confirm" @change="changeHandler"
			keyName="city_name"></u-picker>
		<!-- 历史记录弹框 -->
		<u-modal :show="historyshow" title="历史记录" :showCancelButton="false" confirmText="暂不选择"
			@confirm="historyshow = false">
			<template v-slot:default></template>
			<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>
		</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';
	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: '',
				FormData: {
					// 充值账号
					account: '',
					// 商品ID
					g_id: 0,
					// 规格ID
					spec_id: 0,
					// 地区
					area: '',
					// 地级
					city: '',
					// 是否抵扣
					is_deduction: 1,
					// 身份证
					idcard: '',
					// 抵扣金额
					deduction_amount: 0,
					// 写死
					houseType: '1'
				},
				// 因为页面接口请求时间过长
				isShow: false,
				// 地址选择
				show: false,
				loading: false,
				// 一级
				columns: [
					// 一级的列表
					[],
					// 默认的二级列表
					[],
				],
				// 二级
				columnData: [],
				// 面额点击索引
				index: 0,
				backAmount: 0,
				// 用户是否需要优惠
				discount: 0,
				// 历史记录弹框
				historyshow: false,
				// 历史记录列表
				historylist: [],
				// 维护地区
				notification: ''
			}
		},
		computed: {
			dikou() {
				try {
					if (this['InforData']['spec']['length'] == 0) {
						return 0
					}
					let data = this['InforData']['spec'][this['index']]
					console.log((data.price - data.buying_price) * (data.deduction_prop / 100), 'data ');
					console.log((data.price - data.buying_price) * (data.deduction_prop / 100), '抵扣金额');
					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['InforData']['spec'][this['index']]['price'] / 100
						}
						return (this['InforData']['spec']['length'] > 0 ? ((this['InforData']['spec'][this['index']][
								'price'
							] - this.backAmount *
							100) / 100) : 0)
					} catch (e) {
						//TODO handle the exception
					}
				}
			},
			yongjin: {
				get() {
					try {
						return this['InforData']['spec']['length'] > 0 ? (this['InforData']['spec'][this['index']]['self_commission']) : 0
					} catch (e) {
						//TODO handle the exception
					}
				}
			},
			// 地区展示过滤
			Areatext() {
				if (!this['FormData']['area'] && !this['FormData']['city']) {
					return '请选择区域';
				};
				return `${this['FormData']['area']}-${this['FormData']['city']}`
			}
		},
		methods: {
			/**
			 * @充值下单
			 * */
			rechargeNow() {
				uni.showLoading({
					title: '加载中'
				})
				if (this['FormData']['account'] == '') {
					return this.$u.toast('请输入充值帐号')
				} else if (this['FormData']['area'] == '') {
					return this.$u.toast('请选择充值地区')
				} else if (this['FormData']['g_id'] == 10 && this['FormData']['idcard'] == '') {
					return this.$u.toast('请输入身份证后六位')
				} else if (this['FormData']['g_id'] == 10 && this['FormData']['idcard']['length'] < 6) {
					return this.$u.toast('请输入正确的身份证后六位')
				} else if (this['FormData']['area']['length'] == 0) {
					return this.$u.toast('请等待页面加载...')
				}

				this['FormData']['spec_id'] = this['InforData']['spec'][this['index']]['b_sku_id'];
				// 判断用户是否抵扣
				if (this['FormData']['is_deduction']) {
					this['FormData']['deduction_amount'] = this['backAmount'];
				} else {
					this['FormData']['deduction_amount'] = 0;
				}

				this.$store.dispatch('card/electricityCreateOrder2', this['FormData']).then(payres => {
					uni.hideLoading();
					console.log(payres['result']['timeStamp'], payres['result']['timestamp'], 'timeStamp');
					self.requestPay({
						payData: payres['result'],
						success: (res => {
							console.log(res, '支付成功');
							let history
							try {
								history = JSON.parse(uni.getStorageSync('historylist'));
							} catch (e) {
								history = [];
							}
							// 如果本地没有记录(第一次充值)
							if (history['length'] <= 0) {
								// console.log(2);
								uni.setStorageSync('historylist', JSON.stringify([self['FormData'][
									'account'
								]]));

							} else {
								// console.log(1);
								let index = history.indexOf(self['FormData']['account']);
								if (index != -1) {
									let i = history.splice(index, 1)[0];
									history.unshift(i);
								} else {
									// 本地已经有历史记录
									// 检查本地历史记录是否已满
									if (history['length'] >= 5) {
										// 本地记录已经满了则将第一个删除将刚刚充值的账户设置为第一个
										history.splice(0, 1);
									}
									history.unshift(self['FormData']['account']);
								}
								uni.setStorageSync('historylist', JSON.stringify(history));
							}
							uni.redirectTo({
								// url: '/pages/Myteam/Locallife?type=2'
								url: '/pages/order/orderindex-recharge'
							})
						}),
						file: (err => {
							console.log(err, '支付失败');
						})
					})
				})
			},

			getBackAmount() {
				// console.log(this['$refs'],'ref')
				this.$nextTick(e => {
					// console.log(this['$refs'],'ref')
					this.backAmount = this['$refs']['card-checked'].GetP();
				})
			},
			/**
			 * @获取充值信息
			 * */
			getGoodsInfo() {
				this.$store.dispatch('card/goodsSkuList', {
					b_goods_id: this['FormData']['g_id'],
					b_id: this['b_id']
				}).then(res => {
					// 数据获取完成之后再显示页面获取到信息之后再获取地区
					self.$store.dispatch('card/elecity').then(area => {
						self.$store.dispatch('card/maintainInfo').then(data => {
							// 展示维护区域通知
							if (data['area']['length'] > 0) {
								self['notification'] =
									`${data['area'].map(item=>item['short_name']).join("/")},部分通道维护，充值到账可能会延迟或者失败，请知悉`;
							}
							if (res['spec']['length'] > 0) {
								let arrs = ['贵州', '云南', '海南', '广东', '广西']
								switch (res['g_id']) {
									// 10 代表是南网充电渠道ID
									// 13 代表是国网充电渠道ID
									case 10:
										this['FormData']['netType'] = '南网';
										let arr1 = area.filter(item => {
											return arrs.indexOf(item['short_name']) != -1
										})
										self.AreaDataFormat(arr1, 2)
										break;
									case 13:
										this['FormData']['netType'] = '国网';
										let arr2 = area.filter(item => {
											return arrs.indexOf(item['short_name']) == -1
										})
										self.AreaDataFormat(arr2, 2)
										break;
								}
							}
						})
						uni.hideLoading();
						console.log('执行');
						self.$nextTick(() => {
							self['isShow'] = true;
							self['InforData'] = res;
							self.getBackAmount();
							try {
								let history = JSON.parse(uni.getStorageSync(
									'historylist'));
								if (history) {
									if (history['length'] == 1) {
										self['FormData']['account'] = history[0];
									} else {
										self['historylist'] = history
										self['historyshow'] = true;
									}
								}
							} catch (e) {
								//TODO handle the exception
							}
						})
			
					})
				})
			},

			/**
			 * @对后台的地区数据经行格式化
			 * */
			AreaDataFormat(area, level) {
				// 构建二级默认数组
				let _a = [];
				console.log(area,'areaareaareaarea');
				for (var i = 0; i < area['length']; i++) {
					let item1 = area[i];
					self['columns'][0].push({
						id: item1['id'],
						city_name: item1['short_name']
					});
					if (level == 2) {
						// 构建二级数组
						self['columnData'][i] = [];
						for (var j = 0; j < item1['child']['length']; j++) {
							let item2 = item1['child'][j];
							// 将二级默认数据添加至一级数组
							if (i <= 0) {
								_a.push({
									id: item2['id'],
									city_name: item2['short_name']
								})
							}
							// 将二级数据添加值二级数组中
							self['columnData'][i].push({
								id: item2['id'],
								city_name: item2['short_name']
							})
						}
					}
				}
				if (level == 2) {
					self['columns'][1] = [];
					self['columns'][1] = _a;
				}
			},

			/**
			 * @跳转客服
			 * */
			service() {
				uni.openCustomerServiceChat({
					extInfo: {
						url: SERVICEELECTRICITY,
					},
					corpId: 'ww4f46b491a045158c',

					success(e) {
						console.log(e)
					},
					fail(e) {
						console.log(e)
					}
				})
			},

			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['FormData']['area'] = `${e['value'][0]['city_name']}`;
				// 因为南网充值与国网充值提交参数不一样,前者需要两个参数,后者接口只需要area字段所以在此处判断是否存在
				this['FormData']['city'] = e['value'][1] ? e['value'][1]['city_name'] : '';
				// 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(op) {
			console.log(getApp()['globalData']['parameters'],'页面参数');
			self = this;
			this['FormData']['g_id'] = op['goods_id'] || getApp()['globalData']['parameters']['g_id'];
			this['b_id'] = op['b_id'] || getApp()['globalData']['parameters']['b_id'];
			uni.showLoading({
				title: "正在加载中..."
			})
			this.getGoodsInfo();
		}
	}
</script>

<style lang="scss">
	/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;
		height: 185rpx;
		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>
