<template>
  <view class="parking">
    <view class="loading" v-show="loading">
      <u-loadmore status="loading" icon-type="flower" :load-text="{ loading: '正在定位中...' }" />
    </view>
    <view class="parking-header">
      <u-search placeholder="搜索停车点" v-model="searchContent" :show-action="false" @change="searchInputChange"> </u-search>
      <u-icon
        v-if="!searchContent && isShowSearchParking == false"
        class="icon"
        name="list"
        size="44"
        color="#ffffff"
        placeholder-color="#B5B5B5"
        search-icon-color="#B3B3B3"
        @click="listIconClick"
      >
      </u-icon>
      <u-icon
        v-if="searchContent || isShowSearchParking == true"
        class="icon"
        name="close"
        size="36"
        color="#ffffff"
        placeholder-color="#B5B5B5"
        search-icon-color="#B3B3B3"
        @click="clearSearchInput"
      >
      </u-icon>
    </view>
    <view class="parking-map">
      <map
        id="pagemap"
        style="width: 100%; height: calc(100vh - 240rpx)"
        :show-location="true"
        :latitude="latitude"
        :longitude="longitude"
        @markertap="markertap"
        :enable-traffic="true"
        :enable-zoom="true"
        :scale="scale"
        :markers="covers"
      ></map>
    </view>
    <view class="address-box" :class="nearParkingObj.type == 'down' ? 'address-down' : 'address-up'" v-if="nearParkingFlag">
      <view class="address-box-down-icon" :class="{ 'up-icon': nearParkingObj.type === 'up' }" @click="pullDown"> </view>
      <scroll-view scroll-y class="address-box-scroll" :style="{ height: `calc(${nearParkingObj.height} - 76rpx)` }">
        <view class="address-box-list">
          <view class="address-box-list-item" v-for="(item, index) in nearParkingList" :key="index" @click="positionAddress(item)">
            <view class="abli-header">
              <view class="abli-header-title"
                >{{ item.roadName }} <text class="abli-header-subtitle">{{ item.areaName }}</text></view
              >
              <!-- <view class="abli-header-subtitle">{{ item.areaName }}</view> -->
              <view class="abli-header-surplus">
                <view class="abli-header-surplus-left"
                  >余位<text>{{ item.spaceIdle }}</text></view
                >
                <view class="abli-header-surplus-right" :class="{ disabled: !item.monthAmount }" @click.stop="createMonth(item)">办理包月</view>
              </view>
            </view>
            <view class="abli-bottom">
              <view class="abli-bottom-left">
                <view class="abli-bottom-left-navigation" @click.stop="navigation(item.latitude, item.longitude, item.areaName)">导航</view>
                <view class="abli-bottom-left-distance">{{ item.distance | kmUnit }}</view>
              </view>
              <view class="abli-bottom-right" @click.stop="lookParkingRule(item)">收费规则</view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="parking-address-list" v-if="isShowSearchParking">
      <view class="parking-address-list-item" v-for="(item, index) in searchParkingList" :key="index + 's'" @click="clickSearchParking(item)">
        <view class="pali-left">
          <view>{{ item.roadName }}</view>
          <view>{{ item.areaName }}</view>
        </view>
        <view class="pali-right">
          <image src="../../static/img/distance-icon.png" mode="" @click.stop="navigation(item.latitude, item.longitude, item.areaName)"></image>
          <view>路线</view>
        </view>
      </view>
    </view>
    <u-select v-model="mapSelect" :list="mapSelectList" @confirm="mapSelectConfirm"></u-select>
    <map id="map" hidden="true"></map>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
