//获取应用实例
const app = getApp();
var token = wx.getStorageSync('token');
const util = require('../../utils/utils.js');
var mytime = null;
import {
  BluetoothManager,
  CMD
} from '../../service/BluWkm';
const bluM = new BluetoothManager;
Page({
  data: {
    markers: [], //显示单车、停车的P
    polygons: [], //区域
    longitude: '113.488478', //113.786111
    latitude: '34.140701', //34.78304
    height1: '', //兼容自定义导航栏的高度
    show: false, //车子详情的布尔值 
    id: '', //停车区域的ID
    stopP: false, //判断是否显示停车区域
    polygons1: [], //可骑行区域 先用这个变量代表
    controls: [], //地图上当前定位的箭头                     
    background: false, //弹窗的背景颜色 
    realname: false, //当前是否已经实名
    deposit: false, //当前是否交押金
    userStatus: '', //用户的一些状态 是否交押金等   0                                                                                           
    scanfail: false, //扫码失败弹窗
    is_pay_order: '', //检测当前是否有订单未支付
    code: '', //点击立即用车 把编号赋值给code
    over: false, //关闭图标
    over1: false, //扫码失败关闭图标
    location: '', //是否有位置权限
    screenHeight: '', //屏幕可视高度
    bluetooth: false, //是否开启蓝牙 false开始 true未开启
    box_no: '', //中控编号
    abnormal: '', //提示账号异常
    ads: [],
    mid: [],
    currentSwiper: 0,
    center_currentSwiper: 0,
    bike_no: undefined,
    stopShow: false,
    stop_info: [],
    notice: [], //公告内容
    animationData: {},
    tabbar_index: 0,
    zoom: 18,
    versions: false, //版本过低弹窗
    chooseSize: false,
    animationData1: {},
    arrowDown: '',
    stop_type: '',
    marqueePace: 0.6, //滚动速度
    marqueeDistance: 520, //初始滚动距离 用到
    size: 26, //用到
    marqueeWidth: 520, //用到
    length: '',
    swiperCurrent: 0,
    midbolear: '',
    per_money: '',
    img: app.globalData.imgUrl,
    new_user_coupons: []
  },
  chooseSezi: function (e) {
    //底部广告动画效果
    // 用that取代this，防止不必要的情况发生
    var that = this;
    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration: 600,
      // 定义动画效果，当前是匀速
      timingFunction: 'linear'
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    // 先在y轴偏移，然后用step()完成一个动画
    animation.translateY(300).step()
    // 用setData改变当前动画
    that.setData({
      // 通过export()方法导出数据
      animationData1: animation.export(),
      // 改变view里面的Wx：if
      chooseSize: true
    })
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData1: animation.export()
      })
    }, 100)
    var query = wx.createSelectorQuery();
    query.select('.choose').boundingClientRect();
    query.exec(function (res) {
      console.log(res)
      that.setData({
        arrowDown: res[0].height + 40
      })
    })
    var query = wx.createSelectorQuery();
    query.select('.bottomAd').boundingClientRect();
    query.exec(function (res) {
      console.log(res)

    })
  },
  hideModal: function (e) {
    var that = this;
    var animation = wx.createAnimation({
      duration: 800,
      timingFunction: 'linear'
    })
    that.animation = animation
    animation.translateY(300).step()
    that.setData({
      animationData1: animation.export()

    })
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData1: animation.export(),
        chooseSize: false
      })
    }, 700)
  },
  onLoad: function (query) {
    var that = this;
    console.log(query)
    wx.setNavigationBarTitle({
      title: app.globalData.title
    })
    if (query.q) {
      var code1 = decodeURIComponent(query.q)
      var index = code1.lastIndexOf("\=");
      var code = code1.substring(index + 1, code1.length);
      console.log(code)
      that.setData({
        bike_no: code
      })
    }
    if (query.scene) {
      app.globalData.id = query.scene
    }
    this.setData({
      height1: app.globalData.statusBarHeight,
      screenHeight: app.globalData.screenHeight
    })
    wx.getSystemInfo({
      success: (res) => {
        // this.setData({
        //   controls: [{
        //     id: 1,
        //     iconPath: '/img/map1.png', //  大头针图片
        //     position: {
        //       left: (res.windowWidth -163)/ 2,
        //       top: res.windowHeight / 2 - 27,
        //       width: 163,
        //       height: 71
        //     },
        //     clickable: true
        //   }]
        // })
      }
    })
  },
  detail: function () {
    var that = this;
    if (that.data.mid[0].type == 'url') {
      wx.navigateTo({
        url: '/' + that.data.mid[0].detail
      })
    }
  },
  guanbi() {
    this.setData({
      mid: []
    })
    var timestamp = Date.parse(new Date()) / 1000 + 43200;
    // 缓存过期时间
    wx.setStorageSync('midTimes', timestamp)
  },
  tabbar_top: util.throttle(function (e) {
    this.setData({
      stopP: !this.data.stopP,
      tabbar_index: !this.data.stopP ? '1' : '0',
      show: false,
      stopShow: false
    }), this.stop()
    var polygons = this.data.polygons;
    if (this.data.stopP == true) {
      this.setData({
        polygons,
        zoom: 14
      })
    } else {
      this.setData({
        polygons,
        zoom: 18
      })
    }
  }, 2000),
  stop1: util.throttle(function () {
    this.setData({
      stopP: !this.data.stopP,
      tabbar_index: !this.data.stopP ? '1' : '0',
      show: false,
      stopShow: false
    }), this.stop()
    var polygons = this.data.polygons;
    if (this.data.stopP == true) {
      this.setData({
        polygons,
        zoom: 14
      })
    } else {
      this.setData({
        polygons,
        zoom: 18
      })
    }
  }, 2000),
  swiper: util.throttle(function (e) {
    //点击广告页
     console.log(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') {
        wx.navigateTo({
          url: '/' + detail,
        })
      } else if (type == 'phone') {
        wx.makePhoneCall({
          phoneNumber: detail,
        })
      } else if (type == 'toMiniProgram') {
        wx.navigateToMiniProgram({
          appId: detail,
          path:'pages/wjxqList/wjxqList?activityId=QSraSaM',
          extraData: {
            foo: 'bar'
          },
          // envVersion: 'develop',
          success(res) {
            // 打开成功
          }
        })
      }else {
        wx.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
      });
    }
  },
  center_swiperChange: function (e) {
    this.setData({
      center_currentSwiper: e.detail.current
    })
  },
  ads: function (id) {
    var that = this;
    var area_id = ''
    if (id != undefined) {
      area_id = id
    } else {
      area_id = 0
    }
    app.request("/ads?area_id=" + area_id + "&position[]=mid&position[]=header&position[]=footer", '', "GET").then(res => {
      console.log(res)
      if (res.statusCode == 200 && res.data != '') {
        if (res.data.header != undefined || res.data.header != 'undefined') {
          that.setData({
            ads: res.data.header
          })
        }
        if (res.data.mid != undefined || res.data.mid != 'undefined') {
          that.setData({
            mid: res.data.mid
          })
        }
        if (res.data.footer != undefined || res.data.footer != 'undefined') {
          that.setData({
            footer: res.data.footer
          })
        }
      }
    }).catch(err => {
      console.log(err)
    })
  },
  run1: function () {
    var that = this;
    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.run1();
      }
    }, 6)
  },
  notice: function () {
    var that = this;
    var area_id = ''
    if (wx.getStorageSync('home').id != undefined) {
      area_id = wx.getStorageSync('home').id
    }
    var data = {
      'area_id': area_id
    }
    app.request("/index/an", data, "GET").then(res => {
      if (res.statusCode == 200) {
        console.log(res);
        if (res.data != '') {
          that.setData({
            notice: res.data
          });
          var length = res.data.description.length * that.data.size; //计算文字的长度
          that.setData({
            length: length
          })
          if (that.data.length > that.data.marqueeWidth) {
            that.run1();
          } else {
            that.setData({
              marqueeDistance: 0
            })
          }
        }
      }
    })
  },
  tap_notice: util.throttle(function (e) {
    // console.log(e)
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../public_details/public_details?id=' + id,
    })
  }, 1000),
  posi: util.throttle(function () {
    //点击定位  
    //这是一段注释
    this.map()
    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
        })
      },
      fail: function (err) {
        that.setData({
          location: true
        })
      }
    })
  }, 1500),
  search: util.throttle(function () {
    //点击首页的搜索框
    console.log('11')
    wx.navigateTo({
      url: '../navigation/navigation',
    })
  }, 1500),
  bindregionchange: function (e) {
    //实现大头针移动选点
    var that = this
    // console.log(e)
    // if (e.type == "end" && e.causedBy == 'drag') {
    //   //停止
    //   console.log('end')
    //   var mapCtx = wx.createMapContext("map")
    //   mapCtx.getCenterLocation({
    //     success: function (res) {
    //       var latitude = res.latitude
    //       var longitude = res.longitude
    //       that.setData({ latitude, longitude })
    //       if(that.data.stopP==false){
    //         that.nearbyCars(), that.map()
    //       }
    //     }
    //   })
    // }
  },
  sweepcode: util.throttle(function () {
    this.setData({
      background: false,
      scanfail: false,
      over1: false
    })
    this.sweep_code()
  }, 1500),
  gocode: util.throttle(function () {
    //点击去试试看、使用车牌号开锁
    this.setData({
      background: false,
      scanfail: false,
      over1: false
    })
    wx.navigateTo({
      url: '../input_number/input_number',
    })
  }, 1500),
  home: function () {
    //请求首页接口和一些设置。
    var that = this;
    if (that.data.longitude != '' && that.data.latitude != '' && token != '') {
      //116.411027
      var data = {
        'lat': that.data.latitude,
        'lng': that.data.longitude
      }
      app.request("/pages/home?include=setting", data, "POST").then(res => {
        console.log(res)
        if (res.statusCode == 200) {
          var data = res.data;
          console.log(data)
          if (data.points != []) {
            that.setData({
              id: data.id,
              polygons1: that.data.polygons.concat(data),
              setting: data.setting,
              per_money: Number(data.setting.starting_price),
              polygons: []
            })
            if (!data.id) return
            that.ads(data.id),
              that.ban_stop(data.id), that.setData({
                polygons: that.data.polygons.concat(data)
              })
          }
          clearInterval(mytime)
          setTimeout(function () {
            that.notice();
          }, 500)
          if (res.data.status_code == 423) {
            wx.getLocation({
              success: function (res) {
                wx.showModal({
                  title: '提示',
                  content: '您附近暂无运营区域~',
                  showCancel: false
                })
                var setting = {
                  is_deposit: 1
                }
                that.setData({
                  setting
                })
              },
              fail: function (err) {
                that.setData({
                  location: true
                })
              }
            })
          }
          wx.setStorageSync('setting', data.setting)
          wx.setStorageSync('home', data)
        }
      }).catch(err => {
        console.log(err)
      })
    }
  },
  ban_stop: function (id) {
    var that = this;
    var data1 = {
      'area_id': id
    }
    app.request('/parking/ban-stop-sites', data1, 'GET').then(res => {
      console.log(res)
      if (res.statusCode == 200) {
        var data = res.data
        console.log(data)
        that.setData({
          polygons2: data.polygons,
          markers: that.data.markers.concat(data.centres),
          polygons: that.data.polygons1.concat(data.polygons)
        })
      }
    })
  },
  nearbyCars: function () {
    //附近的车
    var that = this;
    that.setData({
      markers: []
    })
    var data = {
      "lat": that.data.latitude,
      "lng": that.data.longitude
    }
    app.request("/bikes", data, "POST").then(res => {
      // console.log(res)
      if (res.statusCode == 200) {
        var makers = res.data
        if (makers == '') {
          wx.showToast({
            title: '附近暂无车辆',
            icon: 'none'
          })
          that.setData({
            markers: []
          })
        } else {
          that.setData({
            markers: makers
          })
        }
      }
    }).catch(err => {
      console.log(err)
    })
  },
  use: util.throttle(function () {
    //点击车辆详情的立即用车按钮
    this.jiance('use')
  }, 1000),
  map: function () {
    //点击地图使车子变回原来颜色 并且隐藏车子信息
    if (this.data.stopP == false) {
      var markers = this.data.markers;
      for (let item of markers) {
        if (item.type == 1) {
          item.iconPath = 'http://resource.bike.hanyiyun.com/weapp/ban-stop.png'
        } else {
          item.iconPath = 'http://resource.bike.hanyiyun.com/weapp/bluebike.png'
        }
      }
      this.setData({
        show: false,
        markers,
        stopShow: false
      })
    } else {
      var markers = this.data.markers;
      for (let item of markers) {
        if (item.type == 2) {
          item.iconPath = 'http://resource.bike.hanyiyun.com/weapp/stop1.png'
        }
        if (item.type == 1) {
          item.iconPath = 'http://resource.bike.hanyiyun.com/weapp/ban-stop.png'
        }
      }
      this.setData({
        stopShow: false,
        markers,
        show: false
      })
    }
  },
  stop: util.throttle(function () {
    //点击P显示停车区域并隐藏所有车子
    var that = this;
    that.setData({
      markers: []
    })
    that.map()
    // console.log(that.data.stopP)
    if (that.data.stopP == true) {
      that.stopP()
      // console.log('显示停车')
    } else {
      // console.log('隐藏停车')
      that.nearbyCars(), that.setData({
        polygons: that.data.polygons1
      }), that.ban_stop(that.data.id)
    }
  }, 1500),
  marker: function (e) {
    //点击地图上每一辆车子 使点击的车子变色并且显示车子详情
    var that = this;
    var markers = that.data.markers;
    var bolear = ''
    for (let item of markers) {
      if (item.id == e.markerId) {
        if (item.type == undefined) {
          item.iconPath = 'http://resource.bike.hanyiyun.com/weapp/yellowbike.png';
          wx.showLoading({
            title: '获取中...',
          })
          that.setData({
            code: e.markerId,
            bike: []
          })
          app.request('/bike/' + e.markerId, '', 'GET').then(res => {
            // console.log(res)
            wx.hideLoading()
            if (res.statusCode == 200) {
              that.setData({
                bike: res.data,
                show: true,
                box_no: res.data.box_no
              })
            }
          })
        } else {
          item.iconPath = 'http://resource.bike.hanyiyun.com/weapp/ban-stop.png';
        }
      } else {
        if (item.type == undefined) {
          item.iconPath = 'http://resource.bike.hanyiyun.com/weapp/bluebike.png';
        } else {
          item.iconPath = 'http://resource.bike.hanyiyun.com/weapp/ban-stop.png';
        }
      }
    }
    that.setData({
      markers,
      stopShow: true
    })
  },
  mine: function () {
    //点击左上角我的图标 跳到我的页面
    this.map()
    //如果缓存里的avatar_url 不等于空  或者  uese 不等于空
    if (wx.getStorageSync('userInfo').avatar_url != null && wx.getStorageSync('userInfo') != '') {
      wx.navigateTo({
        url: '../personal/mine/mine',
      })
    } else {
      wx.reLaunch({
        url: '../authentication/authentication',
      })
    }
  },
  stop_marker: function (e) {
    console.log(e)
    var that = this;
    var markers = e.currentTarget.dataset.markers;
    for (let item of markers) {
      if (item.id == e.markerId) {
        if (item.type == 2) {
          item.iconPath = 'http://resource.bike.hanyiyun.com/weapp/orange-stop.png'
          that.setData({
            stop_info: item,
            stop_type: 2
          })
        }
        if (item.type == 1) {
          item.iconPath = 'http://resource.bike.hanyiyun.com/weapp/ban-stop.png'
          that.setData({
            stop_info: item,
            stop_type: 1
          })
        }
      } else {
        if (item.type == 2) {
          item.iconPath = 'http://resource.bike.hanyiyun.com/weapp/stop1.png'
        }
        if (item.type == 1) {
          item.iconPath = 'http://resource.bike.hanyiyun.com/weapp/ban-stop.png'
        }
      }
    }
    // console.log(markers)
    this.setData({
      stopShow: true,
      markers
    })
  },
  stopP: function () {
    var that = this;
    var data1 = {
      'area_id': that.data.id
    }
    that.setData({
      markers: []
    })
    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
        })
      }
    })
  },
  refresh: util.throttle(function () {
    //点击刷新
    var that = this;
    that.setData({
      polygons: []
    })
    if (this.data.stopP == true) {
      that.stopP(), wx.showToast({
        title: '刷新成功',
        icon: 'none'
      })
    } else {
      this.location(), wx.showToast({
        title: '刷新成功',
        icon: 'none'
      })
    }
  }, 1500),
  authentication: util.throttle(function () {
    //点击去实名认证
    var state = wx.getStorageSync('userState')
    if (state.is_bind_mobile == 0) {
      wx.navigateTo({
        url: '/pages/real_name/real_name?state1=1&index=0',
      })
    } else if (state.is_bind_mobile == 1) {
      wx.navigateTo({
        url: '/pages/real_name/real_name?state2=2&index=1',
      })
    }

    this.setData({
      background: false,
      realname: false,
      over: false
    })
  }, 1500),
  sweep_code: util.throttle(function () {
    //点击扫码开锁
    var that = this;
    wx.getLocation({
      success: function (res) {
        that.map()
        // console.log(that.data.userStatus.is_pay_order)
        if (wx.getStorageSync('setting') == '') {
          wx.getLocation({
            success: function (res) {
              wx.showModal({
                title: '提示',
                content: '您附近暂无运营区域~',
                showCancel: false
              })
            },
            fail: function (err) {
              that.setData({
                location: true
              })
            }
          })
          return;
        }
        that.jiance('scan')
      },
      fail: function (err) {
        that.setData({
          location: true
        })
      }
    })
  }, 1500),
  jiance: function (source) {
    var that = this;
    if (that.data.userStatus.is_punishment) {
      wx.showModal({
        title: '提示',
        content: '您当前有违章订单需要处理，请处理后再来用车吧！',
        confirmText: '去处理',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/fine/fine',
            })
          }
        }
      })
      return;
    }
    var userStatus = that.data.userStatus;
    if (userStatus.is_pay_order != false && userStatus.is_pay_order != undefined) {
      this.setData({
        is_pay_order: 1,
        background: true
      })
      return;
    } else if (userStatus.is_pay_rent_order != false && userStatus.is_pay_rent_order != undefined) {
      this.setData({
        is_pay_order: 1,
        background: true
      })
      return;
    } else {
      if (that.data.setting.is_card == 1) {
        if (userStatus.is_card_certified == 0) {
          that.setData({
            realname: true,
            background: true,
            over: true
          })
          return;
        }
      }
      if (userStatus.is_bind_mobile == 0) {
        console.log('else===>else===>if')
        wx.showModal({
          title: '提示',
          content: '您还未绑定手机号，去绑定？',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/real_name/real_name?state1=1&index=0',
              })
            }
          }
        })
        return;
      } else if (userStatus.is_deposit == 0 && that.data.setting.is_deposit != 0 && userStatus.is_coupon_deposit_free == false) {
        console.log('else===>else===>else if')
        that.setData({
          deposit: true,
          background: true
        })
        return;
      } else {
        if (source == 'use') {
          wx.navigateTo({
            url: '../sweep_code/sweep_code?code=' + that.data.code,
          })
        } else {
          wx.scanCode({
            onlyFromCamera: true,
            success: function (res) {
              // console.log(res)
              var index = res.result.lastIndexOf("\=");
              var code = res.result.substring(index + 1, res.result.length);
              console.log(code.length)
              if (code.length == 11) {
                wx.navigateTo({
                  url: '../sweep_code/sweep_code?code=' + code,
                })
              } else {
                wx.showToast({
                  title: '请扫描正确的二维码！',
                  icon: 'none'
                })
              }

            },
            fail: function (err) {
              console.log(err)
              that.setData({
                background: true,
                scanfail: true,
                over1: true
              })
            }
          })
        }
      }
    }
  },
  think: util.throttle(function () {
    //点击我再想想 关闭弹窗和背景
    this.setData({
      background: false,
      deposit: false,
      over: false
    })
  }, 1500),
  deposit: util.throttle(function () {
    //点击现在就去 跳到交押金页面
    this.setData({
      background: false,
      deposit: false,
      over: false
    })
    wx.navigateTo({
      url: '/pages/personal/deposit/deposit?home=index',
    })
  }, 1500),
  cancel: util.throttle(function () {
    //点击取消，下次吧
    this.setData({
      is_pay_order: false,
      background: false
    })
  }, 1500),
  go_pay: util.throttle(function () {
    //点击去支付
    this.setData({
      is_pay_order: false,
      background: false
    })
    var pay_order = ''
    var rent = ''
    if (this.data.userStatus.is_pay_order != false && this.data.userStatus.is_pay_order != undefined) {
      pay_order = this.data.userStatus.is_pay_order
    }
    if (this.data.userStatus.is_pay_rent_order != false && this.data.userStatus.is_pay_rent_order != undefined) {
      pay_order = this.data.userStatus.is_pay_rent_order;
      rent = 'rent'
    }
    // console.log(rent)
    wx.navigateTo({
      url: '/pages/payment/payment?order=' + pay_order + '&rent=' + rent,
    })
  }, 1500),
  over: function () {
    //如果当前未实名 弹窗显示后 点击关闭按钮
    this.setData({
      realname: false,
      background: false,
      scanfail: false,
      over1: false,
      over: false,
    })
  },
  onShow: function () {
    var that = this;
    token = wx.getStorageSync('token')
    this.setData({
      show: false,
      midbolear: wx.getStorageSync('midTimes'),
      polygons: []
    })
    this.location();
    this.getUser();
    setTimeout(() => {
      that.userState();
    }, 1000);
    wx.hideHomeButton();
  },
  onReady: function () {

  },
  kefu: util.throttle(function () {
    wx.makePhoneCall({
      phoneNumber: wx.getStorageSync('home').customer_service_phone,
    })
  }, 1500),
  userState: function () {
    var that = this;
    if (token != '') {
      var data = {
        'area_id': that.data.id
      }
      app.request("/user/status", data, "GET").then(res => {
        console.log(res)
        if (res.statusCode == 200) {
          that.setData({
            userStatus: res.data,
            is_pay_order: res.data.is_pay_order
          }), wx.setStorageSync('userState', res.data)
          if (res.data.status == 0) {
            that.setData({
              abnormal: true,
              background: true
            })
            return;
          }
          if (res.data.is_ride_order != false) {
            wx.reLaunch({
              url: '/pages/riding/riding?order=' + res.data.is_ride_order,
            })
            return;
          }
          if (res.data.is_rent_order != false) {
            wx.reLaunch({
              url: '/pages/daily_riding/daily_riding?order=' + res.data.is_rent_order,
            })
            return;
          }
          if (res.data.is_pay_order != false) {
            that.setData({
              background: true,
              is_pay_order: true
            })
            return;
          }
          if (res.data.is_pay_rent_order != false) {
            that.setData({
              background: true,
              is_pay_order: true
            })
            return;
          }
          if (res.data.is_punishment) {
            wx.showModal({
              title: '提示',
              content: '您当前有违章订单需要处理，请处理后再来用车吧！',
              confirmText: '去处理',
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/fine/fine',
                  })
                }
              }
            })
            return;
          }
          var setting = wx.getStorageSync('setting');
          console.log(setting)
          if (setting == '' || setting == undefined) return;
          if (setting.is_card == 1 && setting.is_deposit == 1) {
            if (res.data.is_ride_order == false && res.data.is_pay_order == false && that.data.bike_no != undefined && res.data.is_pay_rent_order == false) {
              wx.navigateTo({
                url: '../sweep_code/sweep_code?code=' + that.data.bike_no,
              })
              return;
            }
          } else if (that.data.setting.is_card == 0 && that.data.setting.is_deposit == 0) {
            if (res.data.is_ride_order == false && res.data.is_pay_order == false && that.data.bike_no != undefined && res.data.is_pay_rent_order == false) {
              wx.navigateTo({
                url: '../sweep_code/sweep_code?code=' + that.data.bike_no,
              })
              return;
            }
          } else {
            console.log('else')
            if (setting.is_card == 1) {
              if (res.data.is_ride_order == false && res.data.is_pay_order == false && that.data.bike_no != undefined && res.data.is_pay_rent_order == false) {
                wx.navigateTo({
                  url: '../sweep_code/sweep_code?code=' + that.data.bike_no,
                })
                return;
              }
            } else if (setting.is_deposit == 1) {
              if (res.data.is_ride_order == false && res.data.is_pay_order == false && that.data.bike_no != undefined && res.data.is_pay_rent_order == false) {
                wx.navigateTo({
                  url: '../sweep_code/sweep_code?code=' + that.data.bike_no,
                })
                return;
              }
            }
          }
          if (res.data.is_new_user_coupons == 1) {
            app.request("/coupon/getNewUserCoupons", '', "GET").then(res => {
              console.log(res)
              that.setData({
                new_user_coupons: res.data
              })
              // 200 == res.statusCode && wx.setStorageSync("userInfo", res.data)
            })
          }
        }
      }).catch(err => {
        console.log(err)
      })
    }
  },
  getUser() {
    if (token != '') {
      app.request("/me", '', "GET").then(res => {
        console.log(res)
        200 == res.statusCode && wx.setStorageSync("userInfo", res.data)
      }).catch(err => {
        console.log(err)
      })
    }
  },
  bulingqu: function () {
    var userStatus = this.data.userStatus;
    userStatus.is_new_user_coupons = 0
    this.setData({
      userStatus
    })
    console.log(this.data.userStatus)
  },
  lingqu: function () {
    var status = this.data.new_user_coupons;
    var arr = []
    for (var i = 0; i < status.length; i++) {
      arr.push(status[i].id)
    }
    console.log(arr)
    var data = {
      ids: arr
    }
    app.request('/user/newUserCoupons', data, 'POST').then(res => {
      console.log(res)
      this.setData({
        new_user_coupons: []
      })
      wx.navigateTo({
        url: '/pages/newUser/newUser',
      })
      console.log(this.data.userStatus)
    })
  },
  lookCar: util.throttle(function (e) {
    console.log(e)
    wx.showLoading({
      title: '找车中...',
      mask: true
    })
    bluM.connectDeivece(e.currentTarget.dataset.box_no, CMD.bell)
    app.request('/bike/find/' + e.currentTarget.dataset.id, '', '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
        })
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000,
          mask: true
        })
      }
    })
  }, 1000),
  usage: util.throttle(function () {
    this.map()
    wx.navigateTo({
      url: '/pages/accounting_rules/accounting_rules',
    })
  }, 1500),
  help: util.throttle(function () {
    //点击如何用车 跳到如何用车页面
    this.map()
    wx.navigateTo({
      url: '../personal/help/help',
    })
  }, 1500),
  go_setting: util.throttle(function () {
    //点击去设置位置权限
    this.setData({
      background: false,
      location: false
    })
    wx.openSetting({
      success: function (res) {
        // console.log(res)
        // console.log(res.authSetting)
      }
    })
  }, 1500),
  open: util.throttle(function () {
    //点击已打开
    this.setData({
      background: false,
      location: false
    })
  }, 1500),
  navgiate: util.throttle(function (e) {
    console.log(e)
    if (this.data.stop_type == 1) return;
    var latitude = this.data.stop_info.latitude;
    var longitude = this.data.stop_info.longitude;
    var name = this.data.stop_info.name;
    wx.openLocation({ //​使用微信内置地图查看位置。
      latitude: latitude, //要去的纬度-地址
      longitude: longitude, //要去的经度-地址
      name: name
    })
  }, 1000),
  location: function () {
    //获取当前经纬度 如果未授权让用户去授权
    var that = this;
    wx.showLoading({
      title: '定位中...',
      mask: true
    })
    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,
          show: false
        })
        if (that.data.stopP == false) {
          console.log('false')
          that.home(), that.nearbyCars()
        } else {
          that.stop()
        }
        wx.hideLoading()
      },
      fail: function () {
        wx.hideLoading()
        wx.getSetting({
          success: function (res) {
            // console.log(res)
            var statu = res.authSetting;
            if (statu['scope.userLocation'] == false) {
              that.setData({
                background: true,
                location: true
              })
            }
          }
        })
      }
    })
  },
  onHide: function () {
    console.log('onHide')
    this.setData({
      bike_no: undefined,
      background: false,
      bluetooth: false,
      location: false,
      scanfail: false,
      over1: false
    })
    // clearInterval(mytime)
  },
  onUnload: function () {
    console.log('onUnload')

  },
  onShareAppMessage: function () {

  }
})