//获取应用实例
const app = getApp();
var token = wx.getStorageSync('token');
const util = require('../../../utils/utils.js');
var mytime = null;
Page({
  data: {
    showOnlinePhone: wx.getStorageSync('home').setting,
    markers: [], //显示单车、停车的P
    longitude: '0',
    latitude: '0',
    height1: '', //兼容自定义导航栏的高度
    show: false, //车子详情的布尔值 
    id: '', //停车区域的ID      
    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,
    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:'',
    time:'',
    img:app.globalData.imgUrl,
    title:app.globalData.title 
  },
  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
    })
    this.getUser();
    this.userState();
    this.location()
  },
  guanbi() {
    this.setData({
      mid: []
    })
    var timestamp = Date.parse(new Date())/1000+43200;
    // 缓存过期时间
    wx.setStorageSync('midTimes', timestamp)
  },
  swiper: util.throttle(function (e) {
    //点击广告页
    // console.log(e)
    var type = e.currentTarget.dataset.type;
    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 {
        wx.navigateTo({
          url: '/pages/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
          })
        }
      }
    }).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: '/pages/public_details/public_details?id=' + id,
    })
  }, 1000),
  search: util.throttle(function () {
    //点击首页的搜索框
    wx.navigateTo({
      url: '/pages/navigation/navigation',
    })
  }, 1500),
  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: '/pages/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=>{
        if (res.statusCode == 200) {
          var data = res.data;
          console.log(data)
          if (data.points != []) {
            that.setData({
              id: data.id,
              setting: data.setting,
              per_money: Number(data.setting.starting_price),
            })
            if (!data.id) return
            that.ads(data.id)
          }
          clearInterval(mytime)
          setTimeout(function () {
            that.notice();
          }, 500)
          if (res.data.status_code == 423) {
            wx.getLocation({
              success: function (res) {
                wx.showModal({
                  title: '提示',
                  content: '您附近暂无运营区域~',
                  showCancel: false
                })
              },
              fail: function (err) {
                that.setData({
                  location: true
                })
              }
            })
          }
          wx.setStorageSync('setting', data.setting)
          wx.setStorageSync('home', data)
        }
      })
    }
  },
  html5(e){
    wx.navigateTo({
      url: '/pages/compatible/html5/html5',
    })
  },
  mine: function () {
    //点击左上角我的图标 跳到我的页面
    //如果缓存里的avatar_url 不等于空  或者  uese 不等于空
    if (wx.getStorageSync('userInfo').avatar_url != null && wx.getStorageSync('userInfo') != '') {
      wx.navigateTo({
        url: '/pages/personal/mine/mine',
      })
    } else {
      wx.reLaunch({
        url: '/pages/authentication/authentication',
      })
    }
  },
  qixingCare(){
    wx.navigateTo({
      url: '/pages/recharge/recharge',
    })
  },
  yajinCare(){
    wx.navigateTo({
      url: '/pages/personal/deposit/deposit',
    })
  },
  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) {
        // 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;
        }
        if(that.data.userStatus.is_punishment){
          wx.showModal({
            title: '提示',
            content:'您当前有违章订单需要处理，请处理后再来用车吧！',
            confirmText:'去处理',
            success:function(res){
              if(res.confirm){
                wx.navigateTo({
                  url: '/pages/fine/fine',
                })
              }
            }
          })
          return;
        }
        if (that.data.userStatus.is_pay_order != false && that.data.userStatus.is_pay_order != undefined) {
          that.setData({
            is_pay_order: 1,
            background: true
          })
          return;
        } else if (that.data.userStatus.is_pay_rent_order != false && that.data.userStatus.is_pay_rent_order != undefined) {
          that.setData({
            is_pay_order: 1,
            background: true
          })
          return;
        } else {
          if (wx.getStorageSync('userInfo').avatar_url != null && wx.getStorageSync('userInfo') != '') {
            if (that.data.userStatus.is_card_certified == 0) {
              that.setData({
                realname: true,
                background: true,
                over: true
              })
              return;
            } else if (that.data.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 (that.data.userStatus.is_deposit == 0) {
                that.setData({
                  deposit: true,
                  background: true
                })
                return;
              } 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: '/pages/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
                    })
                  }
                })
              }
            }
          } else {
            wx.reLaunch({
              url: '/pages/authentication/authentication',
            })
          }
        }
      },
      fail: function (err) {
        that.setData({
          location: true
        })
      }
    })
  }, 1500),
  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,
    })
  },
  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
        })
          that.home()
        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
              })
            }
          }
        })
      }
    })
  },
  onShow: function () {
    var that = this;
    token = wx.getStorageSync('token')
    this.setData({
      show: false,
      midbolear: wx.getStorageSync('midTimes'),
      time: wx.getStorageSync('home').customer_service_time
    })
    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 != '') {
      app.request('/user/status','','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 (that.data.userStatus.is_ride_order != false) {
            wx.reLaunch({
              url: '/pages/riding/riding?order=' + that.data.userStatus.is_ride_order,
            })
            return;
          }
          if (that.data.userStatus.is_rent_order != false) {
            wx.reLaunch({
              url: '/pages/daily_riding/daily_riding?order=' + that.data.userStatus.is_rent_order,
            })
            return;
          }
          if (that.data.userStatus.is_pay_order != false) {
            that.setData({
              background: true,
              is_pay_order: true
            })
            return;
          }
          if (that.data.userStatus.is_pay_rent_order != false) {
            that.setData({
              background: true,
              is_pay_order: true
            })
            return;
          }
          if(that.data.userStatus.is_punishment){
            console.log(that.data.userStatus)
            wx.showModal({
              title: '提示',
              content:'您当前有违章订单需要处理，请处理后再来用车吧！',
              confirmText:'去处理',
              success:function(res){
                if(res.confirm){
                  wx.navigateTo({
                    url: '/pages/fine/fine',
                  })
                }
              }
            })
            return;
          }
          if (wx.getStorageSync('userInfo') && res.data.is_card_certified == 1 && res.data.is_deposit == 1 && 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: '/pages/sweep_code/sweep_code?code=' + that.data.bike_no,
            })
            return;
          }
          if (wx.getStorageSync('userInfo').avatar_url != null && wx.getStorageSync('userInfo') != '' && that.data.bike_no != undefined) {
            if (that.data.userStatus.is_card_certified == 0 && that.data.bike_no != undefined) {
              that.setData({
                realname: true,
                background: true,
                over: true
              })
              return;
            } else if (that.data.userStatus.is_bind_mobile == 0 && that.data.bike_no != undefined) {
              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 (that.data.userStatus.is_deposit == 0 && that.data.bike_no != undefined) {
                that.setData({
                  deposit: true,
                  background: true
                })
                return;
              }
            }
          } else {
            // wx.redirectTo({
            //   url: '../authentication/authentication',
            // })
          }
        }
      })
    }
  },
  getUser() {
    if (token != '') {
      app.request('/me','','GET').then(res=>{
        200 == res.statusCode && wx.setStorageSync("userInfo", res.data)
      })
    }
  },
  usage: util.throttle(function () {
    wx.navigateTo({
      url: '/pages/accounting_rules/accounting_rules',
    })
  }, 1500),
  help: util.throttle(function () {
    //点击如何用车 跳到如何用车页面
    wx.navigateTo({
      url: '/pages/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),
  onHide: function () {
    console.log('onHide')
    this.setData({
      bike_no: undefined,
      background: false,
      bluetooth: false,
      location: false,
      scanfail: false,
      over1: false
    })
    // clearInterval(mytime)
  },
  service(){
    this.setData({kefu:true})
  },
  hidden(){
    this.setData({kefu:false})
  },
  onUnload: function () {
    console.log('onUnload')
    
  },
  onShareAppMessage: function () {
    
  }
})