<template>
	<view class="main-view">
		<Navigation :scroll='scrollTop'></Navigation>
		<view class="content">
			<swiper v-if="shop_image.length!=0" class="swiper" :indicator-dots="true" :autoplay="true" :interval="2000"
				indicator-color="rgba(0, 0, 0, 0.3)" indicator-active-color="#000000" :duration="1000" circular>
				<swiper-item class="swiper-item" v-for="(item,index) in shop_image" :key="index">
					<image class="swiper-item-img" :src="item" mode="aspectFit"></image>
				</swiper-item>
			</swiper>
			<img v-else class="bg-img" src="https://qiniu.bms16.com/FhRnr7rADHHsOFfpWO4duD15SgIt" alt="">
		</view>
		<view class="cabinet-detail">
			<view class="cabinet-name-view flex-row flex-between">
				<view class="cabinet-name">{{cabinetInfo.cabinet_name}}</view>
				<!-- <view class="distance">{{cabinetInfo.distance}}km</view> -->
			</view>

			<view v-if="tagList.length==0" class="no_battery">
					{{ $t('无可用电池') }}
				</view>
				<view class="flex-row" style="justify-content: center;">
					<view class="icon-box flex-row">
						<view v-for="(item, index) in tagList" class="item-tag flex-row">
							<text class="tag_name">
								{{item.main_tag_name ? (item.main_tag_name) : ''}}{{item.child_tag_name ? '/' + item.child_tag_name : ''}}·
							</text>
							<text class="tag_num">{{'x' + item.num}}</text>
						</view>
					</view>
				</view>

			<view class="flex-row flex-between">
				<view :class="isWorkTimer ? 'left_grid_2' : 'left_grid_1'">
					<view class="flex-row">
						<img class="icon_grid"
							:src="!isWorkTimer ? 'https://zxappfile.bms16.com/zx_admin/cab_timer.png' : 'https://zxappfile.bms16.com/zx_admin/cab_timer_work.png'">
						<view :class="isWorkTimer ? 'grid_text_1' : 'grid_text_rest' ">{{isWorkTimer ? $t('营业中'): t('已休息')}}
						</view>
					</view>
					<view class="grid_text_2">
						{{cabinetInfo.work_begin_time!=null?cabinetInfo.work_begin_time:'00:00'}}-{{cabinetInfo.work_end_time!=null?cabinetInfo.work_end_time:'23:59'}}
					</view>
				</view>
				<view @tap="navToCabinet" class="right_grid flex-between">
					<view>
						<view class="cab_distance">
							{{ $t('直线距您') }}{{cabinetInfo.distance>1?(cabinetInfo.distance+$t('千米')):(cabinetInfo.distance*1000+$t('米'))}}
						</view>
						<view class="cab_address">{{cabinetInfo.address}}</view>
					</view>
					<view>
						<img class="icon_grid_1" src="https://zxappfile.bms16.com/zx_admin/cab_nav.png">
						<view class="grid_nav">{{ $t('导航') }}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="battery-list-view">
			<view class="battery-title flex-row flex-between">
				<text class="blod-text">{{ $t('格口详情') }}</text>
				<text class="cabinet-ref">{{ $t('电柜编号：') }}<text class="cabinet-ref-text"> {{cabinetInfo.dev_id}}</text></text>
			</view>
			<view class="battery-list-main flex-row flex-start">
				<view class="battery-list" v-for="(item, index) in batteryList" :key="item.unique">
					<!-- <block v-if="item.isReservation">
							<view class="battery-list-g">
								<view class="namber-view flex-row">
									<view class="namber namber-g">
										{{item.box_sn}}
									</view>
								</view>
	
								<view class="status-img-view flex-row">
									<img class="status-img" src="https://zxappfile.bms16.com/zx_admin/reservation.png"
										alt="">
								</view>
								<view class="tip-text tip-text-g1">{{ $t('已预约') }}</view>
							</view>
						</block> -->
					<!-- {{ $t('没有预约') }}-->
					<!-- <block v-else> -->
					<!-- {{ $t('空仓或者仓门不可用') }}-->
					<view v-if="!item.cabinet_battery_sn||(item.fault_reason&&item.fault_reason.length>0)"
						:class="(item.fault_reason&&item.fault_reason.length>0)?'battery-list-s':'battery-list-g'">
						<!-- <view class="namber-view flex-row">
									<view
										:class="(item.fault_reason&&item.fault_reason.length>0)?'namber namber-s':'namber namber-g'">
										{{item.box_sn}}
									</view>
								</view> -->

						<view class="namber-view flex-row flex-between">
							<view
								:class="(item.fault_reason&&item.fault_reason.length>0)?'namber namber-s':'namber namber-g'">
								{{item.box_sn}}
							</view>
							<view v-if="item.tag_info" class="tag_type_n">
								{{item.tag_info.main_tag_name ? (item.tag_info.main_tag_name) : ''}}{{item.tag_info.child_tag_name ? '/' + item.tag_info.child_tag_name : ''}}
							</view>
						</view>

						<view class="status-img-view flex-row">
							<img v-if="!item.cabinet_battery_sn&&!(item.fault_reason&&item.fault_reason.length>0)"
								class="status-img" src="https://qiniu.bms16.com/FtOgmvwtoUCVzEyxIau6-6i0hjLt" alt="">
							<img v-if="item.fault_reason&&item.fault_reason.length>0" class="status-img"
								src="https://qiniu.bms16.com/FmMGYfe7eRSQvM8zeKEVeSmzbArd" alt="">
						</view>
						<!-- <view class="battery-ref">124513215</view> -->
						<view v-if="!item.cabinet_battery_sn&&!(item.fault_reason&&item.fault_reason.length>0)"
							class="tip-text tip-text-g">{{ $t('空仓') }}</view>
						<view v-if="item.fault_reason&&item.fault_reason.length>0" class="tip-text tip-text-u">
							{{item.fault_reason[0]}}
						</view>
					</view>
					<!-- {{ $t('满电或者电量未满') }} -->
					<view v-else :class="(item.is_full_soc==1)?'battery-list-b':'battery-list-o'">
						<view class="namber-view flex-row flex-between">
							<view :class="(item.is_full_soc==1)?'namber namber-b':'namber namber-o'">{{item.box_sn}}
							</view>
							<view v-if="item.tag_info" class="tag_type">
								{{item.tag_info.main_tag_name ? (item.tag_info.main_tag_name) : ''}}{{item.tag_info.child_tag_name ? '/' + item.tag_info.child_tag_name : ''}}
							</view>
						</view>
						<view class="status-img-view flex-row">
							<view v-if="item.cabinet_battery_sn" class="progress-bar-view">
								<progressView :soc="item.soc" :status="item.is_full_soc"></progressView>
							</view>
							<view v-if="item.cabinet_battery_sn" class="battery-number">
								{{item.battery_sn}}
								<!-- 0168 8256 9608 -->
							</view>
						</view>
						<view v-if="item.is_full_soc==1" class="tip-text tip-text-b">{{ $t('电池可用') }}</view>
						<view v-else class="tip-text tip-text-o">{{ $t('待充满') }}</view>
					</view>
					<!-- </block> -->
				</view>
			</view>
			<scanBtn :dev_id="dev_id" :listData='listData' :cab_info="cabinetInfo" @refreshCabinet="refreshCabinet"
				@popPackageModel="clickPopPackageModel" ref="scanRef"></scanBtn>
		</view>

	</view>
