<template>
	<ax-body :blank="0">
		<view class="site-body">
			<view class="top-banner" v-if="stationDetail.pictures">
				<swiper class="banner-swiper" circular :autoplay="true" interval="3000" duration="500"
					@change="swiperChange">
					<swiper-item class="banner-swiper-item" v-for="item in stationDetail.pictures">
						<image class="swiper-item-image" :src="item" mode=""></image>
					</swiper-item>
				</swiper>
				<view class="swiper-current">{{ bannerIndex }}/{{ stationDetail.pictures.length }}</view>
			</view>
			<view class="site-content" :style="{ top: `${stationDetail.pictures ? '320rpx' : '0'}` }">
				<view class="top-site-info">
					<view class="site-title">{{ stationDetail.stationName }}</view>
					<view class="site-text">
						<image src="@/static/img/site-icon03.png" class="icon"></image>
						<view class="item-text">{{ stationDetail.tips }}</view>
					</view>
				</view>
				<view class="site-location">
					<view class="location-left">
						<view class="left-km">距离您{{ stationDetail.distance }}km</view>
						<view class="left-address">{{ stationDetail.address }}</view>
					</view>
					<view class="location-rihgt" @click="openLocation()">
						<image src="@/static/img/locate2.svg" class="right-icon"></image>
						<view class="right-nav">导航</view>
					</view>
				</view>
				<view class="site-cost-info">
					<view class="cost-info-title">
						<view class="title-name">费用信息</view>
						<view class="check-info" @click="toPriceAll()">
							<text>查看全部</text>
							<text class="ax ax-iconline i-arrow-right icon"></text>
						</view>
					</view>
					<view class="cost-price-info" v-if="!stationDetail.firmUser">
						<view class="cost-title">
							<view class="title-left">当前价</view>
							<view class="title-right">惊喜价</view>
						</view>
						<view class="cost-price">
							<text style="color: #FF6464;font-size: 48rpx;font-weight: 800;">{{
								stationDetail.currentPrice
							}}</text>
							<text class="cost-price-unit">元/度</text>
						</view>
						<view class="time-cost-price">当前时段：</view>
						<view class="time-cost-number">{{ stationDetail.currentPeriod }}</view>
					</view>
					<view class="firm-price-info-box" v-else>
						<view class="current-price-info">
							<view class="current-price-title">当前价</view>
							<view class="current-price">
								<view class="current-price-text"><text class="operation-symbol">￥</text>
									<text>{{ stationDetail.currentPrice }}</text>
								</view>
								<view class="current-price-unit">元/度</view>
							</view>
							<view class="time-current-price">当前时段：</view>
							<view class="time-current-number">{{ stationDetail.currentPeriod }}</view>
						</view>
						<view class="firm-price-info">
							<view class="firm-price-title">
								<view class="title-text">企业专享价</view>
								<view class="tags-price">特惠价</view>
							</view>
							<view class="firm-price-box">
								<view class="firm-price-text">
									{{ stationDetail.enterprisePrice || '--' }}
								</view>
								<view class="firm-price-unit">元/度</view>
							</view>
							<view class="current-pay-price-box">
								<view class="pay-price">
									<view class="firm-old-price">{{ stationDetail.currentPrice }}元/度
									</view>
									<!-- <view class="discount-price">本单预计省9元</view> -->
								</view>
								<image class="pay-price-icon" src="/static/img/firm-price.png" mode=""></image>
							</view>
						</view>
					</view>
					<view class="stopcar-tips">
						<image class="stopcar-tips-icon" src="@/static/img/site-icon03.png"></image>
						<view class="stopcar-tips-text">
							<view class="tips-text-title">停车参考</view>
							<view class="tips-text-mini">充电减免2小时停车费</view>
						</view>
					</view>
				</view>
				<view class="site-list-card">
					<view class="cost-info-title">
						<view class="title-name">充电终端</view>
						<view class="check-info" @click="toDeiceAll()">
							<text>查看全部</text>
							<text class="ax ax-iconline i-arrow-right icon"></text>
						</view>
					</view>
					<view class="app-flex site-select-tab">
						<view class="select-item" v-for="(item, index) in siteSortList" @click="selectItem(item, index)"
							:class="{ selectItemActive: siteSelectIndex == index }">
							{{ item.text }}({{ item.total }})
						</view>
					</view>
					<view class="site-list-box">
						<view v-for="(item, index) in filteredConnectorList" :key="index" @click="goTerminal(item)"
							class="terminal-item">
							<view class="state" :class="[getSatesObj(item).color]">
								<view class="cake">
									<image src="@/static/img/site-icon01.svg" class="icon"></image>
									<view class="name">{{ formatStatusName(item.statusName) }}</view>
								</view>
							</view>
							<view class="info">
								<view class="name">{{ item.connectorName }}</view>
								<view class="subinfo">电类分类：{{ item.equipmentType }}</view>
								<view class="subinfo">终端编号：{{ item.connectorCode }}</view>
							</view>
						</view>
						<view v-if="filteredConnectorList.length === 0" class="not-data">暂无设备</view>
					</view>
				</view>
				<view class="site-list-card">
					<view class="cost-info-title">
						<view class="title-name">电站信息</view>
						<view class="check-info">
							<text>查看全部</text>
							<text class="ax ax-iconline i-arrow-right icon"></text>
						</view>
					</view>
					<view class="site-detail-line"></view>
					<view class="site-detail-info">
						<view class="detail-info-item">
							<view class="left-item">营业时间</view>
							<view class="right-item">{{ stationDetail.businessHours || '--' }}</view>
						</view>
						<view class="detail-info-item">
							<view class="left-item">服务提供</view>
							<view class="right-item">{{ stationDetail.serviceProvider }}</view>
						</view>
						<view class="detail-info-item">
							<view class="left-item">发票提供</view>
							<view class="right-item">{{ stationDetail.serviceProvider }}</view>
						</view>
						<view class="detail-info-item">
							<view class="left-item">客服热线</view>
							<view class="right-item">{{ stationDetail.customerServiceHotline }}</view>
						</view>
					</view>
				</view>
				<view style="height: 200rpx;"></view>
			</view>
			<!-- 扫码充电 -->
			<view class="footer">
				<view class="bg5">
					<view class="text">
						<view>中数电动</view>
						<view>特惠价</view>
					</view>
					<image src="@/static/img/site-bg05.svg" class="bg" mode="heightFix"></image>
				</view>
				<view class="price-wrap">
					<view class="price">
						<text class="symbol">￥</text>
						<!-- v-if="nowPriceTime.firmPrice===null" -->
						<text v-if="!stationDetail.firmUser">{{ stationDetail.currentPrice }}</text>
						<text v-else>{{ stationDetail.enterprisePrice || '--' }}</text>
					</view>
					<view class="unit">元/度</view>
				</view>
				<view @click="sacn()" class="scan">扫码充电</view>
			</view>
		</view>
	</ax-body>
