<template>
<div class='root'>
  <!-- <picker :value='street.index' :range='street.columnOne' @change="pickerConfirm($event,'street')">{{street.label}}</picker>
  <picker v-if="street.label!='点击选择街道'" :value='community.index' :range='community.columnOne' @change="pickerConfirm($event,'community')">{{community.label}}</picker>
  <div v-else class='transparent'/>
  <textarea placeholder="在此记录您当前的详细位置" v-model='text'></textarea>
  <div class='button' :style="style" @tap='canICheckin' :class="{disabled: community.label=='点击选择社区'}">定位</div> -->
  <div class="baseinfo-box">
    <div class="list-input between">
      <span>当前街道</span>
      <picker :value='street.index' :range='street.columnOne' @change="pickerConfirm($event,'street')">
        <div hover-class='hover'>{{street.label}}</div>
      </picker>
    </div>
    <div class="list-input between">
      <span>当前社区</span>
      <picker :value='community.index' :range='community.columnOne' @change="pickerConfirm($event,'community')">
        <div hover-class='hover'>{{community.label}}</div>
      </picker>
    </div>
    <!-- <div class='greytitle' style='margin-top:20rpx;'>详细位置</div>
    <div class='textarea'>
      <textarea placeholder='在此记录您当前的详细位置 (如办公室、事务所大厅等)' v-model='text'></textarea>
    </div> -->
    <div class='tip'>社区定位功能用于收集社区经纬定信息，为本社区打卡提供定位数据。此菜单仅在以下条件下才开启，并只收集一次即可：<br>a. 新加入的社区需要定位数据。<br>b. 社区定位不准确，需要重新定位。<br>c. 社区搬家需要重新定位经纬度。</div>
    <div class='tip strong'>定位时请确认您正在所选社区的办公室门口或方圆50米内。</div>
    <div class='commit' @tap='canICheckin'><div>定位</div></div>
  </div>
