<template>
	<view class="service-main">
		<navBar type="index"></navBar>
		<!-- #ifdef MP-WEIXIN -->
		<map @markertap='markertapFn' class="my_app" id="myMap" :longitude="myLocation.longitude"
			:latitude="myLocation.latitude" :scale="18" show-location enable-3D show-compass enable-overlooking
			:enable-satellite="false" :markers="markers" :polyline="polylines" :enable-traffic="false"
			style="width: 100%; height: calc(50vh - 0rpx)">
			<block v-for="(item, index) in nearCabinetList" :key="index">
				<cover-view v-if="selectType === 'cabinet'" slot="callout" :marker-id="item.id" class="mark blue_bg">
					{{ item.available_cnt }}
				</cover-view>
			</block>
		</map>
		<!-- #endif -->

		<!-- #ifdef APP -->
		<googleMap keyId="1" width="100%" height='calc(50vh - 0rpx)' @changMarkertap="changMarkertap"
			v-if="myLocation.latitude" :mapData='markers' :myLocation='myLocation'></googleMap>
		<!-- #endif -->

		<!-- 地图控件 -->
		<cover-view @click="isSearch = false" :class="[
        'control-icon-view',
        'flex-row',
        isSearch ? 'flex-between' : 'flex-end',
      ]">
			<cover-view v-if="isSearch" class="seach-return-view flex-row"><cover-image class="seach-return-img"
					src="https://qiniu.bms16.com/Fjpnr3cH9ZqTQrGlw3Ywp3qbJGIG"></cover-image></cover-view>
			<!-- <cover-view @tap="moveToLocation" class="current-location-view flex-row"><cover-image
					class="current-location-icon"
					src="https://qiniu.bms16.com/FgLe8FKDOzgt3wxi2lZt-yQGmbP3"></cover-image></cover-view> -->
		</cover-view>
		
		<view class="store-cabinet-block">
			<view class="block-p"></view>
			<view v-if="isSearch" class="search-view flex-row">
				<view class="search-input-view">
					<img class="search-icon" src="https://qiniu.bms16.com/FgvJrOE8Lps7tyNL86SOZKbLT1uH" alt="" />
					<input v-model="inputSearchValue" type="text" class="search-input" placeholder="请输入搜索内容"
						placeholder-class="input-placeholder" :focus="isFocused" @focus="handleFocus"
						@blur="handleBlur" />
					<img v-if="isFocused" @tap="clearSearch" class="search-close-icon"
						src="https://qiniu.bms16.com/FhKzwftEPo70kloqIVxKH7g0pD6I" alt="清空" />
				</view>
				<view v-if="isFocused" @tap="tapSearch" :class="['search-btn', isFocused ? 'search-btn-i' : '']">搜索
				</view>
			</view>
			<view class="flex-row flex-between" style="margin-bottom: 40rpx">
				<view class="check-type flex-row">
					<view @tap="tapSelectType" data-type="store" :class="[
              'store-type',
              selectType === 'store' ? 'store-type-i' : 'store-type-s',
            ]">门店</view>
					<view @tap="tapSelectType" data-type="cabinet" :class="[
              'cabinet-type',
              selectType === 'cabinet' ? 'cabinet-type-i' : 'cabinet-type-s',
            ]">换电柜</view>
				</view>
				<view class="config-view flex-row">
					<view class="seach-img" @tap="openSearch"><img
							src="https://qiniu.bms16.com/FiWnFuZm5vWQ_Si3CEYLGJnVhSal" alt="搜索" /></view>
					<view @tap="openSelectType" class="screen-img"><img
							:src="'https://qiniu.bms16.com/'+(shop_type!=''?'FikPWd13ENc2SWnC3q1n5F22uUDs':'FpElQHM5NbxHDjz1LrwaHYN668LR')"
							alt="筛选" /></view>
				</view>
			</view>
			<CarRentalList :activeMarkersId='activeMarkersId' v-if="selectType === 'store'" :near_store_list="nearCabinetList" />
			<CabinetList v-if="selectType === 'cabinet'" :near_cabinet_list="nearCabinetList" />
		</view>
		<leaseType :showLeaseType="showLeaseType" :selectType="selectType" :modelTypeList="modelTypeList"
			@closeSelectType="closeSelectType" @checkCabinetType="checkCabinetType" />
			
		<CustomTabbar curt-tab="service" />
	</view>
