// map.js
var EARTH_RADIUS = 6378.137; //地球半径
var QQMapWX = require('../../qqmap-wx-jssdk/qqmap-wx-jssdk.js');
// import { QQMapWX } from '../../node_modules/qqmap-wx-jssdk/qqmap-wx-jssdk.js';
var qqmapsdk = new QQMapWX({
    key: 'C4QBZ-UYQLI-S45G2-5ETMC-LQYWE-L6FJU'
  }),
  lat, lon;

function rad(d) {
  return d * Math.PI / 180.0;
}

function getDistance(lng1, lat1, lng2, lat2) {
  var radLat1 = rad(lat1);
  var radLat2 = rad(lat2);
  var a = radLat1 - radLat2;
  var b = rad(lng1) - rad(lng2);
  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 * EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000;
  return s; //返回数值单位:公里
}

Page({
  data: {
    latitudes: "39.10316416330441",
    longitudes: "117.00926862608128",
    latitudess: "",
    longitudess: "",
    suggestion: [],
    markers: [{
      iconPath: '/images/01-01/cart-2.png',
      id: 0,
      latitude: 39.14111,
      longitude: 117.00739,
      width: 50,
      height: 50
    }],
    circles: [{
      latitude: '39.14111',
      longitude: '117.00739',
      color: '#999999',
      fillColor: '#7cb5ec88',
      radius: 150,
      strokeWidth: 2
    }],
    polygons: [{
      points: [{
        longitude: 116.42,
        latitude: 38.33
      }, {
        longitude: 118.324520,
        latitude: 40.21229
      }],
      strokeWidth: 5,
      zIndex: 1,
    }],
    controls: [{
      id: 1,
      iconPath: '/resources/location.png',
      position: {
        left: 0,
        // top: 300 - 50,
        width: 50,
        height: 50
      },
      clickable: true
    }]
  },
  btn() {
    const key = 'C4QBZ-UYQLI-S45G2-5ETMC-LQYWE-L6FJU'; //使用在腾讯位置服务申请的key
    const referer = ''; //调用插件的app的名称
    const location = JSON.stringify({
      latitude: 39.89631551,
      longitude: 116.323459711
    });
    const category = '生活服务,娱乐休闲';

    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`
    });
  },
  onLoad: function (options) {
    let that = this;
    this.getCenterLocation();
    this.getCrlcle();
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res)
        console.log(res.latitude, '111')
        console.log(res.longitude, '222')
        lat = res.latitude;
        lon = res.longitude;
        that.setData({
          latitudess: res.latitude,
          longitudess: res.longitude
        })
      }
    })
  },


  nearby_search: function () {
    var _this = this;
    let location = lat + ',' + lon;
    // 调用接口
    qqmapsdk.search({
      keyword: '', //搜索关键词
      location: location, //设置周边搜索中心点
      success: function (res) { //搜索成功后的回调
        var mks = []
        for (var i = 0; i < res.data.length; i++) {
          mks.push({ // 获取返回结果,放到mks数组中
            title: res.data[i].title,
            id: res.data[i].id,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng,
            iconPath: "/resources/my_marker.png", //图标路径
            width: 20,
            height: 20
          })
        }
        _this.setData({ //设置markers属性,将搜索结果显示在地图中
          markers: mks
        })
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
  getsuggest: function (e) {
    var _this = this;
    let location = lat + ',' + lon;
    //调用关键词提示接口
    qqmapsdk.getSuggestion({
      //获取输入框值并设置keyword参数
      keyword: '', //用户输入的关键词,可设置固定值,如keyword:'KFC'
      location: location,
      //region:'北京', //设置城市名,限制关键词所示的地域范围,非必填参数
      success: function (res) { //搜索成功后的回调
        console.log(res);
        var sug = [];
        for (var i = 0; i < res.data.length; i++) {
          sug.push({ // 获取返回结果,放到sug数组中
            title: res.data[i].title,
            id: res.data[i].id,
            addr: res.data[i].address,
            city: res.data[i].city,
            district: res.data[i].district,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng
          });
        }
        _this.setData({ //设置suggestion属性,将关键词搜索结果以列表形式展示
          suggestion: sug
        });
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
  getCrlcle() {
    this.wxmap = wx.createMapContext('map')
    this.wxmap.getRegion({
      success: res => {
        console.log(res + 'get');
        let lng1 = res.northeast.longitude;
        let lat1 = res.northeast.latitude;
        let lng2 = res.southwest.longitude;
        let lat2 = res.southwest.latitude;

        let longitude = lng1 - lng2;
        let latitude = lat1 - lat2;
        let flag = longitude > latitude ? true : false;
        let radius = 0;
        //计算得到短边,然后再通过*1000转变为m,除2得到半径,*0.8优化显示,让圈圈只占界面的80%
        if (flag) {
          radius = getDistance(lng1, lat1, lng1, lat2) * 1000 / 2 * 0.8;
        } else {
          radius = getDistance(lng1, lat1, lng2, lat1) * 1000 / 2 * 0.8;
        }
        this.setData({
          "circles[0].radius": radius
        });
      }
    });
  },
  getCenterLocation() {
    this.wxmap = wx.createMapContext('map')
    var that = this;
    this.wxmap.getCenterLocation({
      success(res) {
        console.log(res.longitude)
        console.log(res.latitude)
        lon = res.longitude;
        lat = res.latitude;
        that.getsuggest()
        // that.getCrlcle();
        // that.data.markers[1].longitude = res.longitude;
        // that.data.markers[1].latitude = res.latitude;
        // that.setData({
        //   markers: that.data.markers
        // });
      }
    })
  },
  regionchange(e) {
    console.log(e.type)
    this.getCenterLocation();
  },
  markertap(e) {
    console.log(e.markerId)
    console.log(e);
  },
  controltap(e) {
    console.log(e.controlId)
  },

})

//逆解析地址
qqmapsdk.reverseGeocoder({
  location: {
    latitude: lat,
    longitude: lon
  },
  success: function (res) {
    console.log("reverseGeocoder  res地址结果对象", res.result)
    console.log(location, 'location')
  },

  fail: function (res) {
    console.log("获取地址失败");
    console.log(res);
  },

  complete: function (completeres) {
    console.log("获取地址失败");
    console.log(completeres);
  }
});