</template>

<script>
	import {
		getLocation,
		msg,
		strJoin
	} from '../../utils/util.js';
	import progressView from '@/component/progressView/progressView';
	const http = require('../../common/request.js');
	const config = require('../../common/config_gyq.js');
	const common = require('../../common/common.js');
	var user = require('../../common/user.js');
	var bluetooth = require('../../common/bluetooth.js');
	var cabinetDetailImpl = require('./cabinetDetailImpl.js');
	// const IndexBind = require('../index/model/indexBind.js');
	const DF_CAB_INFO_DONE = 10000; //机柜信息传输完成
	import scanBtn from '@/component/scanCabBtn/scanBtn';
	export default {
		components: {
			progressView,
			scanBtn
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop
		},
		data() {
			return {
				dev_id: '',
				listData: {},
				isWorkTimer: true,
				tagList: [],
				batteryList: [], //电池列表
				isOpenBluetooth: false,
				isBluetooth: false, //存储蓝牙状态
				isShowToBuy: false,
				payType: 0,
				myLocation: {},
				reservation_info: [],
				cabinetInfo: {}, //机柜详情
				num: 0,
				is_scan: 0,
				fre_price: 0,
				online_status: 0, //0离线 1 在线
				wallet_money: 0, //钱包余额
				scan_dev_id: '', //扫码机柜id
				license_plate_number: '', //车牌号
				can_battery_num: 0, //可用电池数
				blueInfo: {}, //蓝牙信息
				cabBatterySn: '', //蓝牙换电需要的数据 cabinet_battery_sn
				shop_image: [],
				isShowAppoint: false,
				packType: 0,
				notShow: 0,
				car_info: {}
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.notShow = options.notShow ? options.notShow : 1
			this.dev_id = options.dev_id
			const storedLocation = uni.getStorageSync('user_current_location');
			this.car_info = uni.getStorageSync('car_info') || {};
			const car_list = uni.getStorageSync('user_car_list') || null
			this.license_plate_number = car_list ? car_list.plate_number : ''
			const me = this
			if (storedLocation && storedLocation.longitude && storedLocation.latitude) {
				// 如果本地有存储的定位信息，则直接使用
				this.setData({
					myLocation: storedLocation
				});
				if (options && options.dev_id != '' && options.is_scan == 1) {
					this.is_scan = 1
					this.dev_id = options.dev_id
				}
				if (options && options.dev_id != '') {
					this.dev_id = options.dev_id
					this.loadCabinetDetail();
				}
			} else {
				// this.getLocationAndSave();
			}
			// bluetooth.initBluetooth()

		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {

		},
		methods: {
			clickClosePackage() {
				this.setData({
					isModelCenter: false
				})
			},
			clickPopPackageModel(e, notShow) {
				// console.log(e.packType,notShow,'sadasd');

				// this.notShow = notShow?notShow:this.notShow
				// if ((e.packType === 0&&this.notShow==1) || e.packType === 2) {
				// 	this.setData({
				// 		isModelCenter: true,
				// 		packType: e.packType
				// 	})
				// }
				// if (e.packType === 1) {
				// 	if (this.is_scan === 1) {
				// 		this.$refs.scanRef.loadNowCabinetDetail(this.dev_id)
				// 	}
				// }
				// if (e.packType === 3) {
				// 	if (this.is_scan === 1) {
				// 		this.getBindBattery(e)
				// 	}
				// }
			},

			getBindBattery(packInfo) {
				this.loadNowCabinetDetail(this.dev_id, this.myLocation, packInfo.order_sn, (bindSuccess) => {
					uni.showModal({
						title: this.$t('提示'),
						content: this.$t('领取电池成功'),
						confirmText: this.$t('确定'),
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								setTimeout(() => {
									uni.switchTab({
										url: '/pages/index/index'
									});
								}, 1500)
							}
						},
						fail: function(res) {},
						complete: function(res) {},
					})
				})
			},

			//计算电池数量
			deduplicateAndCountByMainAndChild(data) {
				// 1. 统计次数：根据 main_tag_code 和 child_tag_code（如果存在）
				const countMap = {};

				data.forEach(item => {
					// 如果 child_tag_code 为空，则只根据 main_tag_code 统计
					const key = item.child_tag_code ?
						`${item.main_tag_code}_${item.child_tag_code}` :
						item.main_tag_code;

					countMap[key] = (countMap[key] || 0) + 1;
				});

				// 2. 去重并添加 num 字段
				const seen = new Set();
				return data.filter(item => {
					// 生成去重键（与统计时逻辑一致）
					const key = item.child_tag_code ?
						`${item.main_tag_code}_${item.child_tag_code}` :
						item.main_tag_code;

					// 如果是第一次出现，添加 num 并保留
					if (!seen.has(key)) {
						seen.add(key);
						item.num = countMap[key]; // 直接修改原对象（如需要深拷贝可改用 { ...item, num }）
						return true;
					}
					// 否则过滤掉
					return false;
				});
			},

			async loadCabinetDetail() {
				//获取机柜信息
				const that = this
				var _can_num = 0
				let resp = await http.postApi(config.API_CABINET_INFO, {
					car_sn: this.car_info.car_sn,
					dev_id: this.dev_id,
					longitude: this.myLocation.longitude,
					latitude: this.myLocation.latitude,
				})
				if (resp.data.code === 200) {
					// const _batteryList = resp.data.data.boxList
					// // 计算可用电池数
					// for (let i = 0; i < _batteryList.length; i++) {
					// 	if (_batteryList[i].cabinet_battery_sn && (!(_batteryList[i].fault_reason &&
					// 			_batteryList[i].fault_reason.length > 0))) {
					// 		_can_num = _can_num + 1
					// 	}
					// }

					var cabinetInfo = resp.data.data.cabinetInfo
					cabinetInfo.work_begin_time = cabinetInfo.work_begin_time == null ? '00:00' : cabinetInfo
						.work_begin_time
					cabinetInfo.work_end_time = cabinetInfo.work_end_time == null ? '00:00' : cabinetInfo
						.work_end_time
					const isWorkTimer = cabinetDetailImpl.isWithinTimeRange(cabinetInfo.work_begin_time,
						cabinetInfo.work_end_time)
					var reservation_List = resp.data.data.cabinetInfo.reservation_info
					var box_list = resp.data.data.boxList
					// box_list = cabinetDetailImpl.getBoxReservation(box_list, reservation_List)
					console.log(box_list, "box_list")
					let tagList = []
					box_list.map(item => {
						if (item.tag_info) {
							tagList.push(item.tag_info)
						}

					})
					tagList = this.deduplicateAndCountByMainAndChild(tagList)
					that.setData({
						reservation_info: reservation_List,
						isWorkTimer: isWorkTimer,
						tagList,
						cabinetInfo: cabinetInfo,
						batteryList: box_list,
						listData: resp.data.data,
						online_status: cabinetInfo.online_status,
						can_battery_num: resp.data.data.can_exchange_num,
						shop_image: JSON.parse(cabinetInfo.imgs.split(',')) || []
					})
				} else {
					common.simpleToast(resp.data.msg)
					// setTimeout(() => {
					// 	uni.switchTab({
					// 		url: '/pages/index/index'
					// 	});
					// }, 1500)
				}
			},
			refreshCabinet() {
				this.loadCabinetDetail()
			},

			navToCabinet() {
				//导航去机柜
				const {
					latitude,
					longitude,
					cityname,
					address,
					cabinet_name
				} = this.cabinetInfo
				uni.openLocation({
					latitude: latitude - 0,
					longitude: longitude - 0,
					scale: 15,
					name: cabinet_name,
					address: address,
					success: function(res) {}
				});
			},
			getLocationAndSave: function() {
				const me = this;
				uni.getLocation({
					type: 'gcj02',
					success: function(res) {
						uni.hideLoading();
						var myLocation = {
							longitude: res.longitude,
							latitude: res.latitude
						}
						me.setData({
							myLocation: myLocation
						})
						uni.setStorageSync('user_current_location', myLocation);
					},
					fail: function(res) {
						uni.hideLoading();
					},
					complete: function(res) {
						uni.hideLoading();
					}
				});
			},
			loadNowCabinetDetail(dev_id, myLocation, order_sn, bindSuccess, bluetoothCallBack) {
				const timeNow = Date.now()
				const me = this
				const pData = {
					longitude: myLocation.longitude,
					latitude: myLocation.latitude,
					dev_id: dev_id || '',
					time: timeNow
				}
				http.postApi(config.API_DAYHIRE_CABINRT_CABINRT_INFO, pData, (resp) => {
					if (resp.data.code === 200) {
						online_status = resp.data.data.cabinetInfo.online_status
						const device = {
							device_type: "LSCabinet",
							bt_type: "",
							mac_id: resp.data.data.cabinetInfo.bt_mac,
							btid: resp.data.data.cabinetInfo.bt_mac,
							dev_id: resp.data.data.cabinetInfo.dev_id,
							key: decodeKey(resp.data.data.cabinetInfo.bt_sec),
							btkey: resp.data.data.cabinetInfo.bt_mac,
							bt_sec: decodeKey(resp.data.data.cabinetInfo.bt_sec),
							bt_mac: resp.data.data.cabinetInfo.bt_mac
						}
						console.log(online_status)
						if (online_status == 1) {
							console.log("bb设备数据", device)
							toBindBattery(DEVICE_TYPE_CABINET, '', dev_id, order_sn, bindSuccess)
						} else {
							console.log("aa设备数据", device)
							bluetoothCallBack(device)
						}
					} else {
						common.simpleToast(resp.data.msg)
					}
				})
			}
		}

	};
</script>

<style>
	@import './cabinetDetail.css';
</style>