<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
        v-if="searchContent || isShowSearchParking == true"
        class="icon"
        name="close"
        size="36"
        color="#ffffff"
        placeholder-color="#B5B5B5"
        search-icon-color="#B3B3B3"
        @click="clearSearchInput"
      />
    </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"
      />
    </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>
      <!-- tab -->
      <template v-if="projectFlag !== 'zhenning'">
        <u-tabs :list="tabObj.tabList" :is-scroll="false" :current="tabObj.current" bg-color="transparent" @change="tabChange" />
      </template>
      <scroll-view scroll-y class="address-box-scroll" :style="{ height: `calc(${nearParkingObj.height} - 164rpx)` }">
        <view class="address-box-list" v-if="nearParkingList.length > 0">
          <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 || item.parkName }} <text class="abli-header-subtitle">{{ item.areaName }}</text></view
              >
              <view class="abli-header-surplus">
                <view class="abli-header-surplus-left">
                  余位<text>{{ item.spaceIdle || item.surplusPlace }}</text></view
                >
                <template v-if="tabObj.current === 1">
                  <view class="abli-header-surplus-right" @click.stop="createMonth(item)">办理包月</view>
                </template>
                <template v-else-if="item.monthAmount">
                  <view class="abli-header-surplus-right" @click.stop="createMonth(item)">办理包月</view>
                </template>
                <template v-else>
                  <view class="abli-header-surplus-right" :class="{ disabled: !item.monthAmount }"> 办理包月</view>
                </template>
              </view>
            </view>
            <view class="abli-bottom">
              <view class="abli-bottom-left">
                <view
                  class="abli-bottom-left-navigation"
                  v-if="currentPosition.latitude && currentPosition.longitude"
                  @click.stop="navigation(item.latitude, item.longitude, item.roadName || item.parkName)"
                  >导航</view
                >
                <view class="abli-bottom-left-navigation-disabled" @click="disabledNavigation" v-else>导航</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>
        <view class="address-box-list" v-else>
          <u-empty text="暂无数据" mode="list"></u-empty>
        </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 || item.parkName }}</view>
          <view>{{ item.areaName }}</view>
        </view>
        <view class="pali-right" v-if="currentPosition.latitude && currentPosition.longitude">
          <image
            src="../../static/img/distance-icon.png"
            mode=""
            @click.stop="navigation(item.latitude, item.longitude, item.roadName || item.parkName)"
          ></image>
          <view>路线</view>
        </view>
        <view class="pali-right" v-else>
          <image src="../../static/img/distance-icon.png" mode="" @click.stop="disabledNavigation"></image>
          <view>路线</view>
        </view>
      </view>
    </view>
    <u-select v-model="mapSelect" :list="mapSelectList" @confirm="mapSelectConfirm" />
    <map id="map" hidden="true" />
    <u-toast ref="uToast" />
  </view>
</template>