</template>

<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 http_gyq = require("@/common/request.js");
	var storage = require("@/common/storage.js");
	import LeaseType from "./components/leaseType/leaseType";
	import CarRentalList from "./components/carRentalList/carRentalList";
	import CabinetList from "./components/cabinetList/cabinetList";
	import CustomTabbar from "@/component/customTabbar/index";
	import googleMap from "@/component/googleMap/googleMap";
	import {
		LEASE_TYPE_ARR
	} from '@/common/constant.js'
	const SHOPSELECTIMG = `https://qiniu.bms16.com/FkS7hjd6tl6ydLIi9-SQI0vGboMW`
	const CABINET_ICON_URL =
		"https://zxappfile.bms16.com/zx_client/shop_mark.png";

	const CABINET_ICON_URLS =
		"https://qiniu.bms16.com/FmYKRICv7sPvsFuFB3wo9MIkpd0-";
	export default {
		data() {
			return {
				activeMarkersId: 0,
				myLocation: {
					latitude: 0,
					longitude: 0,
				},
				selectType: "store",
				type: 1,
				nearStoreList: [],
				nearCabinetList: [],
				markers: {},
				polylines: [],
				mapContext: null, // map上下文
				isSearch: false, //是否处于搜索状态
				inputSearchValue: "",
				isFocused: false,
				showLeaseType: false,
				modelTypeList: [],
				shop_type: ''
			};
		},
		components: {
			googleMap,
			LeaseType,
			CarRentalList,
			CabinetList,
			CustomTabbar,
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.loadModelType();
			this.locationFn()
		},

		methods: {
			//点击图标跳转
			changMarkertap(e) {
				this.activeMarkersId= e.id
				let index = 0
				for (var i = 0; i < this.nearCabinetList.length; i++) {
					var item = this.nearCabinetList[i];
					if (item.id == e.id) {
						index = i
						break
					}
				}
				this.nearCabinetList.unshift(this.nearCabinetList.splice(index, 1)[0])
			},

			markertapFn(e) {
				let markerId = e.markerId
				if (markerId == 5000) return
				if (this.selectType == 'store') {
					this.markers.map(item => {
						if (markerId == item.id) {
							item.iconPath = SHOPSELECTIMG
							let distance = common.getFlatternDistance(this.myLocation.longitude, this.myLocation
								.latitude, item.longitude, item.latitude)
							let time = Math.ceil(Number(((distance - 0) / 1000).toFixed(2)) * 25 / 10)
							let content = `${common.formatDistance(Number(distance))} 骑行${time}分钟`
							item.label = {
								content,
								color: "#0074FF",
								fontSize: 10,
								bgColor: "#fff",
								borderRadius: 10,
								padding: 5,
								anchorX: -45,
								anchorY: -6
							}
							this.activeMarkersId = item.id
						} else {
							item.iconPath = CABINET_ICON_URL
							item.label = {}
						}
					})
				} else if (this.selectType == 'cabinet') {

				}

			},


			locationFn() {
				let _this = this
				uni.getLocation({
					success(res) {
						_this.myLocation = {
							latitude: res.latitude,
							longitude: res.longitude,
						}
						_this.loadCarRentalList();
					}
				})
			},

			tapSelectType(e) {
				const {
					type
				} = e.currentTarget.dataset;
				this.nearCabinetList = []
				console.log(type)
				this.setData({
					selectType: type,
				});
				console.log(type == 'store' ? 1 : 2)
				this.type = type == 'store' ? 1 : 2
				if (type === "store") {
					this.loadCarRentalList();
				} else {
					this.loadNearCabinetList();
				}

			},
			//附近门店列表
			loadCarRentalList(name = '', shop_type = '') {
				const pData = {
					limit: 50,
					longitude: this.myLocation.longitude,
					latitude: this.myLocation.latitude,
					name,
					shop_type
				};
				const me = this;
				var nearCabinetList = [];
				http.postApi(config.API_NEAR_SHOP_LIST, pData, (resp) => {
					if (resp.data.code == 200) {
						me.markers = {}
						let markers = {
							markers: []
						}
						nearCabinetList = resp.data.data.list.map(item => {
							return {
								...item,
								distance: common.formatDistance(common.getFlatternDistance(this.myLocation
									.longitude, this
									.myLocation.latitude, item.longitude, item.latitude))
							}
						})
						markers.markers = nearCabinetList.map(item => {
							return {
								width: 50,
								height: 52,
								id: Number(item.id),
								longitude: item.longitude,
								latitude: item.latitude,
								iconPath: CABINET_ICON_URL,
								iconPathActive: SHOPSELECTIMG,
								content: '233'
							}
						})

						this.getLocationPostion(this.myLocation, markers);
						// console.log(nearCabinetList, "nearCabinetList");
						me.setData({
							nearCabinetList: nearCabinetList,
						});
					} else {
						common.simpleToast(resp.data.msg);
					}
				});
			},
			//附近机柜列表
			async loadNearCabinetList(name = '') {
				const pData = {
					limit: 50,
					longitude: this.myLocation.longitude,
					latitude: this.myLocation.latitude,
					name
				};
				const me = this;
				var nearCabinetList = [];
				let {
					data
				} = await http_gyq.postApi(config_gyq.API_FLK_CABINET_NEAR_LIST, pData)
				if (data.code === 200) {
					this.markers = {}
					nearCabinetList = data.data.cabinetList || [];
					let markers = {}
					markers.markers = nearCabinetList.map(item => {
						return {
							width: 56,
							height: 56,
							id: Number(item.id),
							longitude: item.longitude,
							latitude: item.latitude,
							iconPath: CABINET_ICON_URLS,
							iconPathActive: CABINET_ICON_URLS,
							content: '21'
						}
					})
					this.getLocationPostion(this.myLocation, markers);
					me.setData({
						nearCabinetList: nearCabinetList,
					});

				} else {
					common.simpleToast(data.msg);
				}
			},

			getLocationPostion(centerLocation, markers) {
				const locationData = {
					longitude: centerLocation.longitude,
					latitude: centerLocation.latitude,
					width: 22,
					height: 40,
					id: 50000,
					iconPath: "https://zxappfile.bms16.com/zx_client/location_n.png",
					model_list: [],
				};
				markers.markers.push(locationData);
				markers.type = this.type
				this.markers = markers
				console.log(this.markers)
			},
			moveToLocation() {
				// 将marker移动至中心点
				const mapContext = uni.createMapContext("myMap", this);
				this.mapContext = mapContext;
				this.mapContext.moveToLocation({
					longitude: this.myLocation.longitude,
					latitude: this.myLocation.latitude,
					success: (res) => {
						console.log("marker已移动至中心点");
					},
				});
			},
			handleFocus() {
				this.isFocused = true;
			},
			handleBlur() {
				this.isFocused = false;
			},
			clearSearch() {
				this.setData({
					inputSearchValue: "",
				});
			},
			openSearch() {
				this.isSearch = true;
				this.isFocused = true;
			},
			openSelectType() {
				this.setData({
					showLeaseType: true,
				});
			},
			closeSelectType() {
				this.setData({
					showLeaseType: false,
				});
			},
			tapSearch() {
				if (this.selectType === 'store') {
					this.loadCarRentalList(this.inputSearchValue)
				} else {
					this.loadNearCabinetList(this.inputSearchValue)
				}
			},
			checkCabinetType(e) {
				console.log(e, "e");
				const obj = LEASE_TYPE_ARR.find(v => v.value == e)
				const shop_type = (e == 100) ? '' : obj.type
				this.setData({
					showLeaseType: false,
					shop_type
				});
				this.loadCarRentalList('', shop_type)
			},
			loadModelType() {
				const me = this
				http.postApi(config.API_NEAR_BATTERY_TYPE_LIST, {}, (resp) => {
					if (resp.data.code === 200) {
						me.setData({
							modelTypeList: resp.data.data.list
						})
					} else {
						common.simpleToast(resp.data.msg);
					}
				});
			},
		},
	};
</script>
<style>
	@import "./service.css";
</style>