// pages/sign/index.js
var utils = require("../../utils/util.js");
var myRequest = require("../../utils/api.js");
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js')

var intervalTime
Page({

  /**
   * 页面的初始数据
   */
  data: {
    time:'',
    latitude: '',
    longitude: '',

    deviceLat:'',
    deviceLon:'',
    mylat:'',
    mylon:'',
    radius:50,
    address:'',
    isSing:false,
    mapCtx:'',
    circle:[],
    orderId:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onReady: function (e) {
    
  
  },
  setCenter(){
      var that = this
     this.mapCtx.moveToLocation()
  
  },
  onLoad(options) {

    let info = JSON.parse(options.item)
    console.log(info)
    let device = info.device
    this.setData({
      deviceLat:device.latitude,//device.latitude,31.26249
      deviceLon:device.longitude,//device.longitude,120.63212
      orderId:info.orderId,
      address:device.name
    })
    this.mapCtx = wx.createMapContext('myMap')
    this.getCircle();
    this.getTime();
    this.setCenter()
  },
  singOut(){
    console.log('签到')
  },
  getDistancesValue(lat1, lng1, lat2, lng2) {
    let EARTH_RADIUS = 6378.137;// 地球半径
    let radLat1 = lat1 * Math.PI / 180.0; //lat1 * Math.PI / 180.0=>弧度计算
    let radLat2 = lat2 * Math.PI / 180.0;
    let a = radLat1 - radLat2;
    let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    let 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 { m: s * 1000, km: Number(s.toFixed(2)) }
  },

  getCircle(){
    this.setData({
      circle:[{
        latitude:this.data.deviceLat,
        longitude: this.data.deviceLon,
        radius:this.data.radius,
        color:'#1772F6',
        fillColor:'#1772F68F'
      }]
    })
  },
  getDistance(){
    let that = this;
    wx.getLocation({//调用API得到经纬度
      type: 'gcj02',
      isHighAccuracy: true,
      success: function (res) {
        const distance  =utils.getDistances(res.latitude,res.longitude,that.data.deviceLat,that.data.deviceLon)
        
        that.setData({
          isSing:distance.m<that.data.radius,
          mylat:res.latitude,
          mylon:res.longitude
        })
  
      }
 
    })



  },
  async startSign(){
    if(!this.data.isSing){
      wx.showToast({
        title: '范围之外',
        icon:'none'
      })
      return 
    }
    let orderId = this.data.orderId
    let address = await this.mapwxAddress(this.data.mylat,this.data.mylon)
    console.log(address)
 
  
    myRequest.myRequest('deviceRepairOrder/supporter/check/'+this.data.orderId,{
      location:address
    },'post').then(res=>{
      wx.showToast({
        title: '签到成功',
        icon:'none'
      })
      setTimeout(()=>{
        clearInterval(intervalTime)
        wx.navigateBack({
          delta: 1,
          success: function (e) {
            var page = getCurrentPages().pop();
            if (page == undefined || page == null) return;
            page.onLoad({id:orderId}); // 刷新数据
          }
        });

      },1000)

    })
  },
  //逆向地址接卸
  mapwxAddress(latitude,longitude){
 return new Promise((reslove,reject)=>{
      //地址解析
      var demo = new QQMapWX({
        key: 'D6LBZ-45P3N-3V2FH-S2YBM-6ISH3-7LF7W'
      });
      demo.reverseGeocoder({//地址解析
        location: {
          latitude: latitude,
          longitude: longitude 
        },
        success: function (res) {
   
          reslove( res.result.address)
         
        },
        fail: function (res) {
          reslove('地址解析失效')
        },
        complete: function (res) {
          console.log(res);
        }
      });

 })
  
  },
  setLoaction(){
debugger
    this.setData({
      longitude:this.data.deviceLon,
      latitude:this.data.deviceLat
    })
  },
  getTime() {
    var that = this;
     intervalTime = setInterval(function() {
      var time = utils.getTime();
      that.getDistance()
      that.setData({
        time: time
      })
   }, 1000);

  },


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

  },

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

  },

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

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(intervalTime)
  },

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

  },

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

  },

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

  }
})