import config from '@/config';
import store from '@/store';

export {
  // 判断当前位置是否在指定坐标的一定范围内
  isWithinLocation,
  checkLoactionInDestance
}

function isWithinLocation() {
  let targetLocationInfo, maxDistance;
  // 是否有权限不限制距离 true-不限制，false-限制
  let remoteControl = store.state.user.userInfo.remoteControl;
  let companyConfig = store.state.company.companyConfig;

  if (companyConfig.sagaCare && companyConfig.sagaCareLimit) {
    maxDistance = companyConfig.sagaCareDistance;
    let location = companyConfig.sagaCareCoords.split(',');
    targetLocationInfo = {
      longitude: location[0],
      latitude: location[1]
    }
  };
  maxDistance = maxDistance || 1;
  let toastTip = '您好像不在公司';
  if (remoteControl || (companyConfig.sagaCare && !companyConfig.sagaCareLimit)) {
    return Promise.resolve();
  } else if (config.isOpenLocationPermisson) {
    return checkLoactionInDestance(targetLocationInfo, maxDistance).then((res) => {
      return Promise.resolve(res);
    }, (res) => {
      if (res.reason == 'overDistance') {
        setTimeout(() => {
          wx.showToast({
            title: toastTip,
            duration: 2000,
            icon: 'none'
          })
        }, 0);
      }
      return Promise.reject(res);
    })
  } else {
    return Promise.resolve()
  }
}

function checkLoactionInDestance(targetLocationInfo, maxDistance) {
  return new Promise((resolve, reject) => {
    let locationInfo = store.state.location.locationInfo;
    if (locationInfo.getLastTime + 30e3 > new Date().getTime()) { // - 30秒内返回旧值
      locationInfo.method === 'resolve' ? resolve() : reject(locationInfo.data);
      return;
    }

    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType;
        if (networkType == 'none') {
          wx.showToast({
            title: '网络故障，请稍后重试',
            duration: 2000,
            icon: 'none'
          })
          reject({ reason: 'networkException' });
        } else {
          wx.authorize({
            scope: 'scope.userLocation',
            success: () => {
              // wx.getLocation({
              //   success(res) {
              //     let distance = getDistance(res.latitude, res.longitude, targetLocationInfo.latitude, targetLocationInfo.longitude);
               
              //     if (distance <= maxDistance) {
              //       store.commit('setLocationInfo', {
              //         getLastTime: new Date().getTime(),
              //         data: null,
              //         method: 'resolve'
              //       });
              //       resolve()
              //     } else {
              //       store.commit('locaitonInfo', {
              //         getLastTime: new Date().getTime(),
              //         data: { reason: 'overDistance' },
              //         method: 'reject'
              //       });
              //       reject({ reason: 'overDistance' });
              //     }
              //   },
              //   fail(res) {
              //     let msg = res.errMsg;
              //     switch (res.error) {
              //       case 11:
              //         msg = '无法使用位置服务';
              //         break;
              //       case 12:
              //         msg = '网络异常，请稍后再试';
              //         break;
              //       case 13:
              //         msg = '定位失败，请稍后再试';
              //         break;
              //       case 14:
              //         msg = '业务定位超时，请稍后再试';
              //         break;
              //       default:
              //         msg = '请前往系统设置开启微信定位权限';
              //     }
              //     store.commit('locaitonInfo', {
              //       getLastTime: new Date().getTime(),
              //       data: { reason: 'systemError' },
              //       method: 'reject'
              //     });
              //     reject({ reason: 'systemError' });
              //     setTimeout(() => {
              //       wx.showToast({
              //         title: msg,
              //         duration: 2000,
              //         icon: 'none'
              //       });
              //     }, 0);
              //   }
              // })
            },
            fail: () => {
              wx.showModal({
                title: '提示',
                content: '请授权位置信息',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success: () => {
                      },
                      fail: (res) => {
                        console.log(res);
                      }
                    });
                  }
                }
              })
              store.commit('locaitonInfo', {
                getLastTime: new Date().getTime(),
                data: { reason: 'unAuthorized' },
                method: 'reject'
              });
              reject({ reason: 'unAuthorized' });
            }
          })
        }
      }
    })
  })
}

/**
* 计算两个经纬度的距离(千米)
*/
function getDistance(lat1, lng1, lat2, lng2) {
  var radLat1 = lat1 * Math.PI / 180.0;
  var radLat2 = lat2 * Math.PI / 180.0;
  var a = radLat1 - radLat2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
    Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137;// EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000;
  console.log('getDistance计算两个经纬度的距离(千米)', lat1, lng1, lat2, lng2, s)
  return s;
}