</div>
</template>
<script>
export default {
  data() {
    return {
      text: '',
      hasHandleAuth: false,
      street: {
        columnOne: [],
        index: 0,
        arrStruct: [],
        label: '点击选择街道'
      },
      community: {
        columnOne: [],
        index: 0,
        arrStruct: [],
        label: '点击选择社区'
      }
    }
  },
  methods: {
    canIGetPos(){
      return new Promise( resolve => {
        wx.showLoading({title:'加载中'})
        wx.request({
          url: this.rootUrl + '/law/position',
          success: res => {
            wx.hideLoading()
            resolve(res.data)
          }
        })
      })
    },
    canICheckin() {
      this.canIGetPos().then( res => {
        if(res === 0) {
          wx.showModal({title: '您已进行过定位',icon:'none'})
          wx.navigateBack({delta: 1})
        } else {
          wx.showModal({
            title: '',
            content: '若之前已经完成过收集，则不需要重新收集，请点击取消！\n 若未完成过收集，请点击确认',
            success: res => {
              if (res.confirm) {
                wx.showModal({
                  title: '',
                  content: '确定要定位吗？',
                  success: res => {
                    if(res.confirm){
                      if (this.community.label == '点击选择社区') {
                        wx.showModal({
                          title: '定位失败',
                          content: '请选择您当前所在的街道和社区',
                          showCancel: false
                        })
                      } else {
                        this.getLocation()
                      }
                    }
                  }
                })
              }
            }
          })
        }
      })
    },
    getLocation() {
      wx.showLoading({ title: '正在定位' })
      let lat, lng
      wx.getLocation({
        type: 'gcj02',
        success: res => {
          lat = res.latitude
          lng = res.longitude
          wx.request({
            url: this.rootUrl + '/local/add',
            header: {'content-type': 'application/x-www-form-urlencoded'},
            method: 'POST',
            data: {
              // sessionID: wx.getStorageSync('sessionID'),
              SCID: this.community.arrStruct[this.community.index].value,
              latit: lat,
              longi: lng,
              // localName: formatted_address,
              // remark: this.text
            },
            success: res => {
              if (res.statusCode == '500') {
                this.service.getUnionId(this.rootAvatar, this.rootUrl).then(res => {
                  this.getLocation()
                })
              } else {
                wx.hideLoading()
                if (res.data != -2) {
                  wx.showToast({title: '定位成功'})
                  wx.navigateBack({delta:1})
                } else {
                  wx.showModal({
                    title: '定位失败',
                    content: '已超过当日定位次数上限',
                    showCancel: false
                  })
                }
              }
            }
          })
          // wx.request({
          //   url: 'https://api.map.baidu.com/geocoder/v2/',
          //   data: {
          //     ak: 'AnWpq9Kc3C8cq5CCGAzsq3NxpBkxRnl0',
          //     location: `${lat},${lng}`,
          //     coordtype: 'gcj02ll',
          //     output: 'json'
          //   },
          //   success: res => {
          //     const formatted_address = res.data.result.formatted_address
          //     wx.request({
          //       url: this.rootUrl + '/local/add',
          //       header: {'content-type': 'application/x-www-form-urlencoded'},
          //       method: 'POST',
          //       data: {
          //         // sessionID: wx.getStorageSync('sessionID'),
          //         SCID: this.community.arrStruct[this.community.index].value,
          //         latit: lat,
          //         longi: lng,
          //         // localName: formatted_address,
          //         // remark: this.text
          //       },
          //       success: res => {
          //         if (res.statusCode == '500') {
          //           this.service.getUnionId(this.rootAvatar, this.rootUrl).then(res => {
          //             this.getLocation()
          //           })
          //         } else {
          //           wx.hideLoading()
          //           if (res.data != -2) {
          //             wx.showToast({title: '定位成功'})
          //           } else {
          //             wx.showModal({
          //               title: '定位失败',
          //               content: '已超过当日定位次数上限',
          //               showCancel: false
          //             })
          //           }
          //         }
          //       }
          //     })
          //   }
          // })
        },
        fail: err => {
          let authSetting
          wx.getSetting({
            success: res => {
              authSetting = res.authSetting['scope.userLocation']
              console.log(authSetting)
            },
            complete: () => {
              if (authSetting) {
                if (this.hasHandleAuth) {
                  this.getLocation()
                } else {
                  const realName = wx.getStorageSync('userInfo').nickName
                  this.service.UploadBug(this.rootUrl,'test/getLocation/'+realName,JSON.stringify(err))
                  wx.showModal({
                    title: '定位失败',
                    content: '微信未获得位置权限\n请在您手机的系统设置-权限管理中，打开微信的位置信息获取权限',
                    showCancel: false,
                    success: res => {
                      if (res.confirm) {
                        wx.hideLoading()
                      }
                    }
                  })
                }
              } else {
                wx.hideLoading()
                wx.showModal({
                  title: '授权请求',
                  content: '您已拒绝小程序获取地理位置，若要使用定位功能，请重新授权',
                  showCancel: false,
                  success: res => {
                    if (res.confirm) {
                      wx.openSetting({
                        success: res => {
                          if (res.authSetting['scope.userLocation']) {
                            this.hasHandleAuth = true
                            this.getLocation()
                          }
                        }
                      })
                    }
                  }
                })
              }
            }
          })
        }
      })
    },
    getCommunity() {
      if (arguments[0] !== 'first') {
        wx.showLoading({ title: '加载社区列表' })
      }
      wx.request({
        url: this.rootUrl + '/comm/getbyid/' + this.street.arrStruct[this.street.index].value,
        success: res => {
          this.community.columnOne = res.data.map(v => v.comm_Name)
          this.community.arrStruct = res.data.map(v => { return { label: v.comm_Name, value: v.scid } })
          wx.hideLoading()
        }
      })
    },
    pickerConfirm(e, s) {
      switch (s) {
        case 'street': {
          this.street.index = e.mp.detail.value
          this.street.label = this.street.columnOne[this.street.index]
          this.getCommunity()
          break
        }
        case 'community': {
          this.community.index = e.mp.detail.value
          this.community.label = this.community.columnOne[this.community.index]
          break
        }
      }
    }
  },
  onLoad() {
    wx.request({
      url: this.rootUrl + '/street/all',
      success: res => {
        this.street.columnOne = res.data.map(v => v.street_Name)
        this.street.arrStruct = res.data.map(v => {
          return { label: v.street_Name, value: v.ssid }
        })
        this.getCommunity('first')
      }
    })
  }
}
</script>
<style lang="stylus" scoped>
.root
  position absolute
  Height_Width(100%)
  Background()
  .baseinfo-box
    Background()
  .textarea
    padding 20rpx 40rpx
    Font(30rpx, 40rpx)
    textarea
      height 200rpx
      width calc(100% - 20rpx)
      border-radius 10rpx
      border 1rpx solid #EEE
      background white
    div
      text-align right
  .tip
    Font(30rpx,38rpx)
    margin 30rpx 30rpx 0 30rpx
  .strong
    font-weight bold
    color themeColor
</style>
