var app = getApp()
var interval;
var interval1;
var locationTerval;
var bikelocationTerval;
var settime;
var timeing;
var inter1;
var huancheTime;
import {
  BluetoothManager,
  BtErrorCode,
  CMD
} from '../../service/BluWkm'

const bluM = new BluetoothManager;
const util = require('../../utils/utils.js')
Page({
  data: {
    windowHeight: '',
    code: '',
    longitude: '',
    latitude: '',
    order: '',
    markers: [], //显示单车、停车的P图标
    polygons: [], //区域
    id: '', //区域的ID
    polygons1: [], //可骑行区域 先用这个变量代表 
    controls: [], //地图上当前定位的箭头
    height: '',
    times: '00:00', //当前骑行时间
    detail: '', //车辆信息详情
    estimate_money: '0.00', //预计金额
    minute: '', //骑行总时间秒
    data: [],
    box_no: '',
    screenHeight: '',
    change: false,
    timing: 5,
    isShow: false,
    minute1: '',
    bikePosition: false,
    battery_power: '',
    huanche_timeout: 0,
    img: app.globalData.imgUrl
  },
  onLoad: function (options) {
    var that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    console.log(app.globalData.screenHeight)
    that.setData({
      screenHeight: app.globalData.screenHeight
    })
    wx.getSystemInfo({
      success: function (res) {
        let clientHeight = res.windowHeight;
        let clientWidth = res.windowWidth;
        let ratio = 750 / clientWidth;
        let height = clientHeight * ratio;
        that.setData({
          windowHeight: height
        });
      }
    })
    console.log(options)
    if (options.order != undefined) {
      that.setData({
        order: options.order
      })
    }
    if (options.box_no != undefined) {
      that.setData({
        box_no: options.box_no
      })
    }
    wx.hideLoading();
    that.posiLoca();
    that.bikePosition();
  },
  terval: function () {
    var that = this;
    clearInterval(interval)
    clearInterval(huancheTime)
    var times = ''; //秒数
    var minute = 0; //分钟
    var minute1 = '0'; //分钟
    var hour = 0; //小时
    var hour1 = '0'; //小时
    var time = that.data.minute //获取当前已骑行的秒数  
    console.log(time)
    var no_money_time = time;
    if (no_money_time < 60) {
      that.setData({
        huanche_timeout: 60 - no_money_time
      })
      huancheTime = setInterval(() => {
        var no_money_time1 = that.data.huanche_timeout - 1
        that.setData({
          huanche_timeout: no_money_time1
        })
        if (no_money_time1 == 0) {
          that.setData({
            huanche_timeout: -1
          })
          clearInterval(huancheTime)
        }
      }, 1000);
    } else {
      that.setData({
        huanche_timeout: -1
      })
    }
    if (time > 60) { //秒数大于60 分钟= 秒数/60  秒数=  -1*60  40
      minute = parseInt(time / 60);
      times = time - minute * 60;
      //minute代表分钟  times 代表秒数
    } else {
      minute = parseInt(that.data.minute / 60);
      times = time;
    }
    interval = setInterval(function () {
      //定时器 秒数一秒加1
      times++
      time++
      if (times > 59) { //如果秒数大于59 让分钟加1 秒数归0
        minute = minute + 1
        times = 0
      }
      if (times < 10) { //如果秒数小于10 加一个0
        times = '0' + times
      }
      if (minute < 10) { //如果分钟小于10 加一个0
        minute1 = '0' + minute
      } else {
        minute1 = minute
      }
      if (minute > 59) {
        //分钟大于59 让小时+1
        hour = parseInt(minute / 60)
        if (hour < 10) {
          hour1 = '0' + hour;
        } else {
          hour1 = hour;
        }
        minute1 = minute - hour * 60;
      }
      if (minute1 < 10 && hour > 0) { //如果分钟小于10 加一个0
        minute1 = '0' + minute1
      } else {
        minute1 = minute1
      }
      if (hour > 0) {
        //如果小时大于0 显示 时分
        that.setData({
          times: hour1 + ':' + minute1 + ':' + times
        })
      } else {
        //else 显示 分秒
        that.setData({
          times: minute1 + ':' + times
        })
      }
      var hours = Number(wx.getStorageSync('setting').day_rent_hours), //默认一天可以骑几个小时不收费
        money = Number(wx.getStorageSync('setting').per_hours_day_rent_timeout_money), //超出一小时多少钱
        capping_money = Number(wx.getStorageSync('setting').day_rent_capping_money), //24小时之内封顶多少钱
        rent_money = Number(wx.getStorageSync('setting').day_rent_money); //一天初始钱
      var hour2 = Math.ceil(time / 60 / 60)
      var day = Math.floor(hour2 / 24);
      //求出当前天数
      var day_money = day * capping_money; //算出封顶钱*天数
      var hour_s = (hour2 % 24) - hours; //求余 并减去免费骑行时间
      if (hour_s < 0) { //如果余的时间<0那么就让他为0
        hour_s = 0
      }
      var estimate_money1 = rent_money + hour_s * money; //计算初始钱+超出小时*一小时多少钱
      if (estimate_money1 <= capping_money) { //如果当前钱数<=封顶钱  那么 赋值的钱就是 封顶钱*天+当前钱
        that.setData({
          estimate_money: day_money + estimate_money1 + '.00'
        })
      } else { //如果大于封顶钱 
        that.setData({
          estimate_money: capping_money + day_money + '.00'
        })
      }
    }, 1000)
  },
  onReady: function () {
    var that = this;
    // wx.getSystemInfo({
    //   success({
    //     windowHeight
    //   }) {
    //     console.log(windowHeight)
    //     that.setData({
    //       windowHeight
    //     });
    //   }
    // });
    this.dialog = this.selectComponent("#dialog");
  },
  help: util.throttle(function () {
    //点击帮助
    wx.navigateTo({
      url: '../personal/help/help',
    })
  }, 1000),
  bikePosition: function () {
    //每5秒刷新当前位置
    var that = this;
    bikelocationTerval = setInterval(function () {
      that.bikeLocation()
    }, 30000)
  },
  bikeLocation: function () {
    var that = this;
    var data = {
      bike_no: that.data.code
    }
    app.request('/order/orderBikePosition', data, 'GET').then(res => {
      if (res.statusCode == 200) {
        var mark = that.data.markers;
        if (that.data.bikePosition) {
          mark.pop()
        }
        that.setData({
          markers: mark,
          battery_power: res.data.battery_power
        })
        var array = {}
        array.iconPath = 'http://resource.bike.hanyiyun.com/weapp/dianche.png';
        array.width = 28;
        array.height = 28;
        array.zIndex = 1111;
        array.id = 12345;
        array.latitude = res.data.latitude;
        array.longitude = res.data.longitude;
        that.setData({
          markers: that.data.markers.concat(array)
        })
        that.setData({
          bikePosition: true
        })
      }
    }).catch(err => {
      console.log(err)
    })
  },
  posiLoca: function () {
    //每5秒刷新当前位置
    var that = this;
    locationTerval = setInterval(function () {
      wx.getLocation({
        type: 'gcj02',
        success: (res) => {
          console.log('经纬度为：+++++++++++++++++++++' + res.latitude + '++++++++' + res.longitude)
          var latitude = res.latitude
          var longitude = res.longitude
          that.setData({
            longitude: longitude,
            latitude: latitude
          })
        },
        fail: function (err) {
          console.log(err)
        }
      })
    }, 5000)
  },
  posi: util.throttle(function () {
    //点击定位  
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log('经纬度为：+++++++++++++++++++++' + res.latitude + '++++++++' + res.longitude)
        var latitude = res.latitude
        var longitude = res.longitude
        that.setData({
          longitude: longitude,
          latitude: latitude
        })
      }
    })
  }, 1000),
  search: util.throttle(function () {
    wx.navigateTo({
      url: '../navigation/navigation',
    })
  }, 1000),
  seek: util.throttle(function () {
    //点击响铃
    var that = this;
    wx.showLoading({
      title: '找车中...',
      mask: true
    })
    bluM.connectDeivece(that.data.detail.box_no, CMD.bell)
    app.request('/rent/retry-bell?order_no=' + that.data.order + '&bike_no=' + that.data.code, '', 'GET').then(res => {
      console.log(res)
      if (res.statusCode == 200) {
        res.data.is_ok == true && wx.showToast({
          title: '找车成功',
          icon: 'none',
          duration: 2000
        })
        res.data.is_ok == false && wx.showToast({
          title: '找车失败请重试',
          icon: 'none',
          duration: 2000
        })
      }
    })
  }, 1000),
  refresh: util.throttle(function () {
    //点击刷新
    var that = this;
    var data = Date.parse(new Date()) / 1000;
    that.chushi()
    that.terval()
  }, 1000),
  chushi: function () {
    var that = this;
    var date = Date.parse(new Date()) / 1000;
    app.request('/rent/use-order?no=' + that.data.order, '', 'GET').then(res => {
      console.log(res)
      if (res.statusCode == 200) {
        if (date - res.data.start_use_bike_time <= 0) {
          that.setData({
            minute: 0
          })
        } else {
          that.setData({
            minute: date - res.data.start_use_bike_time
          })
        }
        that.terval()
        wx.showToast({
          title: '刷新成功',
          icon: 'none'
        })
        that.setData({
          data: res.data,
          code: res.data.bike_no,
        })
        app.request('/bike/' + that.data.code, '', 'GET').then(res => {
          console.log(res)
          200 == res.statusCode && that.setData({
            battery_power: res.data.battery_power,
            box_no: res.data.box_no
          })
        })
        if (res.data.status == 2) {
          wx.reLaunch({
            url: '../payment/payment?order=' + res.data.no + '&rent=rent'
          });
          clearInterval(interval);
          clearInterval(interval1);
          clearInterval(locationTerval);
          clearInterval(bikelocationTerval);
        }
        that.bikeLocation();
      }
    }).catch(err => {
      console.log(err)
    })
  },
  close_bike: util.throttle(function () {
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log('经纬度为：+++++++++++++++++++++' + res.latitude + '++++++++' + res.longitude)
        var latitude = res.latitude
        var longitude = res.longitude
        var data = {
          bike_no: that.data.code,
          order_no: that.data.order,
          lat: latitude,
          lng: longitude
        }
        bluM.connectDeivece(that.data.box_no, CMD.lock)
        app.request('/rent/close-bike', data, 'POST').then(res => {
          if (res.statusCode == 200) {
            wx.showToast({
              title: '锁车成功',
              icon: 'none'
            })
            that.setData({
              bolear: 1
            })
          }
        })
      }
    })
  }, 1000),
  open_bike: util.throttle(function () {
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log('经纬度为：+++++++++++++++++++++' + res.latitude + '++++++++' + res.longitude)
        var latitude = res.latitude
        var longitude = res.longitude
        var data = {
          bike_no: that.data.code,
          order_no: that.data.order,
          lat: latitude,
          lng: longitude
        }
        bluM.connectDeivece(that.data.box_no, CMD.unlock)
        app.request('/rent/open-bike', data, 'POST').then(res => {
          if (res.statusCode == 200) {
            wx.showToast({
              title: '开车成功',
              icon: 'none'
            })
            that.setData({
              bolear: 1
            })
          }
        })
      }
    })
  }, 1000),
  location: function () {
    //获取当前经纬度 给地图赋值
    wx.showNavigationBarLoading()
    var that = this
    that.setData({
      polygons: []
    })
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log('经纬度为：+++++++++++++++++++++' + res.latitude + '++++++++' + res.longitude)
        var latitude = res.latitude
        var longitude = res.longitude
        that.setData({
          longitude: longitude,
          latitude: latitude
        })
        var data = {
          'lat': latitude,
          'lng': longitude
        }
        app.request('/pages/home?include=setting', data, 'POST').then(res => {
          if (res.statusCode == 200) {
            var data = res.data;
            var points = data.area_fence;
            data.points = points;
            data.area_fence = []
            data.strokeWidth = 4;
            data.strokeColor = '#0000FF';
            data.zIndex = 1111;
            console.log(data)
            that.setData({
              polygons: that.data.polygons.concat(data),
              id: data.id,
              polygons1: that.data.polygons.concat(data)
            })
            var data1 = {
              'area_id': data.id
            }
            app.request('/parking/stop-sites', data1, 'GET').then(res => {
              // console.log(res)
              if (res.statusCode == 200) {
                var data = res.data
                if (data.length == 0 || data == undefined) {
                  return;
                }
                that.setData({
                  polygons: that.data.polygons1.concat(data.polygons),
                  markers: data.centres
                })
              }
            })
          }
        }).catch(err => {
          console.log(err)
        })
      }
    })
  },
  coundDown: function () {
    var that = this;
    that.setData({
      isShow: true
    })
    timeing = setInterval(function () {
      var timeing1 = that.data.timing;
      timeing1--
      that.setData({
        timing: timeing1
      })
      if (timeing1 <= 0) {
        that.setData({
          timing: 5,
          isShow: false
        })
        clearInterval(timeing)
      }
    }, 1000)
  },
  bindregionchange: function (e) {
    //实现大头针移动选点
    var that = this;
    if (e.type == 'begin') {
      clearTimeout(settime)
      clearInterval(locationTerval);
    }
    if (e.type == 'end') {
      settime = setTimeout(function () {
        that.posiLoca()
      }, 3000)
    }
  },
  onShow: function () {
    this.location();
    this.chushi();
    this.posi();
  },

  end: util.throttle(function () {
    var that = this;
    wx.showLoading({
      title: '结算中...',
      mask: true
    })
    wx.getLocation({
      type: 'gcj02',
      success: (resa) => {
        console.log('经纬度为：+++++++++++++++++++++' + resa.latitude + '++++++++' + resa.longitude)
        var latitude = resa.latitude
        var longitude = resa.longitude
        var data = {
          bike_no: that.data.code,
          order_no: that.data.order,
          lat: latitude,
          lng: longitude
        }
        app.request('/rent/check-is-riding-area', data, 'POST').then(res => {
          console.log(res)
          if (res.statusCode == 200) {
            // clearInterval(interval);
            // clearInterval(interval1);
            clearInterval(locationTerval);
            clearInterval(bikelocationTerval);
            wx.hideNavigationBarLoading(), wx.hideLoading()
            if (res.data.is_close_order == false) {
              // that.closeLock(data)
              wx.navigateTo({
                url: '/pages/confirm_order/confirm_order?bike_no=' + that.data.code + '&order_no=' + that.data.order + '&lat=' + latitude + '&lng=' + longitude + '&order=rent',
              })
            } else {
              bluM.connectDeivece(that.data.box_no, CMD.lock)
              app.request('/rent/close-order', data, 'POST').then(res => {
                console.log(res)
                if (res.statusCode == 200) {
                  clearInterval(interval);
                  clearInterval(interval1);
                  clearInterval(locationTerval);
                  clearInterval(bikelocationTerval);
                  wx.hideLoading()
                  wx.reLaunch({
                    url: '../payment/payment?order=' + res.data.no + '&rent=rent'
                  })
                } else if (res.statusCode == 450) {
                  that.coundDown()
                }
                // wx.hideNavigationBarLoading()
              }).catch(err => {
                console.log(err)
              })
            }
          } else if (res.statusCode == 450) {
            that.coundDown()
            wx.hideLoading()
          }
        }).catch(err => {
          console.log(err)
        })
      }
    })
  }, 1000),
  onHide: function () {

  },
  onUnload: function () {
    clearInterval(locationTerval)
    clearTimeout(settime)
    clearInterval(bikelocationTerval)
  },
  onPullDownRefresh: function () {

  },
  onReachBottom: function () {

  },
  onShareAppMessage: function () {

  }
})