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: '',
    bolear: 1,
    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: '',
    parke: true,
    timeout: 15,
    retry: '',
    bikePosition: false,
    battery_power: '',
    huanche_timeout: 0,
    img: app.globalData.imgUrl,
    title:app.globalData.title
  },
  onLoad: function (options) {
    var that = this;
    wx.showLoading({
      title: '加载中...',
      mask: true
    })

    wx.getSystemInfo({
      success: function (res) {
        // 获取可使用窗口宽度
        let clientHeight = res.windowHeight;
        // 获取可使用窗口高度
        let clientWidth = res.windowWidth;
        // 算出比例
        let ratio = 750 / clientWidth;
        // 算出高度(单位rpx)
        let height = clientHeight * ratio;
        // 设置高度
        console.log(height)
        that.setData({
          windowHeight: height
        });
      }
    })
    console.log(app.globalData.screenHeight)
    that.setData({
      screenHeight: app.globalData.screenHeight
    })
    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()
    if (options.time == 'true') {
      that.setData({
        retry: true
      })
      that.inter1()
    }
  },
  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 setting = wx.getStorageSync('setting');
    var no_money_time = time;
    var close_bike_time = setting.close_bike_time;
    if (no_money_time < close_bike_time) {
      that.setData({
        huanche_timeout: close_bike_time - 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(time / 60);
      times = time;
    }
    interval = setInterval(function () {
      //定时器 秒数一秒加1
      times++
      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)
        minute1 = minute - hour * 60;
        if (hour < 10) {
          hour1 = '0' + hour;
        } else {
          hour1 = hour
        }
      }
      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
        })
      }
      // that.setData({ times: minute1 + ':' + times})
      //计算钱   分钟除以5*5   判断秒数>30  minute = minute+1
      //不满12分钟按12分钟算   并且大于30秒   
      var per_money = setting.per_money;
      var per_minute = setting.per_minute;
      // console.log(minute)
      // console.log(minute1)
      if (setting.starting_price_time > minute) {
        that.setData({
          estimate_money: setting.starting_price
        })
      } else {
        //起步价+（分钟数-起步时长）/ 一块钱可骑多少分钟 * 钱数
        var time = minute - setting.starting_price_time;
        let money = Math.ceil(time / per_minute * Number(per_money)) + Number(setting.starting_price) + '.00';
        if (money == NaN) {
          money = Math.ceil(time / per_minute * Number(per_money)) + Number(setting.starting_price) + '.00';
        }
        if (minute > 0) {
          that.setData({
            estimate_money: money
          })
        } else {
          if (times >= 30) {
            that.setData({
              estimate_money: Math.ceil(1 / per_minute * Number(per_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),
  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)
  },
  bikePosition: function () {
    //每5秒刷新当前位置
    var that = this;
    bikelocationTerval = setInterval(function () {
      that.bikeLocation()
    }, 30000)
  },
  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.code, CMD.bell)
    app.request('/order/retry-bell-lock?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),
  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)
    })
  },
  chushi: function () {
    var that = this;
    var date = Date.parse(new Date()) / 1000;
    app.request('/pages/ride-order?no=' + that.data.order, '', 'GET').then(res => {
      console.log(res)
      if (res.statusCode == 200) {
        // var start_time = 1578446930
        if (date - res.data.start_use_bike_time <= 0) {
          that.setData({
            minute: 0
          })
        } else {
          that.setData({
            minute: date - res.data.start_use_bike_time
          })
        }
        // if (date - start_time <= 0) {
        //   that.setData({ minute: 0 })
        // } else {
        //   that.setData({ minute: date - start_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 == 0) {
          that.setData({
            bolear: 0
          })
        } else if (res.data.status == 1) {
          that.setData({
            bolear: 1
          })
        } else if (res.data.status == 2) {
          clearInterval(interval),
            clearInterval(interval1);
          clearInterval(locationTerval);
          clearInterval(bikelocationTerval);
          wx.reLaunch({
            url: '../payment/payment?order=' + res.data.no
          })
        } else if (res.data.status == 3) {
          wx.reLaunch({
            url: '../index/index',
          })
        } else if (res.data.status == 4) {
          wx.reLaunch({
            url: '../index/index',
          })
        }
        that.bikeLocation();
      }
    }).catch(err => {
      console.log(err)
    })
  },
  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
                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()
  },
  closeLock: function (data) {
    var that = this;
    bluM.connectDeivece(that.data.box_no, CMD.lock)
    app.request('/bike/close-lock', data, 'POST').then(res => {
      console.log(res)
      if (res.statusCode == 200) {
        clearInterval(locationTerval);
        clearInterval(interval);
        clearInterval(bikelocationTerval);
        clearInterval(interval1);
        wx.reLaunch({
          url: '../payment/payment?order=' + res.data.no
        })
      } else if (res.statusCode == 450) {
        that.coundDown()
      }
    }).catch(err => {
      console.log(err)
    })
  },
  end: util.throttle(function () {
    //点击结束骑行 先调接口看看是不是在停车区域 如果是清除定时器 如果不是询问用户用户点继续停车 清除定时器  如果点取消 无反应
    // wx.showNavigationBarLoading()
    wx.showLoading({
      title: '结算中...',
      mask: true
    })
    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
        }
        app.request('/bike/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=order',
              })
            } else {
              bluM.connectDeivece(that.data.box_no, CMD.lock)
              app.request('/bike/close-lock', 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
                  })
                } 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),
  openBike: function () {
    //点击开锁失败重试
    var that = this;
    clearInterval(inter1)
    that.setData({
      timeout: 15
    })
    wx.getBluetoothAdapterState({
      success(res) {
        console.log(res)
        if (res.available == false) {
          wx.showModal({
            title: '提示',
            content: '手动开启蓝牙使用蓝牙开锁',
            showCancel: false
          })
          that.inter1()
        } else {
          wx.showLoading({
            title: '开锁中...',
            mask: true
          })
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              console.log(res)
              bluM.connectDeivece(that.data.box_no, CMD.unlock)
              app.request('/order/retry-open-lock?order_no=' + that.data.order + '&bike_no=' + that.data.code, '', 'GET').then(res => {
                console.log(res)
                that.inter1()
                if (res.statusCode == 200) {
                  wx.hideLoading()
                  if (res.data.status == 1) {
                    wx.showToast({
                      title: '开锁成功',
                      icon: 'none'
                    })
                  }
                }
              })
            },
          })
        }
      }
    })
  },
  inter1: function () {
    //点击临时开车 临时停车后按钮的定时器
    var that = this;
    var timeout1 = that.data.timeout;
    inter1 = setInterval(function () {
      timeout1--
      that.setData({
        timeout: timeout1
      })
      if (timeout1 <= 0) {
        clearInterval(inter1)
        that.setData({
          parke: true,
          timeout: 15,
          retry: false
        })
      } else {
        retry: true
      }
    }, 1000)
  },
  retry1: function () {
    var that = this;
    that.setData({
      timeout: 15
    })
    clearInterval(inter1)
    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.bike_no, CMD.unlock)
        app.request('/bike/temporary-open-lock', data, 'POST').then(res => {
          that.inter1()
          if (res.statusCode == 200) {
            wx.showToast({
              title: '开车成功',
              icon: 'none'
            })
            that.setData({
              bolear: 1
            })
          }
        })
      }
    })
  },
  retry2: function () {
    var that = this;
    that.setData({
      timeout: 15
    })
    clearInterval(inter1)
    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('/bike/temporary-close-lock', data, 'POST').then(res => {
          console.log(res)
          that.inter1()
          if (res.statusCode == 200) {
            wx.showToast({
              title: '停车成功',
              icon: 'none'
            })
            that.setData({
              bolear: 0
            })
          } else if (res.statusCode == 450) {
            that.coundDown()
          }
        })
      }
    })
  },
  parking: 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
        }
        clearInterval(inter1)
        that.setData({
          timeout: 15
        })
        if (that.data.bolear == 1) {
          //代表要临时停车
          app.request('/bike/temporary-close-lock', data, 'POST').then(res => {
            console.log(res)
            that.inter1()
            if (res.statusCode == 200) {
              wx.showToast({
                title: '停车成功',
                icon: 'none'
              })
              bluM.connectDeivece(that.data.box_no, CMD.lock)
              that.setData({
                bolear: 0,
                parke: false
              })
            } else if (res.statusCode == 450) {
              that.coundDown()
            }
          })
        }
        if (that.data.bolear == 0) {
          //代表要临时开车
          app.request('/bike/temporary-open-lock', data, 'POST').then(res => {
            that.inter1()
            if (res.statusCode == 200) {
              wx.showToast({
                title: '开车成功',
                icon: 'none'
              })
              bluM.connectDeivece(that.data.box_no, CMD.unlock)
              that.setData({
                bolear: 1,
                parke: false
              })
            }
          })
        }
      }
    })
  },
  onHide: function () {
    clearInterval(locationTerval);
  },
  onUnload: function () {
    clearInterval(locationTerval)
    clearInterval(bikelocationTerval)
    clearTimeout(settime)
    // clearInterval(huancheTime)
  },
  onPullDownRefresh: function () {

  },
  onReachBottom: function () {

  },
  onShareAppMessage: function () {

  }
})