var api = require('../config/api.js');
var area=require('../utils/area.js');
var util=require('../utils/util.js');
var QQMapWX = require('../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
var app = getApp();

function getCity(){ 
  return new Promise(function(resolve, reject) {  
  qqmapsdk = new QQMapWX({
    key: app.globalData.mapKey //这里自己的key秘钥进行填充
  });

  wx.getSetting({
    success: (res) => {
      console.log(JSON.stringify(res))
      // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
      // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
      // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
      if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
        wx.showModal({
          title: '请求授权当前位置',
          content: '需要获取您的地理位置，请确认授权',
          success: function (res) {
            if (res.cancel) { 
              reject(1);
            } else if (res.confirm) {
              wx.openSetting({
                success: function (dataAu) {
                  if (dataAu.authSetting["scope.userLocation"] == true) {
                    wx.showToast({
                      title: '授权成功',
                      icon: 'success',
                      duration: 1000
                    })
                    //再次授权，调用wx.getLocation的API
                   getLocation().then((res)=>{
                      resolve(res)
                    }).catch((res)=>{
                      reject(res)
                    });

                  } else { 
                   reject(1);
                  }
                }
              })
            }
          }
        })
      }  else {
        //调用wx.getLocation的API
        getLocation().then((res)=>{
          resolve(res)
        }).catch((res)=>{
          reject(res)
        });
      }
    }
  })
  })
}
// 微信获得经纬度
function getLocation () { 
  return new Promise(function(resolve, reject) {
  wx.getLocation({
    type: 'wgs84',
    success: function (res) { 
      var latitude = res.latitude
      var longitude = res.longitude 
      console.info(res)
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: latitude,
          longitude: longitude
        }, 
        success: function (res) {
          ////reject内容 1：未授权（拿默认城市的默认门店） 2：非业务城市 不在服务范围（拿默认城市的默认门店） 3：异常解析()
          let province = res.result.ad_info.province
          let city = res.result.ad_info.city 
          let address=res.result.address;
          console.info(city)
          if(!area.isBusinessCity(city)){//非业务城市
            reject(2);
          } else{//判断是否有门店服务
            util.request(api.OrderBookGetShop,{lng:longitude,lat:latitude}).then(res=>{
              if(res.errno==0){
                var addressInfo={
                  address:address,
                  lng:longitude,
                  lat:latitude,
                  shopId:res.data.shopId,
                  city:city
                }
                wx.setStorageSync('addressInfo', addressInfo)
                resolve(addressInfo)
              }
              else 
                reject(3)
            }).catch(res=>{
              reject(3)
            }) 
          }
          console.info( res) 
        },
        fail: function (res) { 
          reject(3)
        } 
      }); 
    },
    fail: function (res) {
      console.log('fail' + JSON.stringify(res))
      reject(3)
    }
  })
})
}

function chooseLocation(){
  return new Promise(function(resolve, reject) {
    wx.getLocation({
      type: 'wgs84',
      success: function (res) { 
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        wx.chooseLocation({
          success: function(res){
            app.globalData.lng=res.longitude;
            app.globalData.lat=res.latitude;
            app.globalData.address=res.address;
            resolve(true)
          },
          fail: function() {
            reject(false)
          } 
        }) 
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
        reject(false)
      }
    })
  })
}
//判断用户是否拒绝地理位置信息授权，拒绝的话重新请求授权
 function getUserLocation() {
  let that = this;
  wx.getSetting({
    success: (res) => {
      console.log(JSON.stringify(res))
      // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
      // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
      // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
      if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
        wx.showModal({
          title: '请求授权当前位置',
          content: '需要获取您的地理位置，请确认授权',
          success: function (res) {
            if (res.cancel) {
              wx.showToast({
                title: '拒绝授权',
                icon: 'none',
                duration: 1000
              })
            } else if (res.confirm) {
              wx.openSetting({
                success: function (dataAu) {
                  if (dataAu.authSetting["scope.userLocation"] == true) {
                    wx.showToast({
                      title: '授权成功',
                      icon: 'success',
                      duration: 1000
                    })
                    //再次授权，调用wx.getLocation2的API
                    that.getLocation2();
                  } else {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none',
                      duration: 1000
                    })
                  }
                }
              })
            }
          }
        })
      } else if (res.authSetting['scope.userLocation'] == undefined) {
        //调用wx.getLocation2的API
        that.getLocation2();
      }
      else {
        //调用wx.getLocation2的API
        that.getLocation2();
      }
    }
  })
}
// 获取定位当前位置的经纬度
 function getLocation2() {
  let that = this;
  wx.getLocation({
    type: 'wgs84',
    success: function (res) {
      let latitude = res.latitude
      let longitude = res.longitude
      // app.globalData.lat = res.latitude;//
      // app.globalData.lng = res.longitude;//把onload定位时候的经纬度存到全局
     console.log(res);
      that.getLocal(latitude, longitude)
    },
    fail: function (res) {
      console.log('fail' + JSON.stringify(res))
    }
  })
}
 // 获取当前地理位置
  function getLocal (latitude, longitude) {
  let that = this;
  qqmapsdk = new QQMapWX({
    key: app.globalData.mapKey //这里自己的key秘钥进行填充
  });
  qqmapsdk.reverseGeocoder({
    location: {
      latitude: latitude,
      longitude: longitude
    },
    success: function (res) {
      console.log(res);
      // let province = res.result.ad_info.province
      // let city = res.result.ad_info.city
      // let district = res.result.ad_info.district;
      // // 保存一下当前定位的位置留着后面重新定位的时候搜索附近地址用
      // app.globalData.currentLocation = district;
      app.globalData.currentLocationName= res.result.address;
      
      // that.setData({
      //   province: province,
      //   city: city,
      //   latitude: latitude,
      //   longitude: longitude,
      //   district: district
      // })

    },
    fail: function (res) {
      console.log(res);
    },
    complete: function (res) {
      // console.log(res);
    }
  });
}
 


module.exports = {
  getCity:getCity,
  getLocation:getLocation,
  getUserLocation:getUserLocation,
  getLocation2:getLocation2,
  getLocal:getLocal
}