<template>
  <view>
    <view class="title">地理位置</view>
    <view v-if="show">
      <map
        class="map"
        :longitude="longitude"
        :latitude="latitude"
        :scale="16"
        :markers="markers"
        :enable-zoom="true"
        :enable-scroll="true"
      ></map>
    </view>
    <view v-else class="map"></view>
    <view class="explain">检查以确保以下地址是正确的</view>
    <view
      class="view-address"
      :style="{ height: calculateStringTotalWidth(address) > 44 ? '120rpx' : '80rpx' }"
    >
      <view class="address">{{ address }}</view>
    </view>
    <view class="bottom">
      <view class="skip" @click="skipAddress">跳过</view>
      <view class="confirm" @click="toBindLock">下一步</view>
    </view>
  </view>
</template>

<script>
  import { mapState, mapActions } from 'pinia'
  import { useBasicStore } from '@/stores/basic'
  import { getGeocodeAddress } from '@/api/geocode'
  import { useBluetoothStore } from '@/stores/bluetooth'

  export default {
    data() {
      return {
        latitude: null,
        longitude: null,
        show: false,
        markers: [],
        address: '',
        first: true
      }
    },
    computed: {
      ...mapState(useBluetoothStore, ['currentLockInfo'])
    },
    onLoad() {
      this.getLocation()
    },
    onShow() {
      if (this.first) {
        this.first = false
      } else if (!this.show) {
        this.getLocation()
      }
    },
    methods: {
      ...mapActions(useBasicStore, ['routeJump', 'calculateStringTotalWidth']),
      ...mapActions(useBluetoothStore, ['updateCurrentLockInfo']),
      toBindLock() {
        const that = this
        if (this.address === '') {
          uni.showModal({
            title: '提示',
            content: '暂未获取到地理位置信息，请重试',
            confirmText: '重试',
            success: res => {
              if (res.confirm) {
                that.getLocation()
              }
            }
          })
          return
        }
        this.routeJump({
          type: 'redirectTo',
          name: 'bindLock'
        })
      },
      skipAddress() {
        const that = this
        if (this.address !== '') {
          uni.showModal({
            title: '提示',
            content: '已获取当前地理位置，确定跳过吗',
            confirmText: '跳过',
            cancelText: '取消',
            success: res => {
              if (res.confirm) {
                const lockInfo = that.currentLockInfo
                delete lockInfo.position
                that.updateCurrentLockInfo(lockInfo)
                this.routeJump({
                  type: 'redirectTo',
                  name: 'bindLock'
                })
              }
            }
          })
          return
        }
        this.routeJump({
          type: 'redirectTo',
          name: 'bindLock'
        })
      },
      async getLocation() {
        const that = this
        uni.getLocation({
          isHighAccuracy: true,
          type: 'gcj02',
          async success(res) {
            that.latitude = res.latitude
            that.longitude = res.longitude
            that.markers = [
              {
                id: 1,
                latitude: res.latitude,
                longitude: res.longitude,
                iconPath: '/static/images/icon_address.png',
                width: '48rpx',
                height: '48rpx'
              }
            ]
            that.show = true
            const { code, data: result } = await getGeocodeAddress({
              latitude: that.latitude,
              longitude: that.longitude
            })
            if (code === 0) {
              that.address = result.addr
              const position = {
                ...result,
                latitude: that.latitude,
                longitude: that.longitude
              }
              console.log('获取地理位置信息', that.currentLockInfo)
              that.updateCurrentLockInfo({
                ...that.currentLockInfo,
                position
              })
              console.log('获取地理位置信息', that.currentLockInfo)
            }
          },
          fail(res) {
            console.log('获取地理位置信息失败', res)
            if (res.errMsg === 'getLocation:fail auth deny') {
              uni.showModal({
                title: '提示',
                content: '拒绝授权将无法使用定位功能',
                confirmText: '去授权',
                cancelText: '跳过',
                success(res) {
                  if (res.confirm) {
                    uni.openSetting()
                  } else {
                    that.routeJump({
                      type: 'redirectTo',
                      name: 'bindLock'
                    })
                  }
                }
              })
            } else if (res.errMsg === 'getLocation:fail system permission denied') {
              uni.showModal({
                title: '提示',
                content: '定位失败，请打开微信的位置权限',
                confirmText: '去打开',
                cancelText: '跳过',
                success(res) {
                  if (res.confirm) {
                    uni.openAppAuthorizeSetting()
                  } else {
                    that.routeJump({
                      type: 'redirectTo',
                      name: 'bindLock'
                    })
                  }
                }
              })
            } else {
              uni.showModal({
                title: '提示',
                content: '获取地理位置信息失败',
                confirmText: '重试',
                cancelText: '跳过',
                success(res) {
                  if (res.confirm) {
                    that.getLocation()
                  } else {
                    that.routeJump({
                      type: 'redirectTo',
                      name: 'bindLock'
                    })
                  }
                }
              })
            }
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  page {
    background-color: $uni-bg-color-grey;
  }
</style>

<style lang="scss" scoped>
  .map {
    width: 750rpx;
    height: 650rpx;
  }

  .title {
    padding: 40rpx 30rpx;
    font-size: 80rpx;
    font-weight: bold;
  }

  .explain {
    padding: 20rpx 30rpx 0 30rpx;
    font-size: 40rpx;
  }

  .view-address {
    display: flex;
    align-items: center;
    width: 690rpx;
    color: #c4c4c4;
    font-size: 32rpx;
    margin: 0 30rpx;
    border-bottom: #63b8af 3rpx solid;

    .address {
      width: 690rpx;
      text-align: left;
      word-break: break-all;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: normal;
    }
  }

  .bottom {
    width: 600rpx;
    display: flex;
    justify-content: space-between;
    padding: 0 75rpx;
    position: fixed;
    bottom: calc(30rpx + env(safe-area-inset-bottom));

    .skip {
      width: 225rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: 36rpx;
      border-radius: 64rpx;
      border: 3rpx solid #63b8af;
    }

    .confirm {
      border-radius: 64rpx;
      color: #ffffff;
      background-color: #63b8af;
      width: 225rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: 36rpx;
    }
  }
</style>
