// pages/o2oCity/o2oCity.js
var QQMapWX = require('../../../mymap/qqmap-wx-jssdk.min.js');
var qqmapsdk;
var app = getApp();
Page({

  /**
	 * 页面的初始数据
	 */
  data: {
    city: '',
    suggestion: [],
    suggestion1: [],
    suggestionshow1: false,
    suggestionshow: false,
    address_detail: '',
    address_latitude: '',
    address_longitude: '',
    mksData: [],
    markers: [],
    mapmessageData: {
      title: '',
      message: '',
      latitude: '',
      longitude: '',
      city: ''
    },
    scaleData: 16,
    mapshow: false
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    if(options.id){
      this.setData({
        id:options.id
      });
    }
    if(!app.globalData.qqmapkey) {
      app._getTemplate().then(res => {
        qqmapsdk = new QQMapWX({
          key: app.globalData.qqmapkey
        });
        if (options.tag) {
          this.setData({
            tag: options.tag
          });
        }
        if (options.city) {
          this.setData({
            city: options.city
          });
        }
        this._getLocation();
      });
    }else {
      qqmapsdk = new QQMapWX({
        key: app.globalData.qqmapkey
      });
      if (options.tag) {
        this.setData({
          tag: options.tag
        });
      }
      if (options.city) {
        this.setData({
          city: options.city
        });
      }
      this._getLocation();
    }

  },
  _getLocation() {
    let _this = this;

    qqmapsdk.getSuggestion({
      //获取输入框值并设置keyword参数
      keyword: _this.data.city, //用户输入的关键词，可设置固定值,如keyword:'KFC'
      region: _this.data.city, //设置城市名，限制关键词所示的地域范围，非必填参数
      sig: app.globalData.qqmapsig,
      success: function(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属性，将关键词搜索结果以列表形式展示
          suggestion1: sug,
          suggestionshow1: true
        });
      },
      fail: function(error) {
        console.error(error);
      },
      complete: function(res) {

      }
    });
  },

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {

  },

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {

  },

  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {

  },

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {

  },

  /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function() {

  },

  /**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function() {

  },

  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function() {

  },
  goback() {
    wx.navigateBack({
      delta: 1
    });
    this.setData({
      mapshow: false,
      address_detail: '',
      suggestionshow1: true
    });
  },
  searchconfirmbtn(e) {
    var val = e.detail.value;
    this.addressinp(val);
  },
  addressinpbtn(e) {
    var val = e.detail.value;
    this.addressinp(val);
  },
  addressinp(val) {
    var _this = this;
    if (!val) {
      this.setData({
        suggestionshow: false
      });
      return;
    }
    //调用关键词提示接口
    qqmapsdk.getSuggestion({
      //获取输入框值并设置keyword参数
      keyword: val, //用户输入的关键词，可设置固定值,如keyword:'KFC'
      region: _this.data.city, //设置城市名，限制关键词所示的地域范围，非必填参数
      sig: app.globalData.qqmapsig,
      success: function(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,
          suggestionshow: true
        });
      },
      fail: function(error) {
        console.error(error);
      },
      complete: function(res) {

      }
    });
  },
  //点击数据回填方法
  backfill1: function(e) {
    console.log(e.currentTarget.id,"e.currentTarget.id");
    var id = e.currentTarget.id;
    for (var i = 0; i < this.data.suggestion1.length; i++) {
      if (i == id) {
        this.setData({
          address_detail: this.data.suggestion1[i].title,
          address_latitude: this.data.suggestion1[i].latitude,
          address_longitude: this.data.suggestion1[i].longitude,
          'mapmessageData.title': this.data.suggestion1[i].title,
          'mapmessageData.message': this.data.suggestion1[i].addr,
          'mapmessageData.latitude': this.data.suggestion1[i].latitude,
          'mapmessageData.longitude': this.data.suggestion1[i].longitude,
          'mapmessageData.city': this.data.suggestion1[i].city,
          suggestionshow1: false,
          mapshow: true
        });
        this.nearby_search();
      }
    }
  },
  //数据回填方法
  backfill: function(e) {
    console.log(e.currentTarget.id,"e.currentTarget.id");
    var id = e.currentTarget.id;
    for (var i = 0; i < this.data.suggestion.length; i++) {
      if (i == id) {
        this.setData({
          address_detail: this.data.suggestion[i].title,
          address_latitude: this.data.suggestion[i].latitude,
          address_longitude: this.data.suggestion[i].longitude,
          'mapmessageData.title': this.data.suggestion[i].title,
          'mapmessageData.message': this.data.suggestion[i].addr,
          'mapmessageData.latitude': this.data.suggestion[i].latitude,
          'mapmessageData.longitude': this.data.suggestion[i].longitude,
          'mapmessageData.city': this.data.suggestion[i].city,
          suggestionshow: false,
          mapshow: true
        });
        this.nearby_search();
      }
    }
  },
  // 事件触发，调用接口
  nearby_search: function() {
    var _this = this;
    // 调用接口
    qqmapsdk.search({
      keyword: this.data.address_detail, //搜索关键词
      location: {
        latitude: this.data.address_latitude,
        longitude: this.data.address_longitude
      }, //设置周边搜索中心点
      sig: app.globalData.qqmapsig,
      success: function(res) { //搜索成功后的回调
        // console.log('ccccc', res)
        var mks = [];
        var mksData = [];
        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: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png", //图标路径
            width: 20,
            height: 25,
            callout: {
              padding: '10rpx',
              borderRadius: '5rpx',
              content: res.data[i].title
            }
          });
          mksData.push({
            address: res.data[i].address,
            title: res.data[i].title,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng,
            id: res.data[i].id,
            city: res.data[i].ad_info.city ? res.data[i].ad_info.city : res.res.data[i].ad_info.province
          });
        }
        _this.setData({ //设置markers属性，将搜索结果显示在地图中
          markers: mks,
          mksData: mksData
        });
      },
      fail: function(res) {
        console.log(res);
      },
      complete: function(res) {
        console.log(res);
      }
    });
  },
  getmarkertap(e) {
    let markerId = e.markerId;
    for (var i = 0; i < this.data.mksData.length; i++) {
      let id = this.data.mksData[i].id;
      if (markerId == id) {
        this.setData({
          'mapmessageData.title': this.data.mksData[i].title,
          'mapmessageData.message': this.data.mksData[i].address,
          'mapmessageData.latitude': this.data.mksData[i].latitude,
          'mapmessageData.longitude': this.data.mksData[i].longitude,
          'mapmessageData.city': this.data.mksData[i].city
        });
      }
    }
  },
  addbtn() {
    let mapCtx = wx.createMapContext('myMap');
    let that = this;
    mapCtx.getScale({
      success: function(e) {
        let scale = e.scale;
        that.setData({
          scaleData: scale + 1
        });
      }
    });
  },
  minusbtn() {
    let mapCtx = wx.createMapContext('myMap');
    let that = this;
    mapCtx.getScale({
      success: function(e) {
        let scale = e.scale;
        that.setData({
          scaleData: scale - 1
        });
      }
    });
  },
  buttonbtn() {
    if(this.data.tag == 'activityHome' || this.data.tag == 'activitySearch' || this.data.tag == 'activitySort'){
      wx.setStorage({
        key: "address-point",
        data: { point: { lat: this.data.mapmessageData.latitude, lng: this.data.mapmessageData.longitude }, city: this.data.mapmessageData.city }
      });
    }else if(this.data.tag == 'storeConsume'){
      wx.setStorage({
        key: "address-point",
        data: { point: { lat: this.data.mapmessageData.latitude, lng: this.data.mapmessageData.longitude }, city: this.data.mapmessageData.message }
      });
    }else if(this.data.tag && this.data.tag.indexOf("project_verification")!==-1){
      wx.setStorage({
        key: "address-point",
        data: { point: { lat: this.data.mapmessageData.latitude, lng: this.data.mapmessageData.longitude }, city: this.data.mapmessageData.message }
      });
      switch(this.data.tag){
      case "project_verification/MyProject":
        wx.reLaunch({
          url: '/packageH/project_verification/MyProject/MyProject?location_change=1&Location='+JSON.stringify(this.data.mapmessageData),
        });
        break;
      case "project_verification/VerificationProjectList":
        wx.reLaunch({
          url: '/packageH/project_verification/VerificationProjectList/VerificationProjectList?location_change=1',
        });
        break;
      }
      return;
    }else{
      wx.setStorage({
        key: "address-point",
        data: { point: { lat: this.data.mapmessageData.latitude, lng: this.data.mapmessageData.longitude }, city: this.data.mapmessageData.city }
      });
    }
    wx.setStorage({
      key: "address-status",
      data: '1'
    });
    if (this.data.tag == "hotel") {
      wx.reLaunch({
        url: '/packageC/hotel/HotelIndex/HotelIndex?addressData=' + JSON.stringify(this.data.mapmessageData)
      });
    } else if (this.data.tag == "home") {
      wx.reLaunch({
        url: '/packageG/index/index?addressData=' + JSON.stringify(this.data.mapmessageData)
      });
    } else if (this.data.tag == "diy") {
      let urls = wx.getStorageSync('diyurl');
      wx.reLaunch({
        url:urls
      });
    } else if (this.data.tag == "easyRefuel") {
      wx.reLaunch({
        url: '/packageD/easyRefuel/easyRefuel'
      });
    } else if(this.data.tag == 'activityHome'){
      wx.reLaunch({
        url: '/packageC/Myshaky/activityHome/activityHome?addressData=' + JSON.stringify(this.data.mapmessageData),
      });
    }	else if(this.data.tag == 'activitySearch'){
      wx.reLaunch({
        url: '/packageC/Myshaky/activityHome/activityHome?addressData=' + JSON.stringify(this.data.mapmessageData),
      });
    } else if(this.data.tag == 'activitySort'){
      wx.navigateBack({
        delta: 2,
      });
    } else if(this.data.tag == "appointment"){
      wx.reLaunch({
        url: '/packageE/appointment/appointment_index'
      });
    } else if(this.data.tag == "communityStore"){
      wx.reLaunch({
        url: '/packageH/o2o/communityStore/communityStore'
      });
    } else if(this.data.tag == "communityStoreDetails"){
      let urls = wx.getStorageSync('communityStoreDetailsUrl');
      wx.reLaunch({
        url: urls
      });
    } else if(this.data.tag == "storeConsume"){
      wx.reLaunch({
        url: '/packageH/o2o/storeConsumeIndex/storeConsumeIndex?addressData=' + JSON.stringify(this.data.mapmessageData) + '&id='+this.data.id
      });
    } else if(this.data.tag == "tagCloud"){
      wx.navigateBack({
        delta: 2
      });
    } else {
      wx.reLaunch({
        url: '/packageC/o2o/o2oHome/o2oHome?addressData=' + JSON.stringify(this.data.mapmessageData)
      });
    }
  }
});
