<template>
	<view class="container">
		<u-navbar title="停车场主页"  :background="{backgroundColor: '#ffffff'}" class="top-navbar" title-size="30">
		</u-navbar>
		<view class="parking-panel">
			<view class="panel-left">
				<view class="panel-row">
					<text class="item-title" style="font-size: 32rpx;color:#000;">{{parkingSite.parking_name}}</text>
					<u-icon name="edit-pen" size="32" color="#4a4a4a" style="margin-left:100rpx;padding:10rpx;" @tap="editParking"></u-icon>
				</view>
				
				
				<view class="panel-row">
					<text class="item-title">区域</text>
					<text class="item-title">车位余数 / 总数</text>
				</view>
				<view class="panel-row" v-for="(site,index) in parkingSite.sites" :key="index">
					<text class="item-title">{{site.areaName}}</text>
					<text class="num-txt">{{site.surplusParkingNumber}} / {{site.totalParkingNumber}}</text>
				</view>
			</view>
			<image :src="parkingSite.pic_url" style="width:200rpx;height:160rpx;border-radius: 10rpx;"></image>
		</view>
		<view class="parking-adr">
			<view style="padding-left:30rpx;line-height:60rpx;height: 60rpx;position: absolute;z-index: 2;width:100%;background-color: rgba(255,255,255,0.9);">{{parkingSite.address_}}</view>
			<image src="../../static/img/addrbg.png" style="height: 60rpx;width:100%;position: relative;z-index: 1;"></image>
		</view>
		
		<view class="li-title">收费规则</view>
		<view class="li-con">
			<text space="emsp">  {{chargeRule.rule_txt}}</text>
			<!-- <view style="margin-top:15rpx;"><text space="emsp">  {{chargeRule.oth_rule_txt}}</text></view> -->
		</view>
		
		<view class="li-title" style="display: flex;justify-content: space-between;">
			<text>设备列表</text>
			<u-icon name="reload" size="32" color="#55aaff" @click="loadPageData(crtparkId)"></u-icon>
		</view>
		<view class="li-con" v-for="(item,index) in devs">
			<view class="dev-tit">
				<text>{{item.gateName}}</text>
				<u-button type="primary" :custom-style="{height:'60rpx',margin:'0rpx 30rpx'}" :plain="true" @tap="manualPass(item.onlineDevId,item.gateName)">手动放行</u-button>
				<!-- <view class="dev-view"><text>查看</text><u-icon name="arrow-right"></u-icon></view> -->
			</view>
			<view class="dev-stat">
				<view><text style="margin-right:10rpx;">闸口状态：{{item.gateStatus?'在线':'离线'}}  </text>
				<u-icon :name="item.channel_status=='1'?'checkmark-circle-fill':'error-circle-fill'" size="30" :color="item.gateStatus?'#15b53a':'#888888'"></u-icon>
				<!-- <text style="margin:0rpx 10rpx 0rpx 40rpx;">摄像头状态：正常  </text><u-icon name="checkmark-circle-fill" size="30" color="#15b53a"></u-icon> -->
				</view>
			</view>
		</view>
		
		<!-- <u-button type="primary" style="margin:50rpx 50rpx;" @tap="manualPass">出口抬杆放行</u-button> -->
		
		<u-modal v-model="showModal" :title="modalTitle" :show-cancel-button="true" @confirm="exePass">
			<view class="slot-content">
					<u-field  v-model="passNote" label="" placeholder="请填写放行说明" type="textarea" label-width="0" :auto-height="false" :field-style="{height:'140rpx'}"/>
			</view>
		</u-modal>
		
		<u-modal v-model="showEditModal" ref="editModal" title="车位数编辑" :show-cancel-button="true" :async-close="true" @confirm="submitSeat">
			<view class="eidt-content">
				<view class="edit-row" style="font-weight: bold;">
					<text class="item-title">区域</text>
					<text class="item-title" style="margin-right:30rpx;">车位余数 / 总数</text>
				</view>
				<view class="edit-row" v-for="(site,index) in editSites" :key="index">
					<text class="item-title">{{site.areaName}}</text>
					<view style="display: flex;justify-content: flex-end;">
						<u-field type="number" v-model="site.surplusParkingNumber" label="" :label-width="0" :field-style="{'border-bottom':'1px solid #55aaff','width':'60rpx'}" :clearable="false"/>
						<u-field type="number" v-model="site.totalParkingNumber" label="" :label-width="0" :field-style="{'border-bottom':'1px solid #55aaff','width':'60rpx'}" :clearable="false"/>
					</view>
				</view>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import * as api from '@/apis/myparkings.js'
	
	
	export default {
		data() {
			return {
				crtparkId:null,
				showModal:false,
				modalTitle:'放行说明',
				passNote:'',
				opening:false,
				openingChannel:'',
				parkingSite:{},
				editSites:null,
				chargeRule:{},
				othChargeRule:[],
				devs:[],
				showEditModal:false,
				seatModel:{
					total:null,
					idle:null
				}
			}
		},
		onLoad(opt){
			this.loadPageData(opt.park_id);
			this.crtparkId=opt.park_id
		},
		methods: {
			editParking(){
				this.showEditModal=true;
			},
			closeEditModal(isClose){
				if(isClose){
					this.showEditModal=false;
				}
				else{
					this.$refs.editModal.clearLoading();
				}
			},
			synSites(){ //编辑车位提交成功后同步模型数据
				this.parkingSite['sites']=JSON.parse(JSON.stringify(this.editSites))
			},
			submitSeat(){
				//this.crtparkId
				//let arySeat=[{parkId:'11',area:'0',totalParkingNumber:0,surplusParkingNumber:2}]
				let arySeat=this.editSites.map(area=>{
					area['parkId']=this.crtparkId
					return area
				})
				if(this.crtparkId=='1'){ //荆鹏停车场
					api.updateParkingAreaSeat(arySeat).then(resp=>{
						if(!resp.success){
							uni.showToast({
								title:resp.msg||'保存数据失败',
								icon:'none'
							})
							this.closeEditModal()
							return;
						}
						uni.showToast({
							title:'操作成功',
							icon:'success'
						})
						this.synSites()
						this.closeEditModal(true)
						
					}).catch(err=>{
						this.closeEditModal()
						uni.showToast({
							title:'保存数据出错',
							icon:'none'
						})
					})
				}
				
				else{
					api.updateParkingSeat(arySeat[0].parkId,arySeat[0].totalParkingNumber,arySeat[0].surplusParkingNumber).then(resp=>{
							if(!resp.success){
								uni.showToast({
									title:resp.msg||'保存数据失败',
									icon:'none'
								})
								this.closeEditModal()
								return;
							}
							uni.showToast({
								title:'操作成功',
								icon:'success'
							})
							this.synSites()
							this.closeEditModal(true)
						}).catch(err=>{
							this.closeEditModal()
							uni.showToast({
								title:'保存数据出错',
								icon:'none'
							})
						
					})
				}
				
				
				
			},
			manualPass(channelId,gateName){
				if(this.opening){
					uni.showToast({
						title:'开门中，勿重复操作',
						icon:'none'
					})
					return;
				}
				this.modalTitle=gateName+"放行";
				this.showModal=true;
				this.openingChannel=channelId;
			},
			exePass(){
				
				if(!this.openingChannel){
					uni.showToast({
						title:'未选择要开启设备',
						icon:'none'
					})
					
					return;
				}
				uni.showLoading({
					title:'开门中...'
				});
				api.manualPass(this.openingChannel,this.passNote).then(resp => {
					this.opening=false;
					uni.hideLoading();
					if(!resp.success){
						uni.showToast({
							title:resp.msg||'开门失败',
							icon:'none'
						})
					}
					else{
						uni.showToast({
							title:'手动开门已执行',
							icon:'none'
						})
						
					}
				}).catch(error => {
					this.opening=false;
					uni.hideLoading();
					
				});
				
				this.opening=true;
			},
			loadPageData(id){
				uni.showLoading({
					title:'加载中...'
				});
				api.loadParkingCompose(id).then(resp => {
					//console.log(resp);
					uni.hideLoading();
					if(!resp.success){
						uni.showToast({
							title:resp.msg||'加载数据失败',
							icon:'none'
						})
						
						return;
					}
					
					this.processParkInfo(resp.data.areas, resp.data.parkInfo,id)
					
					this.processRuleDatas(resp.data.chargeRule,resp.data.othchargeRule)
					
					this.devs=this.processDevDatas(resp.data.devs,id);  //resp.data.devs
					//console.log(this.devs)
					
				}).catch(error => {
					uni.hideLoading();
				});
			},
			
			processParkInfo(areas,parkInfo,parkId){
				if(!parkInfo.pic_url){
					parkInfo.pic_url="../../static/img/header_bg.png"
				}
				
				let siteAry=null
				if(parkId=='1'){ //荆鹏停车场
					siteAry=areas.map(item=>{
						let {areaName,area,totalParkingNumber,surplusParkingNumber}=item
						return {areaName,area,totalParkingNumber,surplusParkingNumber}
					})
				}
				else{
					siteAry=[{areaName:'全域停车场',totalParkingNumber:parkInfo.total_parking_number,surplusParkingNumber:parkInfo.surplus_parking_number}]
				}
				parkInfo['sites']=siteAry
				this.parkingSite=parkInfo
				this.editSites=JSON.parse(JSON.stringify(siteAry))
				//console.log(this.parkingSite)
			},
			
			processRuleDatas(chargeRule,othchargeRule){
				if(!othchargeRule){
					othchargeRule=[]
				}
				let othRuleTxt={ryc:[],xny:[]};
				othchargeRule.forEach((item) => {
					if(item.car_type=='1'){ //燃油车
						othRuleTxt.ryc.push(`${item.min_section}-${item.max_section}分钟：${item.parking_cost}元`);
					}
					else if(item.car_type=='2'){  //新能源车
						othRuleTxt.xny.push(`${item.min_section}-${item.max_section}分钟：${item.parking_cost}元`);
					}
				})
				this.chargeRule=chargeRule||{}
				this.chargeRule['rule_txt']=`燃油车\n 免费时长：${this.chargeRule.free_duration}分钟，每小时费用：${this.chargeRule.hour_cost}元，${othRuleTxt.ryc.join('，')} \n新能源车\n 免费时长：${this.chargeRule.new_energy_free_duration}分钟，每小时费用：${this.chargeRule.new_energy_hour_cost}元，${othRuleTxt.xny.join('，')} \n每日封顶费用：${this.chargeRule.day_capping_cost}元`;
			},
			
			//设备（通道设备-摄像头），分级显示（停车场-区域-出口、入口），根据所属道闸合并显示
			/*
			{
				area:{
					'areaName':xxx,
					 'gate':{
						channelFlag:{
							'gateName':xxx,
							'gateStatus':xxx ,   //[true:online ,false:offline]
							'onlineDevId':'',
							'channels':[]
						}
					}
				}
			}*/
			processDevDatas(devs,parkId){
				if(!devs){
					return []
				}
				//console.log(devs)
				if(parkId!='1'){ //非荆鹏停车场
					devs.forEach(dev=>{
						dev['gateName']=dev['channel_name']
						dev['gateStatus']=dev['channel_status']=='1'
						dev['onlineDevId']=dev['id']
					}) 
					
					return devs
				}
				
				//荆鹏停车场(按道闸合并处理)
				
				let glbDev={},areaKey=null,gateNameStr=null
				devs.forEach(dev=>{                  //dev.area=['0','1','2',null]  大楼院内(0)、公寓（1）、大楼前门(2)、全部区域(null)
					if(!dev.channel_flag){
						dev.channel_flag='1'
					}
					areaKey=dev.area || 'all'
					if(!glbDev[areaKey]){            //按区域分组
						glbDev[areaKey]={'areaName':dev.area_name||'','gate':{}}   //gate 道闸下的通道设备
					}
					if(!glbDev[areaKey]['gate'][dev.channel_flag]){  //按所属道闸合并显示,道闸名=区域名+道闸序号+'入口/出口'
						gateNameStr=`${glbDev[areaKey]['areaName']}道闸${dev.channel_flag||'1'}`
						//gateNameStr=gateNameStr.replace('全部区域','')
						glbDev[areaKey]['gate'][dev.channel_flag]={'gateName':gateNameStr,'gateStatus':false,'onlineDevId':null, 'channels':[]}
					}
					glbDev[areaKey]['gate'][dev.channel_flag]['channels'].push(dev)
					if(dev.channel_status=="1"){
						glbDev[areaKey]['gate'][dev.channel_flag]['gateStatus']=true
						glbDev[areaKey]['gate'][dev.channel_flag]['onlineDevId']=dev.id
					}
					
				})
				console.log(glbDev)
				let gateAry=[]
				for(let are in glbDev){
					for(let gateIdx in glbDev[are]['gate']){
						gateAry.push(glbDev[are]['gate'][gateIdx])
					}
				}
				
				return gateAry
				
			}
			
			
		}
	}
