<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 -->
		<view style="width: 100%;height: calc(50vh - 0rpx);">
			<googleMap keyId="1" width="100%" height='calc(50vh - 0rpx)' @changMarkertap="changMarkertap"
				v-if="myLocation.latitude" :mapData='markers' :myLocations='myLocation'></googleMap>
		</view>
		<!-- #endif -->

		<!-- {{ $t('地图控件') }} -->
	<!-- 	<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> -->
		
		<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="$t('请输入搜索内容')"
						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" />
				</view>
				<view v-if="isFocused" @tap="tapSearch" :class="['search-btn', isFocused ? 'search-btn-i' : '']">{{ $t('搜索') }}
				</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',
            ]">{{ $t('门店') }}</view>
					<view @tap="tapSelectType" data-type="cabinet" :class="[
              'cabinet-type',
              selectType === 'cabinet' ? 'cabinet-type-i' : 'cabinet-type-s',
            ]">{{ $t('换电柜') }}</view>
				</view>
				<view class="config-view flex-row">
					<view @click='openSelectType' class="flex-row selectFlex">
						<text v-if="selectType === 'store'" class="text">{{leaseUnitsResult}}{{isBuy ? '+' + $t('购买') : ''}}</text>
						<text v-if="selectType === 'cabinet'" class="text">{{cabinetType ? cabinetType : $t('全部')}}</text>
						<u-icon v-if="showLeaseType" name="arrow-down" color="#9FA7B7" size="26"></u-icon>
						<u-icon v-else name="arrow-up" color="#9FA7B7" size="26"></u-icon>
					</view>
					<view class="seach-img" @tap="openSearch"><img
							src="https://qiniu.bms16.com/FiWnFuZm5vWQ_Si3CEYLGJnVhSal" /></view>
					<!-- <view @tap="openSelectType" class="screen-img"><img
							:src="'https://qiniu.bms16.com/'+(shop_type!=''?'FikPWd13ENc2SWnC3q1n5F22uUDs':'FpElQHM5NbxHDjz1LrwaHYN668LR')"
							alt="{{ $t('筛选') }}" /></view> -->
				</view>
			</view>
			<CarRentalList :isBuy='isBuy' :shopType='shopType' :activeMarkersId='activeMarkersId' v-if="selectType === 'store'" :near_store_list="nearCabinetList" />
			
			<CabinetList v-if="selectType === 'cabinet'" :near_cabinet_list="nearCabinetList" />
		</view>
		<leaseType :isBuy='isBuy' :shopType='shopType' :showLeaseType="showLeaseType" :selectType="selectType" :modelTypeList="modelTypeList"
			@closeSelectType="closeSelectType" @checkCabinetType="checkCabinetType" />
			
		<CustomTabbar curt-tab="service" />
	</view>
</template>

<script>
	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 {
				cabinetType:0,
				shopType:1,
				isBuy:true,
				activeMarkersId: 0,
				selectType: "store",
				type: 1,
				nearStoreList: [],
				nearCabinetList: [],
				markers: {},
				polylines: [],
				mapContext: null, // map上下文
				isSearch: false, //是否处于搜索状态
				inputSearchValue: "",
				isFocused: false,
				showLeaseType: false,
				modelTypeList: [],
				shop_type: ''
			};
		},
		computed: {
			leaseUnitsResult() {
				const result = LEASE_TYPE_ARR.find(v => v.value == this.shopType);
				return result ? result.label : '';
			},
			leaseUnits(){
				const result = LEASE_TYPE_ARR.find(v => v.value == this.shopType);
				return result ? result.unit : '';
			}
		},
		components: {
			googleMap,
			LeaseType,
			CarRentalList,
			CabinetList,
			CustomTabbar,
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.loadModelType();
		},
		onShow() {
			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])
			},
			locationFn() {
				let _this = this
				if (this.selectType === "store") {
					this.loadCarRentalList();
				} else {
					this.loadNearCabinetList();
				}
			},
			tapSelectType(e) {
				const {
					type
				} = e.currentTarget.dataset;
				this.nearCabinetList = []
				this.setData({
					selectType: type,
				});
				this.type = type == 'store' ? 1 : 2
				if (type === "store") {
					this.loadCarRentalList();
				} else {
					this.loadNearCabinetList();
				}

			},
			//附近门店列表
			loadCarRentalList(name = '') {
				const pData = {
					limit: 50,
					longitude: this.myLocation.longitude,
					latitude: this.myLocation.latitude,
					name,
					shop_type:'',
					duration_unit:this.shopType
				};
				const me = this;
				let nearCabinetList = [];
				http.postApi(config.API_NEAR_SHOP_LIST, pData, (resp) => {
					if (resp.data.code == 200) {
						me.markers = {}
						let markers = {
							markers: []
						}
						for (let index = 0; index < resp.data.data.list.length; index++) {
								let element = resp.data.data.list[index];
								element.distance = common.formatDistance(common.getFlatternDistance(this.myLocation
									.longitude, this
									.myLocation.latitude, element.longitude, element.latitude))
								let model_list = []
								
								for (let y = 0; y < element.model_list.length; y++) {
									let item = element.model_list[y];
										item.model_images = item.model_images.split(',')[0] || ''
										let price_setting = []
										for (let i = 0; i < item.price_setting.length; i++) {
											let items1 = item.price_setting[i];
											if(items1.hire_duration_unit == this.shopType){
												item.hire_price = items1.hire_price
												model_list.push(item)
											}
										}
								}
								nearCabinetList.push({
									...element,
									model_list
								})
						}
						
						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);
						this.nearCabinetList = nearCabinetList
					} else {
						common.simpleToast(resp.data.msg);
					}
				});
			},
			//附近机柜列表
			async loadNearCabinetList(cabinet_name = '') {
				const pData = {
					limit: 50,
					longitude: this.myLocation.longitude,
					latitude: this.myLocation.latitude,
					cabinet_name
				};
				const me = this;
				let 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 || [];
					for (let i = 0; i < data.data.cabinetList.length; i++) {
						let item = data.data.cabinetList[i];
						if(this.cabinetType){
							for (let i = 0; i < item.tag_code.length; i++) {
								let items = item.tag_code[i];
								if(items.main_tag_name == this.cabinetType || items.child_tag_name == this.cabinetType){
									nearCabinetList.push(item)
								}
								
							}
						}else{
							nearCabinetList.push(item)
						}
						
					}
					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: item.tag_code.length
						}
					})
					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 = !this.isSearch;
				if(this.isSearch == false){
					this.inputSearchValue = ''
				}
				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) {
				if(e.selectType == "store"){
					this.isBuy = e.isBuy
					this.shopType = e.leaseType
					this.showLeaseType = false
					this.loadCarRentalList()
				}else{
					this.cabinetType = e.leaseType
					this.showLeaseType = false
					this.loadNearCabinetList()
				}
				// 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)
			},
			shopList(list){
				let nearCabinetList = []
				for (let i = 0; i < list.length; i++) {
					let item = list[i];
					for (var index = 0; index < item.model_list.length; index++) {
						var items = item.model_list[index];
							for (var s = 0; s < items.price_setting.length; s++) {
								var element = items.price_setting[s];
								if(element.hire_duration_unit == this.shopType){
									items.hire_price = element.hire_price
								}
							}
					}
					nearCabinetList.push(item)
				}
				this.nearCabinetList = nearCabinetList
			},
			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";
	.selectFlex{
		align-items: center;
		margin-right: 20rpx;
	}
	.selectFlex .text{
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
		color: #060809;
		margin-right: 10rpx;
	}
</style>