var app = getApp();
var $ = require('../../js/util.js');
var QQMapWX = require('../../js/qqmap-wx-jssdk.min.js');
var wxMarkerData = [];
var submitting =0;
var oldkeyword ='';
var qqmapsdk;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    is_show:0,
    xpoint: 0,
    ypoint: 0,
    latitude: '',
    longitude: '',
    placeData: {},
    list:[],
    von:0,
    location:'',
    markers: [{
      iconPath: '/images/icon2.png',
      id: 0,
      latitude: 38.0168,
      longitude: 114.48210,
      width: 50,
      height: 50
    }],   
    controls: [{
      id: 1,
      iconPath: '/resources/location.png',
      position: {
        left: 0,
        top: 300 - 50,
        width: 50,
        height: 50
      },
      clickable: true
    }],
    sugData: '',//模糊查询
    ak:'',
    list_show:0,
    param:{
      types:1,
      car_name:'',
      mileage:0,
      status:0
    },
    //省市县三级联动
    curtitle:'当前选择',
    area:{},
    province:{},
    city: '',
    district: {},
    province_infos: {},
    city_infos: {},
    district_infos: {},
    multiIndex:[0,0,0],
    //省市县三级联动end
  }, 
  sel_von:function(e){
    var self=this;
    //console.log(e.currentTarget.dataset);
    var von = e.currentTarget.dataset.index;
    var xpoint = e.currentTarget.dataset.xpoint;
    var ypoint = e.currentTarget.dataset.ypoint;
    var location = e.currentTarget.dataset.location;
    wxMarkerData= [{
        iconPath: '/images/icon2.png',
        id: 0,
        latitude: ypoint,
        longitude: xpoint,
        width: 50,
        height: 50
      }];

    self.setData({
      markers:wxMarkerData,
      von:von,
      xpoint: xpoint,
      ypoint: ypoint,
      location: location,
    }); 
    self.changepoint(e);   
  },
  makertap: function (e) {return;
  },
  onReady: function (e) {
    // 使用 wx.createMapContext 获取 map 上下文
    this.mapCtx = wx.createMapContext('map');
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key: 'JFNBZ-ZGIKU-ESEVG-4RQGG-U5UUK-42B6B'
    });
    this.getIndex();
  },
  getIndex:function(){
    var self = this;
    
    app.HCgetlocation(function (res) {
        // console.log(res);
        wxMarkerData= [{
                iconPath: '/images/icon2.png',
                id: 0,
                latitude: res.latitude,
                longitude: res.longitude,
                width: 50,
                height: 50
              }];
        self.setData({
            markers:wxMarkerData,
            xpoint: res.longitude,
            ypoint: res.latitude,
            latitude: res.latitude,
            longitude:res.longitude,
          });
        if(!app.globalData.this_local) self.getlocationcity();
        self.setData({
          province:app.globalData.this_local.province,
          city:app.globalData.this_local.city,
          district:app.globalData.this_local.district,
        })
        self.loadCity(res.longitude, res.latitude);
    },true);
  },
  select:function(e){return;
    //console.log(e);
  },
  // 绑定input输入 
  bindKeyInput: function (e) {
    if(submitting==1)return;submitting=1;
    var self=this;
    var keyword=e.detail.value;//console.log(keyword);
    if(!keyword && oldkeyword==keyword){submitting=1;return;}oldkeyword=keyword;
    qqmapsdk.getSuggestion({
      //获取输入框值并设置keyword参数
      keyword: keyword, //用户输入的关键词，可设置固定值,如keyword:'KFC'
      region:self.city, //设置城市名，限制关键词所示的地域范围，非必填参数
      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
          });
        }
        self.setData({
            sugData: sug,
            list_show:1,
          });
          submitting=0;
      },
      fail: function(error) {submitting=0;
        console.error(error);
      },
      complete: function(res) {submitting=0;
       // console.log(res);
      }
    });
  },
  getlocationcity:function(){
    var self=this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: self.data.ypoint,
        longitude: self.data.xpoint
      },
      coord_type: 1,
      success: function (res) {
        if (res.message == 'query ok') {
           // console.log(res.result);
          app.globalData.location_n = res.result.formatted_addresses.recommend;
          app.globalData.this_local = res.result.address_component;//省，市，县
        }
      },
    });
  },
  selectthis:function(e){
    var self=this;
    var lng = e.currentTarget.dataset.xpoint;
    var lat = e.currentTarget.dataset.ypoint;
    var location = e.currentTarget.dataset.location;
    
    wxMarkerData= [{
            iconPath: '/images/icon2.png',
            id: 0,
            latitude: lat,
            longitude:lng,
            width: 50,
            height: 50
          }];
    self.setData({
        markers:wxMarkerData,
        list_show:0,
        is_show:0,
        xpoint: lng,
        ypoint: lat, 
        location:location,
      });
    var  def_data={
        id:0,
        title:location,
        location:{lat:lat,lng:lng}        
    };
    self.loadCity(lng, lat,def_data);
  },
  //视野发生变化时触发
  regionchange:function(e) {
    var that = this;    
    // console.log(e); console.log('2----');
    // 地图发生变化的时候，获取中间点，也就是用户选择的位置toFixed
    if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')) {
      that.mapCtx = wx.createMapContext("map");
      // console.log(that.mapCtx); console.log('3++++');
      that.mapCtx.getCenterLocation({
        type: 'gcj02', success: function (res) {
          // console.log(res); console.log('4----');
          
          wxMarkerData =[{ 
              iconPath: '/images/icon2.png',
              id: 0,
              latitude: res.latitude,
              longitude: res.longitude,
              width: 50,
              height: 50
            }];
          that.setData({
            xpoint: res.longitude,
            ypoint: res.latitude,  
            markers:wxMarkerData  
          });
          that.loadCity(res.longitude, res.latitude);
      } 
    })


    }
  },
  //选中某一个地址，点击完成
  submit:function(type){
    var self=this;
    app.showLoading('加载中...');
    if(!self.data.location&& !type){
      var von_info = self.data.list[0];
      var von = 0;
      var xpoint = von_info.point.x;
      var ypoint = von_info.point.y;
      var location = von_info.title;
      self.setData({
        von: von,
        xpoint: xpoint,
        ypoint: ypoint,
        location: location,
      });
    }
    app.HCnavigateTo('../near/near?xpoint=' + self.data.xpoint + '&ypoint=' + self.data.ypoint+'&location='+self.data.location);
  },
  //点击控件时触发
  controltap(e) {
    console.log('controltap');
  },
  showSearchInfo: function (data, i) {
    var that = this;
    that.setData({
      placeData: {
        title: '名称：' + data[i].title + '\n',
        address: '地址：' + data[i].address + '\n',
        telephone: '电话：' + data[i].telephone
      }
    });
  },
  changeMarkerColor: function (data, id) {
    var that = this;
    var markersTemp = [];
    for (var i = 0; i < data.length; i++) {
      if (i === id) {
        data[i].iconPath = "/images/marker_yellow.png";
      } else {
        data[i].iconPath = "./images/marker_red.png";
      }
      markersTemp[i] = data[i];
    }
    that.setData({
      markers: markersTemp
    });
  },
  loadCity: function (longitude, latitude,def_data){
    var that = this;
   // 调用接口
   qqmapsdk.search({
      keyword: that.data.city,  //搜索关键词
      location: latitude+','+longitude,  //39.980014,116.313972设置周边搜索中心点
      success: function (res) { //搜索成功后的回调      
        //console.log(res.data);
        if (res.data) {
            if(def_data)res.data.unshift(def_data)
          that.setData({
            list: res.data
          });
        }else if(def_data){
            that.setData({
                list: def_data
              });
        }
        that.getshow_local();
      },
      fail: function (res) {
        // console.log(res);
      },
      complete: function (res){
        //console.log(res);
      }
  });
  },
  getshow:function(){
    var self = this;
    self.setData({
      is_show: 1,
    })
  },
  gethide: function () {
    var self = this;
    self.setData({
      is_show: 0,
    })
  },
  init_area:function(){
    var self = this;
    var area = self.data.area;
    var province = self.data.province_infos;
    var region = new Array;
    region.push(province);//构造省级列表
    var multiIndex = self.data.multiIndex;
    var cityobj = area[province[multiIndex[0]]['i']];
    if (cityobj){//构造市级列表
      var city = new Array;
      for (var i in cityobj){
        city.push(cityobj[i]);
      }
      region.push(city);
    }
    if (area[city[multiIndex[1]]['i']]){
      var districtobj = area[city[multiIndex[1]]['i']];
      if (districtobj) {//构造区县级列表
        var district = new Array;
        for (var i in districtobj) {
          district.push(districtobj[i]);
        }
        region.push(district);
      }
    }
    self.setData({
      region: region,
    });
  },
  // 确定 调取省市县
  bindMultiPickerChange:function(event){
    var self = this;
    var value = event.detail.value;
    var region = self.data.region;
    //赋值
    var province = region[0][value[0]];
    var city = region[1][value[1]];
    var district = region[2][value[2]];
    self.setData({
      province: province.n,
      city: city.n,
      district: district.n,
      curtitle:'',
    });
    self.geocoding();
  },
  geocoding:function(){
    var self = this;
    var action = 'c=Index&a=geocoding';
    var param = $.ObjectToStr(self.data.param)+'&city='+self.data.city+'&address='+self.data.city;
    // console.log(param);
    app.showLoading('加载中...');
    app.ajaxRequest(action, 'GET', param, function (ret) {
      if(ret.result.length != 0){
        self.loadCity(ret.result.location.lng,ret.result.location.lat);
        self.setData({
          xpoint:ret.result.location.lng,
          ypoint:ret.result.location.lat,
        });
      }else{
        app.HCerror('提示', '定位失败', false);
      }
      
    },true);
  },
  bindMultiPickerColumnChange: function (event) {
    var self = this;
    var column = event.detail.column;
    var value = event.detail.value;
    var multiIndex = self.data.multiIndex;
    multiIndex[column] = value;
    self.setData({
      multiIndex: multiIndex,
    });
    self.init_area();
  },
  getshow_local:function(){
    var self = this;
    var action = 'c=Index&a=address';
    var param = $.ObjectToStr(self.data.param);
    app.showLoading('加载中...');
    app.ajaxRequest(action, 'GET', param, function (ret) {
      if(ret && ret.status==1){
        if (ret.data && ret.data.region) {
          self.setData({
            province_infos: ret.data.region,
            area: ret.data.area,
          });
          self.init_area();
        }
      }
    },true);
  },
  changeaddress:function(event){
    var data = event.currentTarget.dataset.id;
    var param = new Object;
    param.xpoint = data.xpoint;
    param.ypoint = data.ypoint;
    param.address = data.address;
    this.doneshopid(param);
  },
  changepoint: function (event) {
    var data = event.currentTarget.dataset;
    var param = new Object;
    param.xpoint = data.xpoint;
    param.ypoint = data.ypoint;
    param.address = data.location;
    this.doneshopid(param);
  },
  doneshopid:function(data){
    app.showLoading('加载中...');
    var self=this;
    var action = 'c=Login&a=setshopid';
    app.ajaxRequest(action, 'POST', data, function (ret) {
      // console.log(ret);
      if (ret.bind_shop_id) {
        app.globalData.location_n = data.address;
        app.globalData.HCshopid = ret.bind_shop_id;
        app.globalData.send = ret.send;
      }else{
        app.globalData.HCshopid = 0;
      }
      console.log(app.globalData.location_n);
      // app.HCtoast('操作成功！');
      setTimeout(function () {
        app.HCchangeData(1, data, function (ret) {
          app.HCnavigateBack();
        })
      }, 2000);
    }, true);
  },
})