</script>

<style>
	page{
			
			background-color: #f4f4f4;
			font-family: '华文行楷';
		}
	.parking-panel{
		background-color: #ffffff;
		border-radius: 10rpx;
		padding:20rpx;
		display: flex;
		flex-flow: row nowrap;
		justify-content: space-between;
		align-items: center;
		
	}
	.parking-panel .panel-left{
		display: flex;
		flex-flow: column nowrap;
		justify-content: space-between;
		align-items: flex-start;
		font-family: '华文行楷';
		width:480rpx;
		
	}
	
	.parking-panel .panel-left .panel-row,.edit-row{
		display: flex;
		flex-flow: row nowrap;
		justify-content: space-between;
		align-items: center;
		width:100%;
		padding:10rpx 0rpx;
		box-sizing: border-box;
		font-size:28rpx;
	}
	
	.parking-panel .panel-left .panel-row .num-txt{
		font-size: 28rpx;
		font-weight: bold;
		margin:0rpx 10rpx;
	}
	
	.parking-panel .panel-left .panel-row .item-title{
		font-size:24rpx;
		font-weight: bold;
		color:#5d5454;
	}
	
	
	.parking-panel .panel-left .left-title{
		font-weight: bold;
		font-size:32rpx;
		
		color:#000000;
	}
	
	.newpower-txt{
		color:#27bf3e;
		margin:0rpx 10rpx;
	}
	
	.parking-adr{
		background-color: #ffffff;
		/* padding:15rpx 20rpx; */
		font-size: 28rpx;
		height: 60rpx;
	}
	
	.li-title{
		margin:30rpx 20rpx 15rpx;
		border-left:6rpx solid #1b68e3;
		padding:0rpx 20rpx;
	}
	
	.li-con{
		background-color: #ffffff;
		padding:15rpx;
		font-size: 26rpx;
		color:#4a4a4a;
		margin-bottom: 5rpx;
	}
	.dev-tit{
		display: flex;
		flex-flow: row nowrap;
		justify-content: space-between;
		align-items: center;
	}
	.dev-tit>text{
		font-size:32rpx;
		font-weight: bold;
	}
	
	.dev-tit .dev-view>text{
		font-size: 24rpx;
		color:#1B68E3;
		margin-right:10rpx;
	}
	
	.dev-stat{
		font-size:24rpx;
		color:#646464;
		margin:20rpx 0rpx 0rpx;
	}
	
	/deep/.u-textarea-inner{
		background-color: #ececec;
		
	}
	
	.eidt-content{
		padding:10rpx 20rpx;
		box-sizing: border-box;
	}
	
	.edit-row /deep/.u-field{
		width:160rpx !important;
	}
</style>
