// const log = require('../../utils/log')
const {
  getCache,
  setCache,
  CacheKeys
} = require('../../utils/cache')
var app = getApp()
var interval;
// var inter1;
var locationTerval;
var huancheTime;
// var coundDown; //运动中不可锁车倒计时
var linshiStop; //临时停车倒计时
const util = require('../../utils/utils.js');
var interval;
//蓝牙操作方法
var BluetoothOperate = require('../../service/bluetooth.js');
//const { content } = require('../../service/dataTransition.js');
let bluetoothOperate = new BluetoothOperate();
let machineNO = "" //设备编号
let key = "" //蓝牙密钥
let operateType = '' //'open'开锁 'close'上锁 'bell'寻铃 'temporaryClose'临时锁车 'temporaryOpen'临时锁车开车
var mytime = null;

Page({
  data: {
    marqueeDistance: 520, //初始滚动距离 用到
    marqueeWidth: 560, //通知公告用到
    marqueePace: 0.6, //滚动速度
    length: '', //通知公告
    size: 26, //通知公告用到
    notice: '', //通知公告
    currentSwiper: 0,
    nowBikeStatus: '', //当前车辆的状态
    money: {
      time_money: 0,
      dispatch_money: 0,
      total_money: 0
    }, //骑行费用
    steps: 1, //开锁步骤
    parkStatus: 0, //骑行中：0，临时停车：1，点击结束用车：2
    frame: false, //车辆未开锁弹框
    code: '', //车辆编码
    bikeMessage: '', //车辆信息
    times: '0', //当前骑行时间
    estimate_money: '0', //预计金额
    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,
    stopmMinute: 30, //临时停车时间
    stopMiao: 0,
    chaButton: 0, //0 不显示 1显示
    markers: [],
    polygons: [],
    polygons1: [],
    zoom: 18,
    temporaryTime: '', //临时锁车时间
    background: false, //位置权限弹框
    location: false, //位置权限弹框
    coundDownTime: 5, //运动中不可锁车倒计时
    countTimeShow: false,
    dispatch_money: 0, //调度费
    area_id: '', //区域id
    mapHeight: 'calc(100vh - 300px)',
    isHour: false, //及时判断是否含有小时
    popShow: false,
    centerLon: '', //地图中心点经纬度
    centerLat: '', //地图中心点经纬度
    is_out_area: false, //当前用户是否超出区域
    load_num: 0, //超出区域弹窗提示弹出次数控制控制弹窗弹出次数
    isUseTK: app.globalData.isUseTK, //是否使用头盔
    ifKnowUseTK: true, //是否已点击使用头盔
  },
  onShow: function () {
    let isLearn = my.getStorageSync({
      'key': 'videoLearn'
    }).data
    let that = this
    that.setData({
      polygons1: [],
      polygons: []
    })
    my.setNavigationBar({
      title: app.globalData.title
    })
    clearInterval(locationTerval);
    if (isLearn == false || !isLearn) {
      my.navigateTo({
        url: '/pages/video/video?code=' + this.data.code,
      })
    }
    app.login().then(res => {
      that.userState()
      that.posiLoca()
      that.chushiPosiloc()
      if (that.data.code) {
        that.getBikeMessage()
      }
    })
    if (that.data.order != undefined) {
      console.log(that.data.order, 'that.data.orderthat.data.orderthat.data.order')
      that.chushi()
    }
    // that.reloadMap()
  },
  //初始化位之信息并获取区域
  chushiPosiloc: function () {
    let that = this
    my.showLoading({
      content: '正在定位...',
    })
    my.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log('经纬度为：+++++++++++2323++++++++++' + res.latitude + '++++++++' + res.longitude)
        var latitude = res.latitude
        var longitude = res.longitude
        my.hideLoading()
        that.setData({
          longitude: longitude,
          latitude: latitude,
        })
        that.home()
      },
      fail: function (err) {
        console.log(err)
        my.hideLoading()
        if (err.error == 11) {

          my.showAuthGuide({
            authType: 'LBS',
            success: (res) => {

            },
            fail: (error) => {
              my.alert({
                content: '获取位置授权失败'
              });
            },
          })
        }
        my.getSetting({
          success: function (res) {
            // console.log(res)
            var statu = res.authSetting;
            if (statu['scope.userLocation'] == false) {
              that.setData({
                background: true,
                location: true
              })
            }
          }
        })
      }
    })
  },
  onLoad: function (options) {
    let that = this

    if (app.globalData.scanCode) {

      that.setData({
        code: app.globalData.scanCode
      })
    } else if (options.order != undefined) {
      that.setData({
        order: options.order,
      })
    } else {
      that.setData({
        code: options.code
      })
    }
  },
  getNotice(id) {
    let data = {
      'area_id': id
    }
    let isCache = getCache('Notice:' + id)
    console.log(isCache, 'isCache')
    if (isCache) {
      if (isCache != null && isCache instanceof Object && !isCache.hasOwnProperty('id')) return
      this.setData({
        notice: isCache
      })
      var length = isCache.description.length * this.data.size; //计算文字的长度
      this.setData({
        length: length
      })
      if (this.data.length > this.data.marqueeWidth) {
        this.noticeRun();
      } else {
        this.setData({
          marqueeDistance: 0
        })
      }
      return
    }
    app.request("/index/an", data, "GET").then(res => {
      if (200 == res.status) {
        setCache('Notice:' + id, res.data)
        if (res.data != null && res.data instanceof Object && !res.data.hasOwnProperty('id')) return

        this.setData({
          notice: res.data
        })
        var length = res.data.description.length * this.data.size; //计算文字的长度
        this.setData({
          length: length
        })
        if (this.data.length > this.data.marqueeWidth) {
          this.noticeRun();
        } else {
          this.setData({
            marqueeDistance: 0
          })
        }
      }
    }).catch(err => {
      // console.log(err)
    })
  },
  noticeRun: function () {
    var that = this;
    clearInterval(mytime);
    mytime = setInterval(function () {
      if (-that.data.marqueeDistance < that.data.length) {
        that.setData({
          marqueeDistance: that.data.marqueeDistance - that.data.marqueePace,
        })
      } else {
        clearInterval(mytime);
        that.setData({
          marqueeDistance: that.data.marqueeWidth
        });
        that.noticeRun();
      }
    }, 10)
  },
  //广告列表
  adsList: function (id) {
    var that = this;
    var area_id = ''
    if (id != undefined) {
      area_id = id
    } else {
      area_id = 0
    }

    let isCache = getCache('ads:' + id)
    if (isCache) {
      if (isCache == '') return
      if (isCache != null && isCache instanceof Object && isCache.hasOwnProperty('header')) {
        that.setData({
          ads: isCache.header
        })
      }
      if (isCache != null && isCache instanceof Object && isCache.hasOwnProperty('mid')) {
        that.setData({
          mid: isCache.mid,
          adFrame: true
        })
      }
      return
    }

    app.request("/ads?area_id=" + area_id + "&position[]=mid&position[]=header&position[]=footer", '', "GET").then(res => {
      if (res.status == 200) {
        setCache('ads:' + id, res.data)
        if (res.data == '') return
        if (res.data.header) {
          that.setData({
            ads: res.data.header
          })
        }
        if (res.data.mid) {
          that.setData({
            mid: res.data.mid,
            adFrame: true
          })
        }
      }
    }).catch(err => {
      // console.log(err)
    })
  },
  //点击广告页
  swiper: util.throttle(function (e) {

    var type = e.currentTarget.dataset.type;
    var index = e.currentTarget.dataset.index;
    var name = e.currentTarget.dataset.name;
    var detail = e.currentTarget.dataset.detail;
    var id = e.currentTarget.dataset.id;
    if (type != 'clilk_null') {
      if (type == 'wxUrl') {
        console.log(e, 'pppp')
        my.navigateTo({
          url: '/' + detail,
        })
      } else if (type == 'phone') {

        my.makePhoneCall({
          number: detail,
        })
      } else if (type == 'toMiniProgram') {
        my.navigateToMiniProgram({
          appId: detail,
          extraData: {
            foo: 'bar'
          },
          // envVersion: 'develop',
          success(res) {
            // 打开成功
          }
        })
      } else {
        my.navigateTo({
          url: '../swiper/swiper?type=' + type + '&url=' + id + '&name=' + name + '&detail=' + detail,
        })
      }
    }
  }, 1000),
  //点击轮播图
  swiperChange: function (e) {
    if (this.data.currentSwiper == 0 && this.data.swiperCurrent > 1) { //卡死时，重置current为正确索引
      this.setData({
        currentSwiper: this.data.swiperCurrent
      });
    } else { //正常轮转时，记录正确页码索引
      this.setData({
        swiperCurrent: e.detail.current
      });
    }
  },



  //用户状态
  userState: function (area_id) {
    var that = this;

    app.request("/user/status", "GET").then(res => {
      console.log(res, 'zhuangtai')
      if (res.status == 200) {
        my.setStorageSync({
          'key': 'userState',
          data: res.data
        });
        if (res.data.is_ride_order) {
          that.setData({
            order: res.data.is_ride_order,
          })
          that.chushi()
        }
        /**
         * 未支付直接调转支付
         * mead
         */
        if (res.data.is_pay_order) {
          my.navigateTo({
            url: '/pages/pay/pay?order=' + res.data.is_pay_order,
          })
        }
      } else {
        if (this.data.bikeInfo.is_link == 0) {
          my.alert({
            title: '提示',
            content: '当前车子已下线请换辆车子骑行吧~',
            success: function (res) {
              my.reLaunch({
                url: '/pages/index/index',
              })
            }
          })
          return;
        } else if (this.data.bikeMessage.put_status == 0) {
          my.alert({
            title: '提示',
            content: '当前车子还未投放请换辆车子骑行吧~',
            success: function (res) {
              my.reLaunch({
                url: '/pages/index/index',
              })
            }
          })
          return;
        } else if (this.data.bikeMessage.is_low_battery_power == 0) {
          my.alertal({
            title: '提示',
            content: '当前车子电量过低请换辆车子骑行吧~',
            success: function (res) {
              my.reLaunch({
                url: '/pages/index/index',
              })
            }
          })
          return;
        } else if (this.data.bikeMessage.is_trouble == 1) {
          my.alert({
            title: '提示',
            content: '当前车子出现故障请换辆车子骑行吧~',
            success: function (res) {
              my.reLaunch({
                url: '/pages/index/index',
              })
            }
          })
          return;
        } else if (this.data.bikeMessage.is_riding == 1) {
          my.alert({
            title: '提示',
            content: '当前车子正在骑行请换辆车子骑行吧~',
            success: function (res) {
              my.reLaunch({
                url: '/pages/index/index',
              })
            }
          })
          return;
        }
      }
    }).catch(err => {
      console.log(err)
    })
  },
  //骑行区禁停区车辆
  home: function () {
    //请求首页接口和一些设置。
    var that = this;
    if (that.data.longitude != '' && that.data.latitude != '') {
      //116.411027
      var data = {
        'lat': that.data.latitude,
        'lng': that.data.longitude,
        'bike_no': that.data.code
      }
      app.request("/pages/home?include=setting", data, "POST").then(res => {
        console.log(res, '骑行区域')

        if (res.status == 200) {
          var data = res.data;
          that.setData({
            area_id: res.data.id
          })
          let area_id = res.data.id
          that.ban_stop(area_id)
          that.getNotice(area_id)
          that.adsList(area_id)
          console.log(data, '区域')
          my.setStorageSync({
            'key': 'home',
            data: data
          });

        }
        console.log(data, 'tdada')
        if (data) {
          my.setStorageSync({
            'key': 'setting',
            data: data.setting
          });

        } else {
          my.removeStorageSync({
            key: 'setting'
          })
        }
      }).catch(err => {
        console.log(err)
        my.alert({
          title: '提示',
          content: err.data.message,
        })
      })
    }
  },


  //停车区域
  ban_stop: function (area_id) {
    var that = this;
    let home = my.getStorageSync({
      'key': 'home'
    }).data
    that.setData({
      polygons1: that.data.polygons1.concat(home)
    })

    let isCache = getCache('BAN_STOP:' + area_id)
    if (isCache) {
      that.setData({
        markers: that.data.markers.concat(isCache.centres),
        polygons: that.data.polygons1.concat(isCache.polygons),
      })
      return
    }

    var data1 = {
      'area_id': area_id
    }
    app.request('/parking/stop-sites', data1, 'GET').then(res => {
      console.log(res)
      if (res.status == 200) {
        var data = res.data
        console.log(data)
        that.setData({
          markers: that.data.markers.concat(data.centres),
          polygons: that.data.polygons1.concat(data.polygons),
        })
      }
    })
  },
  //初始化信息
  chushi: function () {
    my.showLoading()
    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, ',---------')
      let setting = my.getStorageSync({
        'key': 'setting'
      }).data;

      if (res.status == 200) {
        my.hideLoading()
        my.setStorageSync({
          'key': 'bike_status',
          data: res.data.status
        })

        if (res.data.is_out_area == true) {
          that.setData({
            load_num: that.data.load_num + 1
          })
        }
        if (res.data.is_out_area == true && that.data.load_num == 1) {
          my.showModal({
            title: '提示',
            content: '您当前已超出骑行区域，车辆已经断电，请将车辆骑回运营区，或联系客服进行车辆回电',
            cancelText: '联系客服',
            confirmText: '我知道了',
            complete: (res) => {
              if (res.cancel) {
                my.makePhoneCall({
                  number: my.getStorageSync({
                    'key': 'home'
                  }).data.customer_service_phone,
                })
                that.setData({
                  load_num: 0
                })
              }

              if (res.confirm) {
                that.setData({
                  load_num: 0
                })
              }
            }
          })
        }
        if (res.data.start_use_bike_time <= 0) {
          that.setData({
            minute: 0
          })
        } else {
          let cha = date - res.data.start_use_bike_time
          let setting = my.getStorageSync({
            'key': 'setting'
          }).data;
          var time = parseInt(cha / 60) - setting.starting_price_time;
          var per_money = setting.per_money;
          var per_minute = setting.per_minute;
          // console.log('测试1',times)
          //页面进来时初始化金额

          // let money = parseFloat(parseFloat(time / per_minute * per_money + parseFloat(setting.starting_price)).toFixed(2));
          let money = parseInt(time / per_minute) * per_money + parseFloat(setting.starting_price)

          var hour = Math.floor(cha / 3600 % 24);
          // 分钟
          var minute = Math.floor(cha / 60 % 60);
          // let hour = parseInt(cha / 3600)
          console.log(hour, 'hour')
          console.log(minute, 'hour')
          hour = hour < 10 ? '0' + hour : hour
          minute = minute < 10 && hour > 0 ? '0' + minute : minute
          if (hour > 0) {
            // let minute=

            that.setData({
              minute: date - res.data.start_use_bike_time,
              times: hour + ":" + minute,
              estimate_money: money,
              isHour: true
            })
          } else {
            // let minute = parseInt(cha / 60)
            that.setData({
              minute: date - res.data.start_use_bike_time,
              times: minute,
              estimate_money: money,
              isHour: false
            })
          }

          // that.setData({
          //   minute: date - res.data.start_use_bike_time
          // })
        }
        that.terval()
        my.showToast({
          content: '刷新成功',
          icon: 'none'
        })
        that.setData({
          data: res.data,
          code: res.data.bike_no,
          temporaryTime: res.data.pause_bike_time
        })
        let userStatus = my.getStorageSync({
          'key': 'userState'
        }).data;
        let setting = my.getStorageSync({
          'key': 'setting'
        }).data;
        let bike_status = my.getStorageSync({
          'key': 'bike_status'
        }).data;
        console.log('pppppppp---------------------vyvyvyvy')
        //有正在骑行中的订单的订单
        if (userStatus.is_ride_order != false && bike_status == 1) {
          //骑行中
          console.log('ppppp')
          that.setData({
            steps: 3
          })
          my.setStorageSync({
            'key': 'nowBikeStatus',
            data: 0
          })
          //   that.reloadMap()
        } else if (bike_status == 0 && userStatus.is_ride_order != false) {
          // 临时停车
          that.setData({
            parkStatus: 1,
            steps: 3
          })
          my.setStorageSync({
            'key': 'nowBikeStatus',
            data: 1
          })
          //  that.reloadMap()
          that.stopDownTime()
        }
        app.request('/bike/' + that.data.code, '', 'GET').then(res => {
          console.log(res)
          200 == res.status && that.setData({
            battery_power: res.data.battery_power,
            box_no: res.data.box_no,
            bikeMessage: res.data,
          })
        })
        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);
          my.reLaunch({
            url: '../payment/payment?order=' + res.data.no
          })
        } else {
          my.reLaunch({
            url: '../index/index',
          })
        }
        // that.bikeLocation();
      }
    }).catch(err => {
      console.log(err)
    })
  },
  //获取当前位置
  posiLoca: function () {
    var that = this;
    my.showLoading({
      content: '正在定位...',
      icon: 'none'
    })
    // locationTerval = setInterval(function () {
    my.getLocation({
      type: 'gcj02',
      success: (res) => {
        var latitude = res.latitude
        var longitude = res.longitude
        my.hideLoading()
        that.setData({
          longitude: longitude,
          latitude: latitude,
        })
        if (!that.data.centerLon) {
          //第一次进入当前页面时为为中心点坐标赋值
          that.setData({
            centerLon: res.longitude,
            centerLat: res.latitude,
          })
        }
        that.home()
      },
      fail: function (err) {
        my.hideLoading()
        if (err.error == 11) {
          my.showAuthGuide({
            authType: 'LBS',
            success: (res) => {

            },
            fail: (error) => {
              my.alert({
                content: '获取位置授权失败'
              });
            },
          })
        }
        my.getSetting({
          success: function (res) {
            // console.log(res)
            var statu = res.authSetting;
            if (statu['scope.userLocation'] == false) {
              that.setData({
                background: true,
                location: true
              })
            }
          }
        })
      }
    })

  },
  //获取蓝牙秘钥
  getSecretKey(box_no) {
    //     if (!box_no) box_no = this._bikeMainId
    //     let that = this;
    //     if(box_no== my.getStorageSync('box_no')) return;
    return new Promise(function (res, rej) {
      let param = {
        box_no: box_no, //我公司是通过设备编号获取的密钥
      };
      app.request('/blu/get-key', param, 'GET').then(resp => {
        key = resp.data.key
        res(resp.data.key);
        my.setStorageSync({
          'key': 'box_no',
          data: box_no
        })
      })
    });
  },
  //行车时间计时
  terval: function () {
    var that = this;
    clearInterval(interval)
    clearInterval(huancheTime)
    var times = ''; //秒数
    var minute = Math.round(that.data.minute / 60); //分钟
    var minute1 = '0'; //分钟
    var hour = 0; //小时
    var hour1 = '0'; //小时
    var time = that.data.minute //获取当前已骑行的秒数
    var setting = my.getStorageSync({
      'key': 'setting'
    }).data;

    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
      minute++
      if (minute < 10 && hour > 0) { //如果分钟小于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,
          isHour: true
        })
      } else {
        // //else 显示 分秒
        that.setData({
          times: minute1,
          isHour: false
        })
      }
      // 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;
        // console.log('测试1',times)
        //页面进来时初始化金额

        // let money = Math.round(time / per_minute) * per_money + parseFloat(setting.starting_price)
        let money = parseInt(time / per_minute) * per_money + parseFloat(setting.starting_price)
        that.setData({
          estimate_money: money,
          onload: true
        })
      }
    }, 60000)
  },

  //获取车辆信息
  getBikeMessage: function () {
    my.showLoading()
    var that = this;
    app.request('/bike/' + that.data.code, '', 'GET').then(res => {
      console.log(res, '车辆信息--------------------')
      machineNO = res.data.box_no
      my.hideLoading()
      if (res.status == 200) {
        that.setData({
            bikeMessage: res.data,
            battery_power: res.data.battery_power,
            steps: 1
          }),
          key = res.data.key
      } else {
        setTimeout(function () {
          my.reLaunch({
            url: '/pages/index/index',
          })
        }, 2000)

      }
    })

  },
  //检测用户是否完成实名认证，是否有待支付订单违章记录等
  jiance: function () {
    let that = this
    var userStatus = my.getStorageSync({
      'key': 'userState'
    }).data;
    var setting = my.getStorageSync({
      'key': 'setting'
    }).data;
    console.log(userStatus, '旭颖')
    console.log(setting, '旭颖')
    if (userStatus.is_bind_mobile == 0) {
      my.navigateTo({
        url: '/pages/authorization/authorization',
      })
      //未实名认证
    } else
    if (userStatus.is_card_certified == 0 && setting.is_card == 1) {
      my.navigateTo({
        url: '/pages/real_name/real_name',
      })
    } //是否缴纳押金 
    else if (userStatus.is_deposit == 0 && setting.is_deposit != 0 && userStatus.is_coupon_deposit_free == false) {
      my.navigateTo({
        url: '/pages/ride_zige/ride_zige',
      })
    } else if (userStatus.is_ride_order != false) {
      my.alert({
        title: '提示',
        content: '您有一个正在骑行中的订单',
        success: function (res) {
          my.reLaunch({
            url: '/pages/index/index',
          })
        }
      })
    } else if (userStatus.is_pay_order != false && userStatus.is_pay_order != undefined) {
      my.alert({
        title: '提示',
        content: '您有一个待支付订单，请先支付',
        success: function (res) {
          my.reLaunch({
            url: '/pages/index/index',
          })
        }
      })
    } else {
      that.setData({
        steps: 2
      })
      //   this.reloadMap()
    }



  },



  reloadMap(classname = 'use-bike-bottom') {
    let query = my.createSelectorQuery();
    let th = this;
    query.select('.' + classname).boundingClientRect(function (rect) {
      if (rect != null && rect instanceof Object && rect.hasOwnProperty('height')) {
        let height = rect.height || 300;
        th.setData({
          mapHeight: 'calc(100vh - ' + (height) + 'px)'
        });
      } else {
        let height = 300;
        th.setData({
          mapHeight: 'calc(100vh - ' + height + 'px)'
        });
      }
    }).exec();
  },
  //倒计时

  //临时停车倒计时
  stopDownTime() {
    // let that = this
    // let endTime = Date.parse(new Date()); //date日期类型
    // let startTime
    // if (!that.data.temporaryTime || that.data.temporaryTime == null) {
    //   startTime = endTime
    // } else {
    //   let data1 = that.data.temporaryTime
    //   let data2 = data1.replace(/-/g, '/')
    //   let data3 = new Date(data2)
    //   startTime = data3.getTime()
    // }
    // let totleTime = 1800
    // clearInterval(linshiStop)
    // console.log(endTime, 'endTime')
    // console.log(startTime, 'startTime')
    // let date3 = endTime - startTime;
    // console.log(date3, 'date3')
    // //计算出相差天数
    // var days = Math.floor(date3 / (24 * 3600 * 1000));
    // //计算出小时数
    // var leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
    // var hours = Math.floor(leave1 / (3600 * 1000));
    // //计算相差分钟数
    // var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
    // var minutes = Math.floor(leave2 / (60 * 1000));
    // //计算相差秒数
    // var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
    // var seconds = Math.round(leave3 / 1000);
    // console.log(minutes, 'minutes')

    // let chaTime = totleTime - minutes * 60
    // console.log(chaTime, 'chaTime')
    // linshiStop = setInterval(function () {
    //   let test = 30 * 60 * 1000
    //   console.log(test, 'test')
    //   if (date3 > test) {
    //     that.setData({
    //       stopMiao: 0,
    //       stopmMinute: 0
    //     })
    //     clearInterval(linshiStop)
    //   } else if (chaTime <= 0) {
    //     that.setData({
    //       stopMiao: 0,
    //       stopmMinute: 0
    //     })
    //     clearInterval(linshiStop)
    //   } else {
    //     console.log(minutes, 'pppp')
    //     chaTime--

    //     let fen = parseInt(chaTime / 60);
    //     let miao = parseInt(chaTime % 60);
    //     that.setData({
    //       stopMiao: miao,
    //       stopmMinute: fen
    //     })
    //   }

    // }, 1000)

  },
  //开锁方法
  openBike() {
    var that = this;
    my.showLoading({
      content: '开锁中...',
      mask: true
    })
    var data = {
      bike_no: that.data.code,
      lat: that.data.latitude,
      lng: that.data.longitude,
      area_id: my.getStorageSync({
        'key': 'home'
      }).data.id,
    }
    app.request('/bike/open-lock', data, 'POST').then(res => {
      console.log(res)
      if (res.status == 200) {
        that.setData({
          steps: 3,
          order: res.data.no
        })
        that.terval()
        //蓝牙开锁
        operateType = 'open'
        bluetoothOperate.start(operateType, machineNO, key, (flag) => {
          bluetoothOperate.end((flag) => {});
        });
        my.hideLoading()
      } else {
        // that.setData({
        //   steps: 3
        // })
        // that.terval()
      }
    })


  },
  //开锁失败重试开锁
  retryOpenBike: function () {
    var that = this;
    console.log('重试开锁')
    //蓝牙重试开锁
    my.showLoading({
      content: '开锁中...',
      mask: true
    })

    let data = {
      order_no: that.data.order,
      bike_no: that.data.code
    }
    app.request('/order/retry-open-lock', data, 'GET').then(res => {
      console.log(res)
      if (res.status == 200) {
        my.hideLoading()
        if (res.data.status == 1) {
          that.setData({
            frame: false
          })
          my.hideLoading()
          operateType = 'open'
          bluetoothOperate.start(operateType, machineNO, key, (flag) => {
            bluetoothOperate.end((flag) => {});
          });
          my.showToast({
            content: '开锁成功',
            icon: 'none'
          })
        }
      }
    })
  },
  openBikeClick: function () {
    let that = this
    if (this.data.bikeMessage.is_link == 0) {
      my.alert({
        title: '提示',
        content: '当前车子已下线请换辆车子骑行吧~',
        success: function (res) {
          my.reLaunch({
            url: '/pages/index/index',
          })
        }
      })
      return;
    } else if (this.data.bikeMessage.put_status == 0) {
      my.alert({
        title: '提示',
        content: '当前车子还未投放请换辆车子骑行吧~',
        success: function (res) {
          my.reLaunch({
            url: '/pages/index/index',
          })
        }
      })
      return;
    } else if (this.data.bikeMessage.is_low_battery_power == 0) {
      my.alert({
        title: '提示',
        content: '当前车子电量过低请换辆车子骑行吧~',
        success: function (res) {
          my.reLaunch({
            url: '/pages/index/index',
          })
        }
      })
      return;
    } else if (this.data.bikeMessage.is_trouble == 1) {
      my.alert({
        title: '提示',
        content: '当前车子出现故障请换辆车子骑行吧~',
        success: function (res) {
          my.reLaunch({
            url: '/pages/index/index',
          })
        }
      })
      return;
    } else if (this.data.bikeMessage.is_riding == 1) {
      my.alert({
        title: '提示',
        content: '当前车子正在骑行请换辆车子骑行吧~',
        success: function (res) {
          my.reLaunch({
            url: '/pages/index/index',
          })
        }
      })
      return;
    }
    that.jiance()
  },
  go_setting: util.throttle(function () {
    //点击去设置位置权限
    this.setData({
      background: false,
      location: false
    })
    my.openSetting({
      success: function (res) {}
    })
  }, 1500),
  //点击已开启位置权限
  open: util.throttle(function () {
    this.setData({
      background: false,
      location: false
    })
  }, 1500),
  //寻铃
  clickBell: util.throttle(function (e) {
    //点击响铃
    var that = this;
    my.showLoading({
      content: '找车中...',
      mask: true
    })

    app.request('/order/retry-bell-lock?order_no=' + that.data.order + '&bike_no=' + that.data.code, '', 'GET').then(res => {
      console.log(res)
      if (res.status == 200) {
        //蓝牙寻铃找车
        operateType = 'bell'
        bluetoothOperate.start(operateType, machineNO, key, (flag) => {
          //flag == true 操作成功
          //flag == false 操作失败
          //end
          bluetoothOperate.end((flag) => {});
        });
        res.data.is_ok == true && my.showToast({
          content: '找车成功',
          icon: 'none',
          duration: 2000
        })
        res.data.is_ok == false && my.showToast({
          content: '找车失败请重试',
          icon: 'none',
          duration: 2000
        })
      }
    })
  }, 1000),
  //立即开锁
  konwOpenBike: util.throttle(function () {
    var that = this;
    // that.jiance()
    if (that.data.deposit == true) return;
    that.openBike()
  }, 1000),
  //临时锁车
  parkBike: function () {

    let that = this
    my.showLoading({
      content: '正在临时锁车',
    })
    var data = {
      bike_no: that.data.code,
      order_no: that.data.order,
      lat: that.data.latitude,
      lng: that.data.longitude
    }

    //代表要临时停车
    app.request('/bike/temporary-close-lock', data, 'POST').then(res => {
      console.log(res)
      if (res.status == 200) {
        my.hideLoading()
        //蓝牙临时锁车
        operateType = 'temporaryClose'
        bluetoothOperate.start(operateType, machineNO, key, (flag) => {
          //flag == true 操作成功
          //flag == false 操作失败
          //end
          bluetoothOperate.end((flag) => {});
        });
        my.showToast({
          content: '停车成功',
          icon: 'none'
        })
        that.setData({
          parkStatus: 1,
          // nowBikeStatus:1
        })
        my.setStorageSync({
          'key': 'nowBikeStatus',
          data: 1
        })
        that.stopDownTime()
        // that.getBikeMessage()
      } else if (res.status == 450) {
        my.showToast({
          content: '运动中不能关锁，请稍后重试',
          icon: 'none',
          duration: 5000,
          mask: true
        })
        my.hideLoading()
      }
    })
  },
  //结束临时锁车
  openPark: function () {
    let that = this
    my.showLoading({
      content: '解锁中',
    })
    var data = {
      bike_no: that.data.code,
      order_no: that.data.order,
      lat: that.data.latitude,
      lng: that.data.longitude
    }
    // clearInterval(inter1)

    app.request('/bike/temporary-open-lock', data, 'POST').then(res => {
      // that.inter1()
      if (res.status == 200) {
        my.hideLoading()
        // 蓝牙临时开车
        operateType = 'temporaryOpen'
        bluetoothOperate.start(operateType, machineNO, key, (flag) => {
          //flag == true 操作成功
          //flag == false 操作失败
          //end
          bluetoothOperate.end((flag) => {});
        });
        my.showToast({
          content: '开车成功',
          icon: 'none'
        })
        clearInterval(linshiStop)
        my.setStorageSync({
          'key': 'stopMiao',
          data: 0
        })
        my.setStorageSync({
          'key': 'stopmMinute',
          data: 30
        })
        that.setData({
          stopMiao: 0,
          stopmMinute: 30,
          parkStatus: 0,
          nowBikeStatus: 0
        })
        my.setStorageSync({
          'key': 'nowBikeStatus',
          data: 0
        })
      }
    })

  },
  endUseBike: function () {
    let that = this
    my.showLoading({
      content: '加载中...'
    })
    var data = {
      bike_no: that.data.code,
      order_no: that.data.order,
      lat: that.data.latitude,
      lng: that.data.longitude
    }

    app.request('/order/expect-order-money', data, 'POST').then(res => {
      console.log(res)
      if (res.status == 200) {
        my.hideLoading()
        let data = res.data.dispatch_money
        res.data.time_money = parseFloat(res.data.time_money)
        let data1 = parseFloat(data)

        if (res.data.is_app_check_helmet_status == true && res.data.helmet_status == 1) {
          my.showModal({
            title: '提示',
            content: '头盔未放好！请将头盔放置在头盔卡槽后重新结束用车',
            confirmText: '我知道了',
            showCancel: false,
            complete: (res) => {

            }
          })
        } else {
          that.setData({
            dispatch_money: data1,
            money: res.data,
            chaButton: 1,
            parkStatus: 2
          })
        }
      }
    })
  },
  //确定结束用车
  sureEndUseBike: util.throttle(function () {

    if (this.data.dispatch_money != 0) {
      this.setData({
        popShow: true
      })
    } else {
      this.huanche()
    }

  }, 1000),
  huanche() {
    //还车接口
    my.showLoading({
      content: '结算中...',
      mask: true
    })
    var that = this;
    var data = {
      bike_no: that.data.code,
      order_no: that.data.order,
      lat: that.data.latitude,
      lng: that.data.longitude
    }
    app.request('/bike/close-lock', data, 'POST').then(res => {
      console.log(res)
      my.hideLoading()
      if (res.status == 200) {
        console.log(res, '结束用车')
        clearInterval(linshiStop);
        clearInterval(interval);
        my.setStorageSync({
          'key': 'stopMiao',
          data: 0
        })
        my.setStorageSync({
          'key': 'stopmMinute',
          data: 30
        })
        my.hideNavigationBarLoading(), my.hideLoading()
        my.reLaunch({
          url: '../pay/pay?order=' + res.data.no
        })
        //蓝牙锁车操作 确定结束用车
        if (machineNO && key) {
          operateType = 'close'
          bluetoothOperate.start(operateType, machineNO, key, (flag) => {
            //flag == true 操作成功
            //flag == false 操作失败
            //end
            //订单结束关闭蓝牙
            bluetoothOperate.end((flag) => {});
          });
        }

      } else if (res.status == 450) {
        my.showToast({
          content: '运动中不能关锁，请稍后重试',
          icon: 'none',
          duration: 5000,
          mask: true
        })
      }
    }).catch(err => {
      my.showToast({
        content: '关锁失败，请重试。',
        icon: 'none',
        duration: 5000,
      })
      my.hideLoading()
    })
  },
  //开关头盔锁
  controlToukui: util.throttle(function () {
    var that = this;
    my.showLoading({
      title: '开锁中...',
      mask: true
    })
    let data = {
      order_no: that.data.order,
      bike_no: that.data.code
    }
    // if (app.globalData.req) {
    app.request('/order/retry-open-helmet-lock', data, 'GET', app.globalData.req).then(res => {
      if (res.status == 200) {
        my.hideLoading()
        if (res.data.status == 1) {
          //that.reloadMap()
          my.hideLoading()
          my.showToast({
            content: '头盔锁已开启',
            type: 'none'
          })
        }
      } else {
        // log.warn('重试开锁失败（order/retry-open-lock）' + '用户id' + '--' + wx.getStorageSync('user_ID'))
        my.hideLoading()
      }
    })
  }, 1000),
  //取消锁车
  cancelEndBike: function () {
    let that = this
    that.setData({
      chaButton: 0,
      dispatch_money: 0,
      parkStatus: my.getStorageSync({
        'key': 'nowBikeStatus'
      }).data
    })
    // that.reloadMap()
  },
  //计价规则
  chargeRule: function () {
    my.navigateTo({
      url: '/pages/charge_rule/charge_rule',
    })
  },
  //骑行须知
  bikeKnow: function () {
    my.navigateTo({
      url: '/pages/ride_rule/ride_rule',
    })
  },

  popHide() {
    //取消继续还车
    this.setData({
      popShow: false
    })
  },
  //骑行优惠券
  bikeCoupon: function () {
    my.navigateTo({
      url: '/pages/buy-card/buy-card',
    })
  },
  //客服
  keFu: function () {
    console.log('点击联系客服', my.getStorageSync({
      'key': 'home'
    }).data.customer_service_phone)
    let phone = my.getStorageSync({
      'key': 'home'
    }).data.customer_service_phone
    my.makePhoneCall({
      number: phone || '13203706613'
    })
  },
  //车辆为未开锁弹框
  //打开
  frameClose: function () {
    let that = this
    that.setData({
      frame: false
    })
    //  that.reloadMap()
  },
  //关闭弹框
  frameShow: function () {
    let that = this
    that.setData({
      frame: true
    })
    that.reloadMap('frame')
  },
  //故障上报
  guzhang: function () {
    this.setData({
      frame: false,
    })
    // this.reloadMap()
    my.navigateTo({
      url: '/pages/breakdown/breakdown',
    })
  },
  //附近还车点
  findPark: function () {
    my.navigateTo({
      url: '/pages/parking/parking',
    })
  },
  onHide: function () {
    console.log('onHide5555')
    // clearInterval(testToken
    clearInterval(mytime)
    clearInterval(interval)
    bluetoothOperate.end((flag) => {});
  },
  onUnload: function () {
    clearInterval(locationTerval)
    bluetoothOperate.end((flag) => {});
    // 停止位置跟踪
    // my.stopLocationUpdate({
    //   success: (res) => {
    //     console.log("onUnload stopLocationUpdate success", res)
    //   },
    //   fail: (err) => {
    //     console.log("onUnload stopLocationUpdate fail", err)
    //   }
    // })
  },
  //返回首页
  backHome() {
    my.reLaunch({
      url: '/pages/index/index',
    })
  },
  //关闭中间广告弹框
  closeAdframe: function () {
    this.setData({
      adFrame: false
    })
  },
  //佩戴头盔提示
  knowToukui() {
    this.setData({
      ifKnowUseTK: true
    })
  },
  //将地图将当前位置展示在屏幕中央，防止用户滑动查看停车区时频繁定位中心点
  getPosition: function () {
    this.setData({
      centerLon: this.data.longitude,
      centerLat: this.data.latitude,
    })
  },
})