const {
  api,
  imgName,
  getUserInfo,
  confirmTip,
  wxLogin,
  wxscan,
  alertTip,
  authAgainByUser,
  userLocation
} = require('../../lib/util.js')
const app = getApp()
const qrcode = require('../../lib/qrcode.js')
Page({
  data: {
    list_main: [],
    list_assist: [],
    nowVcuNo: '',
    actions: [{
        name: '使用',
        width: 60,
        color: '#fff',
        fontsize: '16',
        background: '#1479ed',
        icon: 'camera'
      },
      {
        name: '二维码',
        width: 60,
        fontsize: '16',
        background: '#fff',
        icon: 'camera'
      },
      {
        name: '解绑',
        color: '#fff',
        fontsize: '16',
        width: 60,
        icon: 'trash',
        background: '#ed3f14'
      },
      {
        name: '取消',
        width: 60,
        color: '#80848f',
        fontsize: '16',
        icon: 'undo'
      }
    ],
    assistActions: [{
        name: '使用',
        width: 60,
        color: '#fff',
        fontsize: '16',
        background: '#1479ed',
        icon: 'camera'
      },
      {
        name: '二维码',
        width: 60,
        fontsize: '16',
        background: '#fff',
        icon: 'camera'
      },
      {
        name: '取消',
        width: 60,
        color: '#80848f',
        fontsize: '16',
        icon: 'undo'
      }
    ],
  },
  onLoad: function() {
    this.getCarList()
    this.setNowVcuNo()
  },
  onShow: function() {},
  setNowVcuNo() {
    const {
      userMapp: {
        nowVcuNo
      }
    } = wx.getStorageSync('user')
    this.setData({
      nowVcuNo
    })
  },
  actionsClick(e) {
    const id = e.target.id
    if (e.detail.index === 0) {
      this.changeCar(id)
    }
    if (e.detail.index === 1) {
      this.showCode(id)
    }
    if (e.detail.index === 2) {
      this.unbindCar(id)
    }
  },
  actionsClickAssist(e) {
    const id = e.target.id
    if (e.detail.index === 0) {
      this.changeCar(id)
    }
    if (e.detail.index === 1) {
      this.showCode(id)
    }
  },
  getCarList() {
    let that = this
    api.post('device/userBindingDeviceList')
      .then(res => {
        console.log('设备列表：', res)
        if (res.items.length > 0) {
          that.setData({
            list_main: res.items,
            // list_assist: res.items,
          })
        }else{
          wx.reLaunch({
            url: '/pages/device_bind/device_bind',
          })
        }
        wx.stopPullDownRefresh()
      })
      .catch(err => {
        wx.stopPullDownRefresh()
        alertTip(err)
      })
  },
  addCar() {
    // wx.navigateTo({
    //   url: '/pages/device_bind/device_bind?from=device',
    // })
    this.scanImg()


  },
  scanImg() {
    let This = this
    wxscan()
      .then(vcuNo => {
        This.apiUseCar(vcuNo)
      })
      .catch(err => {
        alertTip(err)
      })
  },
  apiUseCar(vcuNo) {
    let This = this
    // if (!This.data.agreeUserCar) {
    //   alertTip('请同意租车协议')
    //   return false
    // }
    api.post('device/userBindingDevice', {
        vcuNo
      })
      .then(res => {
        //有使用的车辆 跳到用车
        console.log('bind:', res)
        let user = wx.getStorageSync('user')
        user.userMapp.nowVcuNo = vcuNo
        wx.setStorageSync('user', user)
        // app.socket.open = false
        // wx.switchTab({
        //   url: '/pages/user_index/user_index',
        // })
        This.getCarList()
        alertTip('添加成功')
        return
      })
      .catch(err => {
        alertTip(err)
        console.error(err)
      })

  },
  onPullDownRefresh() {
    this.getCarList()
  },
  changeCar(vcuNo) {
    confirmTip(`确定切换设备为${vcuNo}`, () => {
      api.post('device/changeDevice', {
          vcuNo
        })
        .then(res => {
          const user = wx.getStorageSync('user')
          user.userMapp.nowVcuNo = vcuNo
          wx.setStorageSync('user', user)
          app.socket.open = false
          alertTip(res.message)
          setTimeout(() => {
            wx.reLaunch({
              url: '/pages/user_index/user_index',
            })
          }, 1500)
        })
        .catch(err => {
          alertTip(err)
        })
    })
  },
  unbindCar(vcuNo) {
    let that = this
    wx.showModal({
      title: '警告',
      content: '确定解除该设备的绑定？',
      success: function(res) {
        if (res.confirm) {
          api.post('device/userUnBindingDevice', {
              vcuNo
            })
            .then(res => {
              alertTip(res.message)
              that.getCarList()
            })
        }
      }
    })
  },
  // carBindUser(e){
  //   console.log(e)
  //   wx.navigateTo({
  //     url: `/pages/carusers/carusers?id=${e.currentTarget.id}&master=${e.currentTarget.dataset.master}`,
  //   })
  // },
  // modify(e){
  //   let that=this
  //   if (Number(e.currentTarget.dataset.master)==wx.getStorageSync('user').userId){
  //     that.setData({
  //       modify: true,
  //       deviceId: Number(e.currentTarget.id)
  //     })
  //   }else{
  //     alertTip('您不是主车主，无法修改')
  //   }
  // },
  // apiModify(e){
  //   let that=this
  //   api.post('api/vehicle/modifyVehicleInfo.json', { name: e.detail.value, otherFeatures: '', id: that.data.deviceId })
  //     .then(res => {
  //       that.setData({
  //         modify: false,
  //         modifyValue:''
  //       })
  //       that.getCarList()
  //     })
  //     .catch(err => {
  //       alertTip(err)
  //     })
  // },
  // giveUp(){
  //   let that=this
  //   wx.showModal({
  //     title: '提示',
  //     content: '确定放弃修改车辆昵称？',
  //     success(res){
  //       if(res.confirm){
  //         that.setData({
  //           modify: false,
  //           modifyValue: ''
  //         })
  //       }
  //     }
  //   })
  // },
  showCode(vcu) {
    wx.navigateTo({
      url: `/pages/qr_code/qr_code?vcu=${vcu}`,
    })
  },
  bindDevice() {
    wx.navigateTo({
      url: `/pages/device_bind/device_bind?from=device`,
    })
  },
  //适配不同屏幕大小的canvas  
  setCanvasSize: function() {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 750 / 460; //不同屏幕下canvas的适配比例；设计稿是750宽  
      var width = res.windowWidth / scale;
      var height = width; //canvas画布为正方形  
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error  
      console.log("获取设备信息失败" + e);
    }
    return size;
  },
})