<template>
	<ax-body blank="0" hideIndicatorArea>
		<image src="@/static/img/page-bg01.png" class="page-background"></image>
		<view class="body" :class="{visit}">
			<!-- 主图 -->
			<view class="app-flex c-center host-graph">
				<image src="@/static/img/charging-01.png" mode="widthFix" class="image"></image>
			</view>
			<!-- 主参数 -->
			<view class="parameter">
				<view class="param"><view class="value">{{deviceInfo.current}}</view><view class="name">电流A</view></view>
				<view class="param"><view class="value">{{getVolt()}}</view><view class="name">电压V</view></view>
				<view class="param"><view class="value">{{deviceInfo.power}}</view><view class="name">功率KW</view></view>
			</view>
			<view class="block">
				<view class="card">
					<view class="title">终端信息</view>
					<view class="cell"><view class="lable">终端状态</view><view class="contet">{{getDeviceStatusLable(deviceInfo.deviceStatus)}}</view></view>
					<view class="cell"><view class="lable">终端编号</view><view class="contet">{{deviceInfo.deviceNo}}</view></view>
					<view class="cell"><view class="lable">充电电站</view><view class="contet">{{deviceInfo.thirdPartyStationName}}</view></view>
					<view class="cell"><view class="lable">充电终端</view><view class="contet">{{deviceInfo.deviceName}}</view></view>
					<view class="cell"><view class="lable">车位编号</view><view class="contet">{{deviceInfo.parkNo ? deviceInfo.parkNo : "无"}}</view></view>
				</view>
			</view>
			<view class="block">
				<view class="card">
					<view class="title">
						<text>费用信息</text>
						<view @click="$app.url.goto('/pages/site-more/site-more?show=1&stationId='+stationInfo.id)" class="more"><text>价格详情</text><icon class="ax-iconline i-arrow-right icon"></icon></view>
					</view>
					<view class="cell">
						<view class="lable">{{personal == 1?'当前电价':'集团折扣价'}}</view>
						<view class="contet app-flex middle">
							<view v-if="personal == 1"><text class="money">{{nowPriceTime.price?parseFloat(nowPriceTime.price).toFixed(4):"0.0000"}}</text><text> 元/度</text></view>
							<view v-else>
								<text class="obsolete"> {{nowPriceTime.price?parseFloat(nowPriceTime.price).toFixed(4):"0.0000"}} 元/度 </text>
								<text class="money">{{getCurrEcPrice()}}</text><text> 元/度</text>
							</view>
						</view>
					</view>
					<view class="cell" v-if="discountInfo&&personal == 1">
						<view class="lable">优惠</view>
						<view class="contet app-flex middle">
							<view>{{discountInfo.temp3}}<text class="money">{{discountInfo.discount?parseFloat(discountInfo.discount).toFixed(4):"0.0000"}}</text><text> 元/度</text></view>
						</view>
					</view>
					<view class="cell"><view class="lable">当前时段</view><view class="contet">{{getPriceLable(nowPriceTime.timeType)}}  {{nowPriceTime.time}}</view></view>
					<!-- <view class="cell" style="height: auto;"><view class="lable">停车参考</view><view class="contet" style="flex: 1;padding-left: 5px;" v-html="stationInfo.parkTips"></view></view> -->
					<view class="cell"><view class="lable">停车参考</view><view class="contet">充电减免2小时停车费，超出时长部分计时收费</view></view>
				</view>
			</view>
			<view v-if="!visit" class="block">
				<view class="card">
					<view class="title">
						<text>我的抵扣券</text>
						<view class="more" v-if="isEc"><view  class="switch" :class="{'personal':personal==1}"><text @click="changeAccount(1)">个人</text><text  @click="changeAccount(2)">集团</text></view></view>
					</view>
					<view class="coupon" :class="{'personal':personal==1}">
						<view class="name">{{personal == 1?'充电抵扣券':'集团抵扣券'}}</view>
						<view class="feature"><view class="line"></view></view>
						<view class="info">
							<view class="value">{{accountInfo.balance}}</view>
							<view class="describe">剩余可抵扣充电费用 (元)</view>
						</view>
					</view>
					<view class="tips">
						<view class="li">1. 可抵扣按照当前电价进行预估计算</view>
						<view class="li">2. 实际结算价以具体充电时段为准</view>
					</view>
				</view>
			</view>
			<!-- 信息 -->
			<view class="footer">
				<view class="tips">账单信息可能会有所延迟，具体以实际结算为准</view>
				<view>
					<button @click="startup()" class="startup">启动终端充电</button>
					<ax-ios-indicator min="10"></ax-ios-indicator>
				</view>
			</view>
		</view>
	</ax-body>
</template>

