const QQMapWX = require("./qqmap-wx-jssdk.js");

const req = require("./request.js");

let qqmapsdk;

const initMap = key => {
  if (!qqmapsdk) {
    qqmapsdk = new QQMapWX({
      key: key ? key : req.public.mapLBSKEY
    });
  }
};

const geocoder = (address, success) => {
  //进行地址解析
  qqmapsdk.geocoder({
    address: address,

    success(res) {
      if (res.status !== 0) return req.msg(res.message);
      // if (res.result.deviation < 0 || res.result.reliability < 7) return req.msg('请输入详细的街道及门牌号');
      success.call(this, res.result);
    },

    fail: function (error) {
      console.error(error);
      success.call(this, false);
    },
    complete: function (res) {
      // console.log(res);
    }
  });
}; //计算两点之间的距离默认直线距离


const calculateDistance = (form, to, success, mode) => {
  // console.log(form, to);
  qqmapsdk.calculateDistance({
    mode: mode ? mode : 'straight',
    from: form,
    to: to,

    success(res) {
      // console.log(res);
      if (res.status !== 0) return req.msg(res.message);
      success.call(this, res.result);
    }

  });
}; //计算是否超出配送距离


const calculate = (form, to, distance, success) => {
  calculateDistance(form, to, res => {
    if (res.elements[0].distance / 1000 > distance) {
      return req.msg('非常抱歉，您的配送地址超出我们的配送服务范围');
    } else {
      success.call(this);
    }
  });
};

const reverseGeocoder = (location, success) => {
  qqmapsdk.reverseGeocoder({
    location: location,

    success(res) {
		console.log('反地址地理位置数据>>>>>>>==',res);
		// req.setStorage('loctionAddressMap', res.result.ad_info);
		req.setStorage('loctionAddressMap', res.result);
      success.call(this, res.result);
    },

    fail: function (error) {
      console.error(error);
      success.call(this, false);
    },
    complete: function (res) {
      // console.log(res);
    }
  });
};

module.exports = {
  initMap: initMap,
  geocoder: geocoder,
  calculateDistance: calculateDistance,
  calculate: calculate,
  reverseGeocoder: reverseGeocoder
};