<template>
  <div class="Attendance-address">
    <AiTMap
      :map.sync="map"
      :lib.sync="lib"
      :ops="ops"
      :libraries="['service', 'tools']">
    </AiTMap>
    <u-popup v-model="isShow" :closeable="false" border-radius="32" height="70%" mode="bottom">
			<div class="wrapper">
        <div class="top">
          <span @click="isShow = false">取消</span>
          <span @click="confirm">确定</span>
        </div>
        <div class="address-search">
          <div class="address-search__wrapper">
            <image src="./images/search.png" />
            <input placeholder-style="color: #98A6B6" placeholder="搜索地点" v-model="address" @input="onChange">
          </div>
        </div>
        <scroll-view scroll-y scroll-into-view="address-item1">
          <div class="address-item" :id="'address-item' + index" v-for="(item, index) in addressList" :key="index" @click="chooseAddress(index)">
            <div class="left">
              <h2>{{ item.title }}</h2>
              <p>{{ item._distance >= 0 ? item._distance + 'm内' : '未知' }} | {{ item.address }}</p>
            </div>
            <div class="right" :class="[currIndex === index ? 'active' : '']"></div>
          </div>
				</scroll-view>
        <div class="address-btn" v-if="!isChooseAddress">
          <span>打卡有效范围</span>
          <div class="right" @click="isShowScope = true">
            <i>{{ distance[chooseIndex] }}米</i>
            <image src="./images/w-right.png" />
          </div>
        </div>
      </div>
		</u-popup>
    <u-popup v-model="isShowScope" :closeable="false" :z-index="11111" border-radius="16" mode="bottom">
			<div class="ActionSheet">
        <div class="ActionSheet-list">
          <div
            @click="chooseDistance(index)"
            v-for="(item, index) in distance"
            :key="index"
            :class="[chooseIndex === index ? 'active' : '']">
            {{ item }}
          </div>
        </div>
        <div class="cancel-btn" @click="isShowScope = false">取消</div>
      </div>
		</u-popup>
  </div>
</template>