import { qqMapTransBMap } from '@/utils/mapTrans.js';
export default {
  data() {
    return {
      searchContent: '',
      page_map: '',
      loading: false,
      latitude: 26.64969,
      longitude: 106.636453,
      scale: 16,
      currentPosition: {
        latitude: 26.64969,
        longitude: 106.636453
      },
      covers: [],
      // 附近列表是否显示
      nearParkingFlag: false,
      // 轮播选中
      swiperCurrent: 0,
      // 附近停车列表
      nearParkingList: [],
      // 是否显示停车场列表
      isShowSearchParking: false,
      // 搜索停车场列表
      searchParkingList: [],
      // 显示单个停车场数据
      isShowParkingDetail: false,
      // 单个停车场数据
      parkingDetailData: {},
      mapSelect: false,
      mapSelectList: [
        {
          value: '1',
          label: '腾讯地图'
        },
        {
          value: '2',
          label: '百度地图'
        },
        {
          value: '3',
          label: '高德地图'
        }
      ],
      // 选中位置经纬度
      currentPositionHover: {},
      nearParkingObj: {
        height: '60vh',
        type: 'down'
      }
    };
  },
  onLoad(page) {
    this.getLocation();
    if (page.keyword) {
      this.searchContent = page.keyword;
      this.searchInputChange(page.keyword);
    }
  },
  methods: {
    /**
     * 查询输入框发生变化
     * @date 2021-08-10
     * @param {String} value
     */
    searchInputChange(value) {
      // 为空时关闭搜索列表
      if (value === '') {
        this.isShowSearchParking = false;
      }
      this.isShowParkingDetail = false;
      this.getNearRoadsl();
    },
    /**
     * 获取定位
     * @date 2021-08-10
     * @returns {any}
     */
    getLocation() {
      const that = this;
      console.log('请求定位');
      // that.getNearRoadsl();
      that.loading = true;
      if (navigator.geolocation) {
        // 判断是否有这个对象
        navigator.geolocation.getCurrentPosition(function (pos) {
          console.log('经度：' + pos.coords.longitude + '纬度：' + pos.coords.latitude);
          that.latitude = pos.coords.latitude;
          that.longitude = pos.coords.longitude;
          that.currentPosition.latitude = pos.coords.latitude;
          that.currentPosition.longitude = pos.coords.longitude;
          that.loading = false;
          that.getNearRoadsl();
        });
      } else {
        this.$refs.uToast.show({
          title: '当前系统不支持GPS API',
          type: 'error'
        });
      }
    },
    /**
     * 导航
     * @date 2021-08-10
     * @param {Number} latitude
     * @param {Number} longitude
     * @returns {any}
     */
    navigation(latitude, longitude, areaName) {
      this.currentPositionHover = {
        latitude,
        longitude,
        areaName
      };
      this.mapSelect = true;
    },
    // 多地图选择
    mapSelectConfirm(item) {
      const name = item[0].label;
      switch (name) {
        case '腾讯地图':
          location.href = `https://apis.map.qq.com/uri/v1/routeplan?type=drive&from=我的位置&fromcoord=${this.currentPosition.latitude},${this.currentPosition.longitude}&to=${this.currentPositionHover.areaName}&tocoord=${this.currentPositionHover.latitude},${this.currentPositionHover.longitude}&policy=1&referer=BOGBZ-2BZ33-O4L32-Y3QJR-PGN66-RFFEL`;
          break;
        case '百度地图':
          const lnglatObj = qqMapTransBMap(this.currentPositionHover.longitude, this.currentPositionHover.latitude);
          location.href = `http://api.map.baidu.com/marker?location=
			${lnglatObj.lat},${lnglatObj.lng}&title=目的地&content=${this.currentPositionHover.areaName}
			&output=html&src=webapp.baidu.openAPIdemo`;
          break;
        case '高德地图':
          location.href = `https://uri.amap.com/navigation?from=${this.currentPosition.longitude},${this.currentPosition.latitude},我的位置&to=${this.currentPositionHover.longitude},${this.currentPositionHover.latitude},${this.currentPositionHover.areaName}&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0`;
          break;
      }
    },
    /**
     * 清空搜索框内容
     * @date 2021-08-10
     * @returns {any}
     */
    clearSearchInput() {
      this.searchContent = '';
      this.isShowSearchParking = false;
      this.getNearRoadsl();
    },
    /**
     * 默认首个点放大 如果有传入经纬度则对应的点放大
     * @date 2021-08-10
     * @param {Number} lon
     * @param {Number} lat
     * @returns {any}
     */
    getNearRoadsl(lon, lat) {
      this.$u.api
        .nearRoadsl({
          latitude: this.currentPosition.latitude,
          longitude: this.currentPosition.longitude,
          roadName: this.searchContent
        })
        .then((res) => {
          const nearParkingList = []; // 附近停车场列表
          this.covers = [];
          res.data.forEach((item, index, arr) => {
            if (item.latitude && item.longitude) {
              nearParkingList.push(item);
              const marker = {
                latitude: item.latitude,
                longitude: item.longitude,
                id: String(index),
                iconPath: require('./../../static/img/parking-icon.png'),
                width: 20,
                height: 25
              };
              // 选中经纬度图标变大
              if (lon && lat) {
                if (lon === item.longitude && lat === item.latitude) {
                  marker.width = 40;
                  marker.height = 50;
                }
              } else {
                if (this.covers.length > 0) {
                  this.covers[0].width = 40;
                  this.covers[0].height = 50;
                }
              }
              this.covers.push(marker);
            }
          });
          this.nearParkingList = nearParkingList;
          if (nearParkingList.length > 0) {
            this.latitude = nearParkingList[0]?.latitude || this.currentPosition.latitude;
            this.longitude = nearParkingList[0]?.longitude || this.currentPosition.longitude;
          } else {
            this.$refs.uToast.show({
              title: '没有相关停车场信息',
              type: 'warning'
            });
          }
          this.nearParkingFlag = true;
          if (this.searchContent) {
            this.searchParkingList = nearParkingList;
            this.isShowSearchParking = true;
            this.nearParkingFlag = false;
          }
        })
        .catch((err) => {
          this.$refs.uToast.show({
            title: err.msg,
            type: 'error'
          });
        });
    },
    /**
     * 点击地图上的标记点触发
     **/
    markertap(e) {
      let lon, lat;
      this.covers.forEach((item, index) => {
        if (e.detail.markerId === item.id) {
          lon = item.longitude;
          lat = item.latitude;
          this.swiperCurrent = index;
        }
      });
      this.getNearRoadsl(lon, lat);
    },
    /**
     * 地址发生变化
     * @date 2021-08-10
     * @param {Object} item
     * @returns {any}
     */
    swiperChange(item) {
      const map = uni.createMapContext('pagemap');
      map.moveToLocation({
        longitude: this.nearParkingList[item.detail.current].longitude,
        latitude: this.nearParkingList[item.detail.current].latitude
      });
      this.getNearRoadsl(this.nearParkingList[item.detail.current].longitude, this.nearParkingList[item.detail.current].latitude);
    },
    /**
     * 点击单个地址
     * @date 2022-08-31
     * @param {any} item
     * @returns {any}
     */
    positionAddress(item) {
      const map = uni.createMapContext('pagemap');
      map.moveToLocation({
        longitude: item.longitude,
        latitude: item.latitude
      });
      this.getNearRoadsl(item.longitude, item.latitude);
    },
    /**
     * 点击单个停车场看详情
     * @date 2021-08-10
     * @param {Object} item 为选中项参数
     * @returns {any}
     */
    clickSearchParking(item) {
      if (item.monthAmount) {
        this.$u.route({
          url: 'pages/parkingInformation/parkingInformation',
          params: {
            roadInfo: JSON.stringify(item),
            longitude: this.currentPosition.longitude,
            latitude: this.currentPosition.latitude
          }
        });
      }
    },
    /**
     * 跳转停车标准页面
     * @date 2021-08-10
     * @param {Object} item
     * @returns {any}
     */
    lookParkingRule(item) {
      this.$u.route({
        url: 'pages/chargeStandard/chargeStandard',
        params: {
          roadNo: item.roadNo
        }
      });
    },
    /**
     * 搜索右侧按钮点击
     **/
    listIconClick() {
      this.isShowSearchParking = true;
      this.nearParkingFlag = false;
      this.searchParkingList = this.nearParkingList;
    },
    /**
     * 跳转包月
     * @date 2021-08-10
     * @param {Object} item
     * @returns {any}
     */
    createMonth(item) {
      if (item.monthAmount) {
        this.$u.route({
          url: 'pages/handleMonthly/handleMonthly',
          params: {
            roadNo: item.roadNo
          }
        });
      }
    },
    pullDown() {
      if (this.nearParkingObj.height === '20vh') {
        this.nearParkingObj.height = '60vh';
        this.nearParkingObj.type = 'down';
      } else {
        this.nearParkingObj.height = '20vh';
        this.nearParkingObj.type = 'up';
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.wrap {
  margin-top: 20vh;
}

@import './parkingLists.scss';
</style>
