<template>
	<view>
		<block v-if="isLogin && car_info.car_sn">
			<view class="container-view"> 
			<navBar type="index" />
				<view class="flex-row flex-between align-center padding_about_40">
					<view class="car-name-view" @tap="navSwitchCar">
						<text style="margin-right: 10rpx;">{{car_info.car_name}}</text>
						<img src="https://qiniu.bms16.com/FoSXDpVGvbdmwbX3CMUBvR7X4IzI"
							style="width: 14rpx;height: 14rpx;" alt="">
					</view>
					<view @click="routerLink('/pages/message/index')" class="news">
						<view v-if="(newsList.plate_count + newsList.device_count) > 0" class="num">{{newsList.plate_count + newsList.device_count}}</view>
						<image src="https://qiniu.bms16.com/FtlfBtBE5-TeTI5EdrciX_u8u_Sx"
							style="width: 48rpx;height: 48rpx;" mode=""></image>
					</view>
				</view>
				<view v-if="isOverdueShow" class="overdue-view flex-row flex-between">
					<view class="overdue-view-text flex-row">
						<text class="overdue-text-left">您已逾期
							<text class="overdue-num">
								<block v-if="orderInfo.hire_duration_time">
									{{orderInfo.hire_duration_time.day > 0 ? orderInfo.hire_duration_time.day :'' }}<text
										v-if="orderInfo.hire_duration_time.day>0">日</text>{{orderInfo.hire_duration_time.hour > 0 ? orderInfo.hire_duration_time.hour :'' }}<text
										v-if="orderInfo.hire_duration_time.hour>0">小时</text>{{orderInfo.hire_duration_time.minute > 0 ? orderInfo.hire_duration_time.minute :'' }}<text
										v-if="orderInfo.hire_duration_time.minute>0">分</text>
								</block>
							</text>
						</text>
						<text style="font-size: 24rpx;opacity: 0.5;">请及时续费或归还车辆</text>
					</view>
					<view @click="routerLink('/pages/order/order')" class="renew-btn">去续费</view>
				</view>
				<view class="car-img-view" @tap="toMoreInfoPage">
					<view class="quantity-view flex-row">
						<text class="quantity flex-row">{{car_info.soc}} <text
								style="font-size: 28rpx;font-weight: 500;">%</text></text>
						<u-line-progress style="width: 100rpx;" active-color="#2ADA62" height="10" :show-percent="false"
							:percent="car_info.soc"></u-line-progress>
						<text class="quantity-text flex-row">
							<text style="font-weight:400;font-size: 22rpx;">{{$t("续航")}}</text>
							<text style="font-size: 36rpx;">{{car_info.endurance}}</text><text
								style="font-size: 30rpx;">km</text>
						</text>
					</view>
					<!-- <img :src="car_info.model_images||'https://qiniu.bms16.com/Fg8_p7083jpsy8BXG4bR6yMs7jQX'" style="width: 100%;height: 526rpx;" alt=""> -->
					<img :src="'https://qiniu.bms16.com/Fg8_p7083jpsy8BXG4bR6yMs7jQX'"
						style="width: 100%;height: 526rpx;" alt="">
					<view class="flex-row align-center update-time-view">
						<text style="margin-right: 10rpx;">{{$t("车辆已关机")}} </text>
						<text style="margin-right: 10rpx;">{{$t("更新于")}} {{car_info.heart_time|| ''}}11-25 23:05 </text>
						<img src="https://qiniu.bms16.com/FsL6XWGoIhfsVB7jRg6EGFVsuaTZ"
							style="width: 24rpx;height: 32rpx;" alt="">
					</view>
				</view>
				<Control :contrilList="contrilList" />


				<view v-if="car_info.exchange_package_info && car_info.exchange_package_info.activity_time"
					class="flex-row flex-between map-card-view">
					<MapCard :car_info="car_info" />

					<view class="card-right">
						<view class="card-bg" @tap="navTravelingTrack">
							<view class="flex-row flex-between card-top-title">
								<view class="flex-row align-center">
									<img style="width: 36rpx;height: 36rpx;"
										src="https://qiniu.bms16.com/FkrcMCV__HraZ0W0NBNdEZPIlwss" alt="">
									<text class="margin_l_8">{{isTrackOrAll?'最近骑行':'总里程'}}</text>
								</view>
								<view @tap.stop="isTrackOrAll=!isTrackOrAll"><img style="width: 24rpx;height: 20rpx;"
										src="https://qiniu.bms16.com/FltPK-o7KGS3dQ2pfQHXGSxOdzaN" alt=""></view>
							</view>
							<view class="card-top-text">{{car_info.current_mail}}<text class="font_24">km</text></view>
						</view>

						<view class="card-bg">
							<view class="flex-row card-top-title">
								<img style="width: 36rpx;height: 36rpx;"
									src="https://qiniu.bms16.com/FtalApKa3STyruaBxxRB4O9hHXyE" alt="">
								<text class="margin_l_8">{{$t("换电套餐")}}</text>
							</view>
							<view v-if="car_info.package_type == 1" class=" card-top-text">
								{{calculateRemainingDays(car_info.exchange_package_info.expire_time)}} <text
									class="font_24">{{$t("天")}}</text>
							</view>
							<view v-if="car_info.package_type == 2" class=" card-top-text">{{item.last_num}} <text
									class="font_24">{{$t("次")}}</text></view>
							<view v-if="car_info.package_type == 3" class=" card-top-text">
								{{item.total_day}}{{$t("天")}}/{{item.last_num}} <text class="font_24">{{$t("次")}}</text>
							</view>
						</view>
					</view>
				</view>
				<view class="config-view">
					<view @tap="navToPage" class="flex-row config-car-view">
						<view class="margin_r_20"><img class="icon_style_64"
								src="https://qiniu.bms16.com/Ftzyvs5whxDdMFksYChHaWKVb0Uk" alt=""></view>
						<view class="flex-row config-text-view" @tap="inductiveUnlockHandle">
							<view class="flex-row font_w_600">{{$t("感应解锁")}}</view>
							<view class="flex-row tip-text-config">{{$t("请先连接蓝牙")}}</view>
						</view>
						<img class="icon_style_28" src="https://qiniu.bms16.com/FqnbZ2iKHmzCGJA8XD30sf5g_CAm" alt="">
					</view>
					<view @tap="navToPage" data-url="/pages/userManagement/userManagement"
						class="flex-row config-car-view">
						<view class="margin_r_20"><img class="icon_style_64"
								src="https://qiniu.bms16.com/FhKkijkN__9UzhYNgamBFSggIlYo" alt=""></view>
						<view class="flex-row config-text-view">
							<view class="flex-row font_w_600">{{$t("用车人管理")}}</view>
							<view class="flex-row tip-text-config">{{car_info.share_num + $t("个家庭账号")}}</view>
						</view>
						<img class="icon_style_28" src="https://qiniu.bms16.com/FqnbZ2iKHmzCGJA8XD30sf5g_CAm" alt="">
					</view>
					<view @click="srcFn(`/pages/deviceInfo/deviceInfo`)" class="flex-row config-car-view">
						<view class="margin_r_20"><img class="icon_style_64"
								src="https://qiniu.bms16.com/FsAg6mHEBJfbtpgIHBrDdNiPo1iH" alt=""></view>
						<view class="flex-row config-text-view">
							<view class="flex-row font_w_600">{{$t("设备信息")}}</view>
							<view class="flex-row tip-text-config">{{$t("软件版本") + (car_info.firmware||'')}}</view>
						</view>
						<img class="icon_style_28" src="https://qiniu.bms16.com/FqnbZ2iKHmzCGJA8XD30sf5g_CAm" alt="">
					</view>
				</view>
				<view style="height: 264rpx;"></view>
			</view>
		</block>

		<block v-else>
			<UnleasedPages :model_list="model_list" :img_list="img_list" />
		</block>
		<BluetoothUnlockAuth ref="bluetoothUnlockAuth" />
		<CustomTabbar @changCar='changCar' curt-tab="home"/>
		<AndroidUnlockAuth :value="isShowPermission" @closePermission="closePermission" v-if="isShowPermission && (platform === 'android')" />
		<IosUnlockAuth :value="isShowPermission" @closePermission="closePermission" v-else-if="isShowPermission && (platform === 'ios')" />
	</view>