<script>
  import { mapState, mapActions } from 'vuex'

  export default {
    name: 'ChooseAddess',

    appName: '选择打卡点',

    data () {
      return {
        latitude: '',
        longitude: '',
        isShow: false,
        address: '',
        currIndex: 0,
        chooseIndex: 0,
        isShowScope: false,
        map: null,
        ops: {},
        lib: null,
        map: null,
        latLng: null,
        distance: ['100', '200', '300', '400', '500'],
        addressList: [],
        page: 1,
        marker: null,
        timeout: null,
        isChooseAddress: false
      }
    },

    watch: {
      map (v) {
        if (v) {
          this.init()
        }
      }
    },

    computed: {
      ...mapState(['user',])
    },

    onLoad (query) {
      if (query.type === 'address') {
        this.isChooseAddress = true

        uni.setNavigationBarTitle({
          title: '选择地点'
        })
      }

      this.getLocation()
    },

    methods: {
      ...mapActions(['injectJWeixin']),

      chooseDistance (index) {
        this.chooseIndex = index
        this.isShowScope = false
      },

      getLocation () {
        this.injectJWeixin(['getLocation']).then(res => {
          wx.getLocation({
            type: 'wgs84',
            success: res => {
              this.longitude = res.longitude
              this.latitude = res.latitude
            },
            error: res => {
              console.log(res)
            }
          })
        })
      },

      init () {
        this.map.setZoom(19)
        this.addMarker(this.map.getCenter())
        this.map.on('click', e => {
          this.addressList = []
          this.latLng = e.latLng
          this.isShow = true

          this.addMarker(e.latLng)
          this.getAddress()
        })
      },

      confirm () {
        const address = this.addressList[this.currIndex]
        if (this.isChooseAddress) {
          uni.$emit('filedChange', {
            ...uni.getStorageSync('formConfig'),
            defaultValue: address.title
          })
        } else {
          uni.$emit('address', {
            address: address.address,
            title: address.title,
            lat: address.location.lat,
            lng: address.location.lng,
            distance: this.distance[this.chooseIndex]
          })
        }
        uni.navigateBack({
          delta: 1
        })
      },

      chooseAddress (index) {
        this.addMarker(this.addressList[index].location)
        this.currIndex = index
      },

      addMarker (position) {
        if (this.marker) {
          this.marker.setMap(null)
          this.marker = null
        }
        this.marker = new this.lib.MultiMarker({
          id: 'marker-layer',
          map: this.map,
          styles: {
            marker: new this.lib.MarkerStyle({
              width: 30,
              height: 45,
              anchor: { x: 10, y: 30 }
            }),
          },
          geometries: [{
            id: 'marker',
            styleId: 'marker',
            position: position,
            properties: {
              title: 'marker'
            }
          }]
        })
        this.easeTo(position)
      },

      easeTo (position) {
        this.map.easeTo({
          center: position,
          zoom: 17
        },
        { duration: 500 })
      },

      onChange () {
        if (this.timeout) {
          clearTimeout(this.timeout)
        }
        this.timeout = setTimeout(() => {
          this.currIndex = -1
          new this.lib.service.Suggestion({
            pageSize: 20
          }).getSuggestions({
            keyword: this.address
          }).then(res => {
            this.addressList = []
            if (res.data.length) {
              this.addressList = res.data
            }
          })
        }, 500)
      },

      getAddress () {
        this.currIndex = 0
        new this.lib.service.Search({
          pageSize: 20
        }).explore({
          center: this.latLng,
          radius: 2000,
          orderBy: '_distance'
        }).then(res => {
          this.addressList = []
          if (res.data.length) {
            this.addressList = res.data
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .Attendance-address {
    width: 100%;
    height: 100vh;

    .ActionSheet {
      background: #F5F6F6;

      .ActionSheet-list {
        margin-bottom: 8px;
        background: #fff;

        div {
          height: 112px;
          line-height: 112px;
          text-align: center;
          color: #333333;
          font-size: 32px;
          border-bottom: 1px solid #D8DDE6;

          &.active {
            color: #1365DD;
            font-weight: 600;
          }

          &:active {
            background: #eee;
          }

          &:last-child {
            border: none;
          }
        }
      }

      .cancel-btn {
        height: 112px;
        line-height: 112px;
        color: #333;
        font-size: 32px;
        text-align: center;
        font-weight: 600;
        background: #fff;

        &:active {
          background: #eee;
        }
      }
    }

    * {
      box-sizing: border-box;
      line-height: 1;
      font-style: normal;
    }

    .wrapper {
      height: 100%;
      overflow: hidden;

      scroll-view {
        height: calc(100% - 308px);
        padding: 0 32px;

        .address-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 32px 0;
          border-bottom: 1px solid #EEEEEE;

          &:last-child {
            border: none;
          }

          .left {
            flex: 1;
            margin-right: 20px;
          }

          .right {
            flex-shrink: 1;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            border: 4px solid #CCCCCC;
            transition: all ease 0.3s;

            &.active {
              border: 10px solid #1365DD;
            }
          }

          h2 {
            margin-bottom: 20px;
            color: #222222;
            font-weight: 600;
            font-size: 34px;
          }

          p {
            line-height: 1.2;
            color: #999999;
            font-size: 28px;
          }
        }
      }

      .address-search {
        display: flex;
        align-items: center;
        height: 100px;
        padding: 0 32px;

        .address-search__wrapper {
          display: flex;
          align-items: center;
          width: 100%;
          height: 72px;
          padding: 0 32px;
          background: #F6F7F9;
          border-radius: 36px;

          image {
            width: 48px;
            height: 48px;
          }

          input {
            flex: 1;
            font-size: 26px;
            color: #333;
          }
        }
      }

      .address-btn {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 112px;
        line-height: 112px;
        padding: 0 32px;
        text-align: center;
        color: #FFFFFF;
        font-size: 32px;
        background: #1365DD;

        image {
          width: 32px;
          height: 32px;
          margin-left: 4px;
        }

        .right {
          display: flex;
          align-items: center;
        }
      }

      .top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 96px;
        padding: 0 32px;
        font-size: 32px;
        color: #999;
        font-weight: 600;

        span:last-child {
          color: #222;
        }
      }
    }

    map {
      width: 100%;
      height: 100%;
    }
  }
</style>