</template>

<script>
export default {
	onLoad: function (option) {
		console.log(option); //打印出上个页面传递的参数。
		this.stationInfo = JSON.parse(option.item);
		this.getStationsInfo();
		this.getConfigStationInfo();
	},
	mounted() {
		this.$app.act.selectorQuery(this, '#footer').then(res => {
			const win = uni.getWindowInfo();
			const tHight = win.windowWidth * 9 / 16;
			this.mainHeight = win.windowHeight - tHight - res.height + 10;
		});

	},
	data() {
		return {
			user_info: this.$app.storage.get('USER_INFO'),
			mainHeight: 0,
			tops: ["../../static/img/$temp-site.png"],
			another: false,
			terminals: [],
			entInfo: {
				title: '服务提供',
				name: '华能贵州盘州市风电有限责任公司',
				code: '915205555155625655',
				tel: '0851-8815158',
				businessLicenceUrl: "/static/img/$temp-site01.jpg"
			},
			stationInfo: "",//站点信息
			deviceList: [],//该站点桩列表
			timePricesList: [],//费用时段列表
			nowPriceTime: {},//当前费用时段信息
			service: {
				tel: '400-0000-0000',
				work: '09:00 至 18:00'
			},
			busineHours: "",//营业时间
			bannerIndex: 1,//轮播下标
			stationDetail: {},
			siteSelectIndex: 0,
			siteSortList: [{
				total: 0,
				text: '空闲',
				status: 1
			}, {
				total: 0,
				text: '占用',
				status: 2
			}, {
				total: 0,
				text: '离线',
				status: 0
			}],
			filteredConnectorList: [],
		}
	},
	methods: {
		swiperChange(e) {
			this.bannerIndex = e.detail.current + 1
		},

		getStationsInfo() {
			let location = this.$app.storage.get('USER_LOCATION')
			this.$api.base("get", "/applet/v1/station/detail", {
				stationId: parseInt(this.stationInfo.stationId),
				longitude: location.split(",")[0] || 0,
				latitude: location.split(",")[1] || 0
			}, {}).then(res => {
				res.data.pictures = JSON.parse(res.data.pictures)
				const countMapping = {
					'空闲': res.data.idleCount,
					'占用': res.data.occupiedCount,
					'离线': res.data.offlineCount
				};
				this.siteSortList.forEach(item => {
					item.total = countMapping[item.text] || 0;
				});
				this.stationDetail = res.data
				// 初始化默认显示空闲状态的前3个设备
				this.siteSelectIndex = 0;
				this.filteredConnectorList = this.stationDetail.connectorList
					.filter(connector => connector.status == 1) // 空闲状态
					.slice(0, 3);
			})
		},

		selectItem(e, i) {
			this.siteSelectIndex = i;
			// 根据选择的状态过滤 connectorList - 先过滤再取前3条
			if (e.status === 1) { // 空闲
				this.filteredConnectorList = this.stationDetail.connectorList
					.filter(connector => connector.status == 1)
					.slice(0, 3);
				console.log("空闲过滤后的connectorList:", this.filteredConnectorList);
			} else if (e.status === 2) { // 占用
				this.filteredConnectorList = this.stationDetail.connectorList
					.filter(connector => connector.status == 2)
					.slice(0, 3);
				console.log("占用过滤后的connectorList:", this.filteredConnectorList);
			} else if (e.status === 0) { // 离线
				this.filteredConnectorList = this.stationDetail.connectorList
					.filter(connector => connector.status == 0)
					.slice(0, 3);
				console.log("离线过滤后的connectorList:", this.filteredConnectorList);
			}
		},

		getSatesObj(item) {
			//{name:'离线',color:'grey'},{name:'空闲',color:'green'},{name:'占用',color:'blue'}
			var obj = {};
			if (item.status == 2) {
				obj = { color: 'blue' };
			} else if (item.status == 0) {
				obj = { color: 'grey' };
			} else if (item.status == 1) {
				obj = { color: 'green' };
			}
			return obj;
		},
		formatStatusName(statusName) {
			// 去掉括号及括号内的内容
			return statusName.replace(/\([^)]*\)/g, '');
		},
		//获取配置文件信息
		getConfigStationInfo() {
			this.$api.static(this.$config.url.configUrl + "stationConfi.json").then(res => {
				console.log("获取的配置文件信息:", res.busineHours);
				this.entInfo = res.entInfo;
				this.service = res.service;
				this.busineHours = res;
			})
		},
		// 拨打电话
		callPhone(phone) {
			this.$app.act.callPhone(phone);
		},
		// 打开客服
		openCustomerService() {
			this.$refs.service.open();
		},
		// 打开服务提供
		openEnt_Serve() {
			this.entInfo.title = '服务提供';
			this.$refs.entInfo.open();
		},
		// 打开发票提供
		openEnt_Invoicing() {
			this.entInfo.title = '发票提供';
			this.$refs.entInfo.open();
		},
		// 关闭企业弹窗
		closeEnt() {
			this.$refs.entInfo.close();
		},
		// 关闭服务弹窗
		closeService() {
			this.$refs.service.close();
		},
		// 打开地图
		openLocation() {
			uni.openLocation({
				latitude: Number(this.stationInfo.lat),
				longitude: Number(this.stationInfo.lng),
			});
		},
		// 跳转充电终端
		goTerminal(item) {
			//设备状态 0：离网1：空闲2：占用（未充电）3：占用（充电中）4：占用（预约锁定）255：故障
			if (item.status == 0 || item.status == 255) {
				return;
			}
			this.$app.url.goto('/subPackages/charging/terminal/terminal?deviceId=' + item.connectorCode + "&deviceStatus=" + item.status);
		},
		//去查看全部电站
		toDeiceAll() {
			this.$app.url.goto('/subPackages/charging/site-more/site-more?stationId=' + this.stationDetail.stationId)
		},
		//去查看全部电价
		toPriceAll() {
			this.$app.url.goto('/subPackages/charging/site-more/site-more?show=1&stationId=' + this.stationDetail.stationId)
		},
		//扫一扫
		sacn() {
			this.$app.act.scan().then(res => {
				console.log(res);
				var paramObj = this.getUrlParams(res.result);
				if (!paramObj || !paramObj.connectorCode) {
					this.$app.popup.alert("二维码不正确。", "温馨提示！");
					return;
				}
				this.getDeviceInfo(paramObj.connectorCode);
			})
		},
		getUrlParams(url) {
			const paramsRegex = /[?&]+([^=&]+)=([^&]*)/gi;
			const params = {};
			let match;
			while (match = paramsRegex.exec(url)) {
				params[match[1]] = match[2];
			}
			return params;
		},
		//通过充电桩编码（sn）获取设备详情
		getDeviceInfo(sn) {
			this.$api.base("get", "/applet/v1/station/connector/detail", { "connectorCode": sn }, {}).then(res => {
				console.log("设备信息：", res)
				this.goTerminal(res.data);
			})
		}
	}
}
</script>

<style scoped>
@import url("new-site.css");
</style>