var app = getApp()
import {
  BluetoothManager,
  CMD
} from '../../service/BluWkm'
const bluM = new BluetoothManager;
const util = require('../../utils/utils.js');
var interval;
Page({
  data: {
    useBikeTip: true,
    code: '',
    arr: [],
    screenHeight: '',
    show: false,
    popShow: false, //用车提醒
    time: 5,
    tapShow: false,
    setting: wx.getStorageSync('setting'),
    footer: [],
    chooseSize: false,
    mid: [],
    animationData: {},
    chooseSize: false,
    animationData1: {},
    arrowDown: '',
    midbolear: '',
    img:app.globalData.imgUrl,
    deposit:false,
    realname:false,
    background:false,
    over:false,
    useruserState:wx.getStorageSync('userState')
  },
  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),
  deposit: util.throttle(function () {
    //点击现在就去 跳到交押金页面
    this.setData({
      background: false,
      deposit: false,
      over: false
    })
    wx.navigateTo({
      url: '/pages/personal/deposit/deposit?home=index',
    })
  }, 1500),
  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 + 15
      })
    })
  },
  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)
  },
  ads: function () {
    var that = this;
    var area_id = ''
    if (wx.getStorageSync('home').id != undefined) {
      area_id = wx.getStorageSync('home').id
    } else {
      area_id = 0
    }
    // var data = {
    //   'position': "['header','mid']",
    //   'area_id': area_id
    // }
    app.request("/ads?area_id=" + area_id + "&position[]=mid&position[]=header&position[]=footer", '', "GET").then(res => {
      // console.log(res)
      if (res.statusCode == 200) {
        that.setData({
          ads: res.data.header
        })
        if (res.data.mid == undefined || res.data.mid == 'undefined') {

        } else {
          that.setData({
            mid: res.data.mid
          })
        }
        if (res.data.footer == undefined || res.data.footer == 'undefined') {

        } else {
          that.setData({
            footer: res.data.footer
          })
        }
      }
    }).catch(err => {
      console.log(err)
    })
  },
  onLoad: function (options) {
  
    console.log(options)
    var that = this;
    var state = wx.getStorageSync('userState')
    if(state.is_new_user==1){
     
      that.setData({
        useBikeTip:false
      })
      console.log(that.data.useBikeTip)
    }else{
      that.setData({
        useBikeTip:true
      })
    }
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    if (wx.getStorageSync('popShow') != true) {
      that.setData({
        popShow: true
      })
    } else {
      that.setData({
        popShow: false
      })
    }
    interval = setInterval(function () {
      var time = that.data.time - 1;
      that.setData({
        time
      })
      if (time <= 0) {
        clearInterval(interval)
        that.setData({
          tapShow: true
        })
      }
    }, 1000)
    this.setData({
      screenHeight: app.globalData.screenHeight
    })
    app.request('/bike/' + options.code, '', 'GET').then(res => {
      console.log(res)
      200 == res.statusCode && that.setData({
        arr: res.data
      }), wx.hideLoading()
      if (res.statusCode == 200) {
        if (res.data.is_link == 0) {
          wx.showModal({
            title: '提示',
            content: '当前车子已下线请换辆车子骑行吧~',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.navigateBack()
              }
            }
          })
          return;
        } else if (res.data.put_status == 0) {
          wx.showModal({
            title: '提示',
            content: '当前车子还未投放请换辆车子骑行吧~',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.navigateBack()
              }
            }
          })
          return;
        } else if (res.data.is_low_battery_power == 0) {
          wx.showModal({
            title: '提示',
            content: '当前车子电量过低请换辆车子骑行吧~',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.navigateBack()
              }
            }
          })
          return;
        } else if (res.data.is_trouble == 1) {
          wx.showModal({
            title: '提示',
            content: '当前车子出现故障请换辆车子骑行吧~',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.navigateBack()
              }
            }
          })
          return;
        } else if (res.data.is_riding == 1) {
          wx.showModal({
            title: '提示',
            content: '当前车子正在骑行请换辆车子骑行吧~',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.navigateBack()
              }
            }
          })
          return;
        } else {
          // bluM.connectDeivece(res.data.box_no, CMD.bell)
          // wx.getBluetoothAdapterState({
          //   success(res) {
          //     console.log(res)
          //     if (res.available == false) {
          //       wx.showModal({
          //         title: '提示',
          //         content: '手动开启蓝牙体验快速开锁~',
          //         showCancel: false
          //       })
          //     }
          //   }
          // })
        }
      }
    })
    that.setData({
      code: options.code
    })
    setTimeout(() => {
      that.ads();
    }, 500);
  },
  rules: function () {
    wx.navigateTo({
      url: "/pages/accounting_rules/accounting_rules",
    })
  },
  view_area: function () {
    wx.navigateTo({
      url: '/pages/navigation/navigation',
    })
  },
  closePop() {
    this.setData({
      popShow: false,
    })
    wx.setStorageSync('popShow', true)
  },
  repair: util.throttle(function () {
    wx.navigateTo({
      url: '../repair/repair?bike_id=' + this.data.code
    })
  }, 1000),
  openBike() {
    var that = this;
    wx.showLoading({
      title: '开锁中...',
      mask: true
    })
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res)
        var data = {
          bike_no: that.data.code,
          lat: res.latitude,
          lng: res.longitude,
          area_id: wx.getStorageSync('home').id,
        }
        bluM.connectDeivece(that.data.arr.box_no, CMD.unlock)
        app.request('/bike/open-lock', data, 'POST', app.globalData.req).then(res => {
          console.log(res)
          if (res.statusCode == 200) {
            wx.reLaunch({
              url: '../riding/riding?order=' + res.data.no + '&code=' + that.data.code + '&box_no=' + that.data.arr.box_no + '&time=true',
            })
            wx.hideLoading()
          }
        })
      },
    })
  },
  think:function () {
    //点击我再想想 关闭弹窗和背景
    this.setData({
      background: false,
      deposit: false,
      over: false
    })
  },
  start: util.throttle(function () {
    var that = this;
    that.jiance()
    if(that.data.deposit==true) return;
    wx.getLocation({
      success: function (res) {
        wx.requestSubscribeMessage({
          tmplIds: ['CBp8jWZHVOQBIB7_n4EHuDv3ik12gOvlaXsOG2U0dPc', 'rV85SkGp7Q508xXz45ycQw8nTN_2VEB7m_GhR-WrCDY'],
          success(res) {
            console.log(res)
          },
          fail: function (err) {
            console.log(err)
          },
          complete: function () {
            that.openBike()
          }
        })
      },
      fail: function (err) {
        wx.showModal({
          title: '提示',
          content: '请打开位置权限~',
          cancelText: "去设置",
          confirmText: "已打开",
          success: function (resp) {
            if (resp.cancel) {
              wx.openSetting({
                success: function (res) {
                  // console.log(res)
                  // console.log(res.authSetting)
                }
              })
            }
          }
        })
      }
    })
  }, 1000),
  rent_start: function () {
    this.setData({
      show: true
    })
  },
  over: function () {
    //如果当前未实名 弹窗显示后 点击关闭按钮
    this.setData({
      realname: false,
      background: false,
      scanfail: false,
      over: false,
    })
  },
  jiance:function(){
    var userStatus = wx.getStorageSync('userState');
    var setting = wx.getStorageSync('setting');
      if (userStatus.is_card_certified == 0 && setting.is_card !=0) {
        this.setData({
          realname: true,
          background: true,
          over: true
        })
        return;
      } else if (userStatus.is_bind_mobile == 0) {
        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 && setting.is_deposit != 0 && userStatus.is_coupon_deposit_free==false) {
          this.setData({
            deposit: true,
            background: true
          })
          return;
        }
      }
  },
  rent_startBike() {
    var that = this;
    if(that.data.deposit==true) return;
    wx.getLocation({
      success: function (res) {
        console.log(res)
        if (app.globalData.req) {
          var data = {
            'type': 'D',
            'bike_no': that.data.code,
            'area_id': wx.getStorageSync('home').id,
            'lat': res.latitude,
            'lng': res.longitude
          }
          app.request('/rent/store-order', data, 'POST', app.globalData.req).then(res => {
            console.log(res)
            if (res.statusCode == 200) {
              console.log(res.data.nonceStr == undefined)
              if (res.data.nonceStr == undefined) {
                wx.reLaunch({
                  url: '/pages/daily_riding/daily_riding?order=' + res.data.no,
                })
              } else {
                wx.reLaunch({
                  url: '/pages/daily_riding/daily_riding?order=' + res.data.no,
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: '您的操作过于频繁，请稍后再试~',
            icon: 'none'
          })
        }

      },
    })
  },
  btn: util.throttle(function () {
    var that = this;
    // that.rent_startBike()
    wx.getLocation({
      success: function (res) {
        wx.requestSubscribeMessage({
          tmplIds: ['ahWdpxZJ48d3K9ZxnrNvXLvx7NEI2j-Ckp5LODNlYNU', 'N7etCOUMjvsyGxx0JroDfMwEmi8daKC20czG6aqkpPc'],
          success(res) {
            console.log(res)
          },
          fail: function (err) {
            console.log(err)
          },
          complete: function () {
            that.rent_startBike()
          }
        })
      },
      fail: function (err) {
        wx.showModal({
          title: '提示',
          content: '请打开位置权限~',
          cancelText: "去设置",
          confirmText: "已打开",
          success: function (resp) {
            if (resp.cancel) {
              wx.openSetting({
                success: function (res) {
                  // console.log(res)
                  // console.log(res.authSetting)
                }
              })
            }
          }
        })
      }
    })

  }, 1000),
  over: function () {
    this.setData({
      show: false
    })
  },
  iKnow: function (e) {
    console.log(e)
    this.setData({
      useBikeTip: true
    })
    console.log(this.data.useBikeTip)
  },
  onReady: function () {

  },
  onShow: function () {
    this.setData({
      setting: wx.getStorageSync('setting')
    })
  },
  onHide: function () {
    clearInterval(interval)
    this.setData({
      time: 5
    })
  },
  onUnload: function () {
    clearInterval(interval)
    this.setData({
      time: 5
    })
  },
  onPullDownRefresh: function () {

  },
  onReachBottom: function () {

  },
  onShareAppMessage: function () {

  }
})