<script>
export default {
	onLoad(opts) {
		console.log("参数信息：",opts)
	   /**
		* 判断终端是否占用状态
		* 判断占用终端设备的是不是用户自己
		*/
		this.deviceId = opts.deviceId
		this.deviceStatus = opts.deviceStatus
	   
	   
	},
	onShow() {
		
		this.queryInChange(this.deviceId,this.deviceStatus);
		
		/**
		 * 刷新用户信息
		 */
		this.userInfo = this.$app.storage.get(this.$config.keyname.userInfo);
		if(!this.userInfo.phone){
			this.$app.url.goto('/pages/login/login')
			return;
		}
		this.$api.login({"checkStatus":1}).then(()=>{
			this.userInfo = this.$app.storage.get(this.$config.keyname.userInfo);
			if(this.userInfo.ecId){
				//查询该集团账户是否正常使用。
				this.$api.base("post","/chargeApi/queryEcInfo",{"ecId":this.userInfo.ecId},{}).then(res=>{
					if(res.ecInfo && res.ecInfo.ecStatus == 1){
						this.isEc = true;
					}
				})
			}
		})
		
		
		
	},
	mounted(){
		
		
	},
	data() {
		return {
			deviceId:0,
			deviceStatus:0,
			visit: '',
			personal: 1,// 1 个人订单 2 集团订单
			isEc : false,//是否集团的用户
			nowPriceTime : {},//当前价格时间段信息
			deviceInfo : {},//充电桩的信息
			accountInfo : {//账户信息
				balance : 0,//可用抵用券余额
			},
			userInfo : {},
			stationInfo : {},//站点信息
			orderInfo : {},//临时订单信息
			checkNum : 0,//检测订单状态次数
			ecInfo : {},//集团信息
			discountInfo:null//优惠信息
		}
	},
	methods: {
		//通过用户id查询是否还有在充电中的订单
		queryInChange(deviceId,deviceStatus){
			if(deviceStatus == 3 || deviceStatus == 4 ){
				//占用充电状态；终端占用且不是自己,进入访问模式
				this.visit = true;
			}
			this.getDeviceInfo(deviceId);//获取设备、站的详情信息
			this.getAccountInfo();//获取账户信息
			/* this.$api.base("post","/chargeApi/queryInChangeByUserId",{},{}).then(res=>{
				if(res.isChange == 1){
					this.orderInfo = res.orderInfo;
					//用户有充电中的订单
					//if(res.orderInfo.deviceId == deviceId){
						// 跳转
						this.$app.url.goto('/pages/charging/charging?orderId='+this.orderInfo.id+"&deviceId="+deviceId,false);
					//}
				}else{
					
				}
				
				
			}) */
		},
		//获取设备的详情信息
		getDeviceInfo(deviceId){
			this.$api.base("post","/chargeApi/getDevicesDetial",{"deviceId":deviceId},{}).then(res=>{
				this.deviceInfo = res.device;
				this.nowPriceTime = res.nowPriceTime;
				this.stationInfo = res.stationInfo;
				if(res.discountInfo){
					this.discountInfo = res.discountInfo
				}
				if(this.deviceInfo.tipsStatus==1){
					this.$app.popup.alert(this.deviceInfo.tipsContent,"温馨提示");
				}
			})
		},
		//获取账户信息
		getAccountInfo(){
			if(this.personal == 1){
				//获取个人账户信息
				this.$api.base("post","/chargeApi/getUserAccount",{},{}).then(res=>{
					this.accountInfo.balance = res.userAccount.balance;
					
				})
			}else{
				//获取集团账户信息
				this.$api.base("post","/chargeApi/getEcUserAccount",{},{error:false}).then(res=>{
					this.ecInfo = res.ecInfo;
					this.accountInfo.balance = res.ecUserAccount.balance;
				}).catch(err=>{
					this.accountInfo.balance = 0;
					this.$app.popup.alert(err.msg,"温馨提示");
				})
			}
		},
		//切换账户
		changeAccount(type){
			if(this.personal == type){
				return;
			}
			this.personal = type;
			 this.getAccountInfo();
		},
		//当前集团折扣价
		getCurrEcPrice(){
			
			if(!this.nowPriceTime){
				return 0;
			}
			var currEcP = this.nowPriceTime.price;
			if(this.ecInfo && this.ecInfo.ecDiscount){
				
				var realServicePrice = this.nowPriceTime.servicePrice
				if(this.stationInfo.contractServicePrice){
					realServicePrice = this.stationInfo.contractServicePrice
				}
				
				currEcP = (this.nowPriceTime.electrovalence + realServicePrice + this.nowPriceTime.addServicePrice * this.ecInfo.ecDiscount/100);
			}
			console.log("dddd",currEcP)
			if(currEcP){
				currEcP = currEcP.toFixed(2);
			}
			return Number(currEcP).toFixed(4);
		},
		//转换出电压值
		getVolt(){
			if(!this.deviceInfo.power){
				return 0;
			}
			var v = this.deviceInfo.power/this.deviceInfo.current * 1000;
			return v;
		},
		//映射 峰  平  谷
		getPriceLable(type){
			//时间类型 1 谷 2 平 3 峰
			var str = "";
			switch (type){
				case 1:
					str = "谷";
					break;
				case 2:
					str = "平";
					break;
				case 3:
					str = "峰";
					break;
			}
			return str;
		},
		//映射订单状态名称（）
		getDeviceStatusLable(status){
			//设备状态 0：离网1：空闲2：占用（未充电）3：占用（充电中）4：占用（预约锁定）255：故障
			var str = "";
			switch (status){
				case 0:
					str = "离网";
					break;
				case 1:
					str = "空闲";
					break;
				case 2:
					str = "占用";
					break;
				case 3:
					str = "占用";
					break;
				case 4:
					str = "占用";
					break;
				case 255:
					str = "故障";
					break;
			}
			return str;
		},
		startup(){
			
			if(this.visit){
				this.$app.popup.alert("该充电枪被占用或存在异常，请重新尝试或更换其他充电枪。","温馨提示");
				return;
			}
			
			//判断账户余额是否大于两元
			if((this.accountInfo.balance - 2) <= 0){
				
				return this.$app.popup.confirm("无法启动充电，抵扣余量需大于2元，请先购买充电券！","温馨提示！",{confirmText:"立即购券"}).then(confirm=>{
					if(confirm){
						this.$app.url.goto('/pages/coupon-buy/coupon-buy',true);
					}
				});
			}
			//统一下单并启动接口
			this.startChangeAndOrder();
		},
		//统一下单并启动接口
		startChangeAndOrder(){
			var obj = {
				userId : this.userInfo.id,
				deviceId : this.deviceInfo.id,
				orderType : this.personal == 2 ? 2 : 1,//订单类型 1 个人订单 2 集团订单
			}
			this.$api.base("post","/chargeApi/startChangeAndOrder",obj,{}).then(res=>{
				//下单成功，并进行了订单预充值
				this.orderInfo = res.orderInfo;
				if(res.flg && res.flg == 1){
					//用户有充电中的订单
					 this.$app.popup.confirm("您有一个进行中充电订单，不可再次启动。",null,{showCancel:false,confirmText:"查看订单"}).then(cres=>{
						this.$app.url.goto('/pages/charging/charging?orderId='+this.orderInfo.id+"&deviceId="+this.deviceInfo.id,false);
					 });
				}else{
					//正常启动充电订单
					this.$app.url.goto('/pages/charging/charging?orderId='+this.orderInfo.id+"&deviceId="+this.deviceInfo.id,false);
				}
				//this.$app.popup.loading(true,{title:"启动中...."})
				//延迟5s查询一下订单，看看是否真的启动成功
				//setTimeout(()=>this.checkedStartStatus(),5000);
			})	
		},
		/* // 通过充电桩编号（sn）检测该设备是否插枪，是否可以进行后续的下单，启动操作
		checkDeviceReady(){
			this.$api.base("post","/chargeApi/checkDeviceReady",{"sn":this.deviceInfo.deviceNo},{}).then(res=>{
				if(res.code == 0){
					//充电桩已经插枪准备好了，可以进行下单充值操作
					this.chargeAndOrder();
				}
			})
		},
		// 进行下单，并进行接口充值，准备启动充电
		chargeAndOrder(){
			var obj = {
				userId : this.userInfo.id,
				deviceId : this.deviceInfo.id,
				orderType : this.personal == 2 ? 2 : 1,//订单类型 1 个人订单 2 集团订单
			}
			this.$api.base("post","/chargeApi/chargeAndOrder",obj,{}).then(res=>{
				if(res.code == 0){
					//下单成功，并进行了订单预充值
					this.orderInfo = res.orderInfo;
					//通知已经充值成功，可以进行设备充电的启动
					this.changePayAndStart();
				}
			})
		},
		// 支付成功启动充电通知
		changePayAndStart(){
			this.$api.base("post","/chargeApi/changePayAndStart",{"id":this.orderInfo.id},{}).then(res=>{
				if(res.code == 0){
					this.$app.popup.loading(ture,{title:"启动中...."})
					//延迟5s查询一下订单，看看是否真的启动成功
					setTimeout(()=>this.checkedStartStatus(),5000);
				}
			})
		}, */
		// 延迟5s查询一下订单，看看是否真的启动成功
		checkedStartStatus(){
			this.$api.base("post","/chargeApi/checkedStartStatus",{"id":this.orderInfo.id},{}).then(res=>{
				
				if(res.code == 0){
					var respObj = res.obj;
					if(respObj.code == 200){
						if(respObj.status == 1){
							uni.hideLoading();
							//状态为1说明正常启动
							this.$app.url.goto('/pages/charging/charging?orderId='+this.orderInfo.id+"&deviceId="+this.deviceInfo.id,false);
						}else{
							//其他状态，说明充电桩，未启动。或其他问题，需要再次进行进行验证
							if(this.checkNum < 20){
								this.checkNum = this.checkNum + 1;
								//延迟2s查询一下订单，看看是否真的启动成功
								setTimeout(()=>this.checkedStartStatus(),2000);
							}
						}
						
					}else{
						uni.hideLoading();
						this.$app.popup.alert(respObj.msg,"温馨提示");
					}
					
				}else{
					uni.hideLoading();
				}
			})
		},
	}
}
</script>

<style scoped>
@import url("terminal.css");
</style>