<script>
import { qqMapTransBMap } from '@/utils/mapTrans.js';
export default {
  data() {
    return {
      tabObj: {
        current: 0,
        tabList: [
          {
            name: '路段'
          },
          {
            name: '停车场'
          }
        ]
      },
      searchContent: '',
      page_map: '',
      loading: false,
      latitude: 26.64969,
      longitude: 106.636453,
      scale: 16,
      currentPosition: {
        latitude: '',
        longitude: ''
      },
      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;
      const obj = {
        0: 'getNearRoadsl',
        1: 'getParkingLotList'
      };
      this[obj[this.tabObj.current]]();
    },
    /**
     * 获取定位
     * @date 2021-08-10
     * @returns {any}
     */
    getLocation() {
      const that = this;
      console.log('请求定位');
      that.loading = true;
      if (navigator.geolocation) {
        const obj = {
          0: 'getNearRoadsl',
          1: 'getParkingLotList'
        };
        // 判断是否有这个对象
        navigator.geolocation.getCurrentPosition(
          function (pos) {
            console.log('浏览器获取位置成功:', JSON.stringify(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[obj[that.tabObj.current]]();
          },
          function (err) {
            console.log('浏览器获取位置失败:', JSON.stringify(err));
            that.loading = false;
            that.$refs.uToast.show({
              title: '您已拒绝授权位置信息或者获取位置信息失败!',
              type: 'error',
              duration: 4000
            });
            that[obj[that.tabObj.current]]();
          },
          {
            timeout: 15000
          }
        );
      } else {
        that.loading = false;
        that.$refs.uToast.show({
          title: '当前系统不支持GPS API',
          type: 'error',
          duration: 4000
        });
        that[obj[that.tabObj.current]]();
      }
    },
    /**
     * 导航
     * @date 2021-08-10
     * @param {Number} latitude
     * @param {Number} longitude
     * @returns {any}
     */
    navigation(latitude, longitude, areaName) {
      this.currentPositionHover = {
        latitude,
        longitude,
        areaName
      };
      this.mapSelect = true;
    },
    disabledNavigation() {
      this.$refs.uToast.show({
        title: '您已拒绝授权位置信息或者获取位置信息失败,无法使用导航功能!',
        type: 'error'
      });
    },
    // 多地图选择
    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;
      const obj = {
        0: 'getNearRoadsl',
        1: 'getParkingLotList'
      };
      this[obj[this.tabObj.current]]();
    },
    /**
     * 默认首个点放大 如果有传入经纬度则对应的点放大
     * @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;
          }
          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'
          });
        });
    },
    getParkingLotList(lon, lat) {
      this.$u.api
        .nearParkingLot({
          status: 1,
          latitude: this.currentPosition.latitude,
          longitude: this.currentPosition.longitude,
          parkName: this.searchContent
        })
        .then((res) => {
          const nearParkingList = []; // 附近停车场列表
          this.covers = [];
          res?.data?.rows.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;
          }
          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;
        }
      });
      const obj = {
        0: 'getNearRoadsl',
        1: 'getParkingLotList'
      };
      this[obj[this.tabObj.current]](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
      });
      const obj = {
        0: 'getNearRoadsl',
        1: 'getParkingLotList'
      };
      this[obj[this.tabObj.current]](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
      });
      const obj = {
        0: 'getNearRoadsl',
        1: 'getParkingLotList'
      };
      this[obj[this.tabObj.current]](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) {
      const obj = {
        0: 'roadNo',
        1: 'parkNo'
      };
      const params = {};
      params[obj[this.tabObj.current]] = item[obj[this.tabObj.current]];
      this.$u.route({
        url: 'pages/chargeStandard/chargeStandard',
        params
      });
    },
    /**
     * 搜索右侧按钮点击
     **/
    listIconClick() {
      this.isShowSearchParking = true;
      this.nearParkingFlag = false;
      this.searchParkingList = this.nearParkingList;
    },
    /**
     * 跳转包月
     * @date 2021-08-10
     * @param {Object} item
     * @returns {any}
     */
    createMonth(item) {
      const obj = {
        0: 'roadNo',
        1: 'parkNo'
      };
      const params = {};
      params[obj[this.tabObj.current]] = item[obj[this.tabObj.current]];
      this.$u.route({
        url: 'pages/handleMonthly/handleMonthly',
        params
      });
    },
    pullDown() {
      if (this.nearParkingObj.height === '20vh') {
        this.nearParkingObj.height = '60vh';
        this.nearParkingObj.type = 'down';
      } else {
        this.nearParkingObj.height = '20vh';
        this.nearParkingObj.type = 'up';
      }
    },
    /**
     * tab切换触发
     * @param {Object} val
     */
    tabChange(val) {
      this.tabObj.current = val;
      const obj = {
        0: 'getNearRoadsl',
        1: 'getParkingLotList'
      };
      this[obj[val]]();
    }
  }
};
</script>

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

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