</template>
<script module="tools" lang="wxs" src="@/pages/common/wxs/tools.wxs"></script>
<script module="tools" lang="sjs" src="@/pages/common/wxs/tools.sjs"></script>
<script>
	var app = getApp();
	var config = require('@/common/config.js');
	var config_gyq = require('@/common/config_gyq.js');
	var common = require('@/common/common.js');
	var http = require('@/common/http.js');
	var request = require('@/common/request.js');
	var storage = require('@/common/storage.js');
	import Control from './components/control/control'
	import MapCard from './components/mapCard/mapCard'
	import UnleasedPages from './components/unleasedPages/unleasedPages'
	import CustomTabbar from '@/component/customTabbar/index';
	import BluetoothUnlockAuth from '../bluetoothUnlock/bluetoothUnlockAuth.vue'
	import AndroidUnlockAuth from './components/AndroidUnlockAuth.vue'
	import IosUnlockAuth from './components/IosUnlockAuth.vue'
	import {
		getFunctionTag,
	} from '@/common/storage.js';
	import permision from "@/js_sdk/wa-permission/permission.js"
	var bluetooth = require('@/common/bluetooth.js');

	export default {
		data() {
			return {
				newsList: {},
				img_list: [],
				isLogin: false,
				isOverdueShow: false,
				contrilList: [],
				isTrackOrAll: true,
				model_list: [],
				car_list: [], //用户车辆列表
				car_sn: '', //当前车辆编号
				isHideInduction: true,
				car_info: {
					exchange_package_info: {
						activity_time: 0
					}
				},
				platform:'android',//手机型号
				isShowPermission:false,//是否打开权限弹窗
				statusBarHeight:0,
			};
		},
		computed: {},
		components: {
			Control,
			MapCard,
			CustomTabbar,
			UnleasedPages,
			BluetoothUnlockAuth,
			AndroidUnlockAuth,
			IosUnlockAuth
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight || 0
			this.locationFn()
			this.loadModelList()
			const user_token = storage.getUserToken()
			if (!user_token) {
				this.loadIsLogin()
				return
			}
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			// const permissionArr=permision.requestAndroidPermissions()
			// app.globalData.permissionArr=permissionArr
			// permision.gotoAppPermissionSetting()
			// let status = checkBatteryOptimizationStatus();
			// if (!permissionArr) {
			//     uni.showModal({
			//         title: "电池优化提示",
			//         content: "您的设备开启了电池优化，可能会影响应用后台运行，请在设置中关闭。",
			//         showCancel: true,
			//         cancelText: "忽略",
			//         confirmText: "去设置",
			//         success(res) {
			//             if (res.confirm) {
			//                 permision.gotoAppPermissionSetting(); // 跳转到电池优化设置
			//             }
			//         }
			//     });
			// }
			// app.globalData.permissionArr=permissionArr
			console.log(getFunctionTag().activeTag)
			this.contrilList = getFunctionTag().activeTag
			const user_token = storage.getUserToken()
			this.car_info = uni.getStorageSync('car_info') || {};
			if (!user_token) {
				this.isLogin = false
				//this.loadIsLogin()

				return
			}
			this.newsNumFn()
			this.isLogin = true
			if (!this.car_info.car_sn) {
				this.loadUserCarList()
			} else {
				this.loadCarDetail(this.car_info.car_sn)
			}

		},
		// 分享给好友
		onShareAppMessage: function(res) { //发送给朋友
			return {
				title: this.appConfig.app_name,
				path: 'pages/index/index',
			}
		},
		methods: {
			async newsNumFn() {
				let {
					data
				} = await request.postApi(config_gyq.API_FLK_MESSAGE_UNREAD_COUNT, {})
				if (data.code == 200) {
					this.newsList = data.data
				}


			},
			locationFn() {
				uni.getLocation({
					success(res) {
						let myLocation = {
							latitude: res.latitude,
							longitude: res.longitude,
						}
						storage.setUserCurrentLocation(myLocation)
					}
				})
			},
			changCar(e) {
				this.car_info = e
			},
			routerLink(url) {
				uni.navigateTo({
					url
				})
			},
			loadIsLogin() {
				uni.showModal({
					title: '提示',
					content: '您还未登录，请先登录',
					showCancel: true,
					cancelText: '取消',
					confirmText: '确定',
					success: function(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/loginRegister/login',
							})
						}
					},
					fail: function(res) {},
					complete: function(res) {},
				})
			},
			connectBluetooth() {
				var device = {
					mac_id: "900000997",
					btid: "900000997",
					btkey: "900000997",
					bt_type: "ZXCar",
					device_type: "ZXCar"
				};
			},
			toMoreInfoPage() {
				uni.navigateTo({
					url: '/pages/moreInfo/moreInfo',
				});
			},
			navTravelingTrack() {
				uni.navigateTo({
					url: '/pages/travelingTrack/travelingTrack?longitude=' + this.longitude + '&latitude=' + this
						.latitude,
					success: function(res) {},
					fail: function(res) {},
					complete: function(res) {}
				});
			},
			inductiveUnlockHandle() {
				const permissionArr=permision.requestAndroidPermissions(this.platform)
				app.globalData.permissionArr=permissionArr
				// let isOpenAllPermission=false
				// app.globalData.permissionArr.map(item=>{
				// 	if(!item.state) isOpenAllPermission=true
				// })
				// this.isShowPermission=true
				this.setData({
					isShowPermission:true
				})
				// this.$refs.bluetoothUnlockAuth.open();	
				// console.log(this.isOpenAllPermission,'this.isOpenAllPermission');
				// if(!isOpenAllPermission){
				// 	common.simpleToast('所需权限开启成功,前往开启蓝牙配对...');
				// 	uni.navigateTo({ url: '/pages/bluetoothUnlock/bluetoothPair' })
				// }else{
				// 	this.$refs.bluetoothUnlockAuth.open();	
				// }
				
			},
			closePermission(){
				this.setData({
					isShowPermission:false
				})
			},
			showInduction() {
				this.isHideInduction = true
			},
			loadModelList() {
				const me = this
				http.postApi(config.API_RECOMMEND_CAR_MODEL_LIST, {}, (resp) => {
					if (resp.data.code === 200) {
						const list = resp.data.data
						console.log('哈哈哈啊哈')
						console.log(resp.data.data)
						const img_list = resp.data.data.map(item => item.image)
						me.setData({
							model_list: list,
							img_list: img_list
						})
					} else {
						common.simpleToast(resp.data.msg);
					}
				})
			},
			srcFn(url) {
				uni.navigateTo({
					url: url
				});
			},
			navToPage(e) {
				const me = this
				const url = e.currentTarget.dataset.url;
				if (!url) {
					return;
				}
				uni.navigateTo({
					url: url
				});
				// if (me.userInfo.is_auth - 0 == 1 && me.userInfo.status - 0 == 2) {
				// 	uni.navigateTo({
				// 		url: url
				// 	});
				// } else if (me.userInfo.is_auth - 0 == 1 && me.userInfo.status - 0 != 2) {
				// 	uni.showModal({
				// 		title: '身份认证提示',
				// 		content: '尚未完成身份认证，是否进行身份认证?',
				// 		cancelText: '取消',
				// 		confirmText: '确定',
				// 		success: function(res) {
				// 			if (res.confirm) {
				// 				me.loadFaceToken()
				// 			}
				// 		},
				// 		fail: function(res) {},
				// 		complete: function(res) {},
				// 	})
				// } else {
				// 	uni.showModal({
				// 		title: '提示',
				// 		content: '您还未登录，请先登录',
				// 		showCancel: true,
				// 		cancelText: '取消',
				// 		confirmText: '确定',
				// 		success: function(res) {
				// 			if (res.confirm) {
				// 				//#ifdef MP-ALIPAY
				// 				uni.navigateTo({
				// 					url: '/pages/phoneLogin/phoneLogin',
				// 				})
				// 				//#endif
				// 				//#ifdef MP-WEIXIN
				// 				uni.navigateTo({
				// 					url: '/pages/login/login',
				// 				})
				// 				//#endif
				// 			}
				// 		},
				// 		fail: function(res) {},
				// 		complete: function(res) {},
				// 	})
				// }
			},
			loadUserCarList() {
				const me = this
				common.loading()
				http.postApi(config.API_FLK_CAR_DEVICE_LIST, {}, (resp) => {
					uni.hideLoading();
					if (resp.data.code === 200) {
						const list = resp.data.data.list
						if (list.length > 0) {
							me.setData({
								car_list: list,
								car_sn: list[0].car_sn || '',
							})
							me.loadCarDetail(list[0].car_sn)
						}
					} else {
						common.simpleToast(resp.data.msg);
					}
				})
			},
			loadCarDetail(car_sn) {
				const me = this
				common.loading()
				http.postApi(config.API_FLK_CAR_DETAIL, {
					car_sn
				}, (resp) => {
					uni.hideLoading();
					if (resp.data.code === 200) {
						resp.data.data.car_sn = car_sn
						me.setData({
							car_info: resp.data.data,
						})
						uni.setStorageSync('car_info', this.car_info);
						//判断逾期
						if(!resp.data.data.sold_time) return 
						let time = Math.ceil(resp.data.data.hire_end_time - Math.floor(new Date()) / 1000) / 60
						if (time > 0) {
							this.isOverdueShow = true
							this.car_info.hire_end_time = common.getTimeToDay(time)
						} else {
							this.isOverdueShow = false
						}

					} else {
						common.simpleToast(resp.data.msg);
					}
				})
			},
			navSwitchCar() {
				const me = this
				//如果租/购多个车辆的话可以切换当前车辆
				uni.navigateTo({
					url: `/pages/carList/carList?list=${encodeURIComponent(JSON.stringify(me.car_list))}&car_sn=${me.car_sn}`,
				})
			},
			formatDistance(distanceMeters) {
				// 判断距离是否超过1000米  
				// let distanceMeters=Number(_distanceMeters)
				if (distanceMeters >= 1000) {
					// 如果超过1000米，则转换为千米并返回  
					return (distanceMeters / 1000).toFixed(1);
				} else {
					// 否则直接返回米  
					return distanceMeters.toFixed(0);
				}
			}

		}
	};
</script>

<style lang="scss" scoped>
	@import './index.css';

	.news {
		position: relative;

		.num {
			position: absolute;
			right: -6rpx;
			top: -6rpx;
			min-width: 28rpx;
			height: 28rpx;
			font-size: 18rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #fff;
			line-height: 1;
			background-color: #FA2918;
			border-radius: 50%;
		}
	}
</style>