// dispatcher/pages/sweeped_books/sweeped_books.js
import { routers, viewImage, sharePage, isFn, getGlobalVal } from '../../../utils/util.js'
import { AgencyVipList, InitBorrowCar, ScanningBooksTwo} from '../../../utils/api.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const { globalData } = getApp()
const { baseImgUrl, thumbnail, qrcodeInvalidToastText } = globalData

Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl,
    thumbnail,
    isLoaded: false,
    isAllCheck: 0,
    isManage: 0,
    totalNum: 0,
    childName:'',
    ids: [],
    pageNo: 1,
    studentId:'',
    isDown: false,
    pageSize: 10,
    isAll: 0,
    totalNumbers: 0,
    list: [
    ],
    nodataArray: {
      text: "暂无图书",
      image: '../../../assets/nodata_1.png',
      margin: '400rpx auto'
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    options.userId = getGlobalVal('userId')
    options.libId = getGlobalVal('list').length > 0 ? getGlobalVal('list')[0].libId : ''
    options.library = getGlobalVal('library')
    this.setData({ options })
    wx.setNavigationBarTitle({
      title: `代办借阅`,
    })
    this.getData(res => {
      this.setData({ isLoaded: 1 })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const obj = { navigateTo, redirectTo, navigateBack, viewImage }
    for (const i in obj) {
      this[i] = obj[i]
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },
 

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const obj = { navigateTo, redirectTo, navigateBack, viewImage }
    for (const i in obj) {
      this[i] = obj[i]
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({ pageNo: 1 })
    this.getData(res => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const { isAll, isDown } = this.data
    if (isAll) {
      this.setData({ isDown: true })
      return
    } else {
      this.setData({ isLoad: true, isDown: false })
      this.getData(() => {
        this.setData({ isLoad: false })
      })
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (isFn(sharePage)) return sharePage()
  },
  /**
   * 选择跳转进入页
   */
  selectNavCtl: function (e) {
    const { id } = e.currentTarget.dataset
    const { options } = this.data
    this.setData({ studentId: id })
    wx.setStorageSync('studentId', id);
    const bookList = getGlobalVal(`presidentBorrowBook_${options.userId}_${options.libId}_${id}`) || []
    console.log(`presidentBorrowBook_${options.userId}_${options.libId}_${id}`)
    console.log(bookList)
    this.setData({bookList })
    this.scanCtl()
  },

  /**
  * 调用微信扫一扫之前判断可借书多少本
  */
  scanCtl: function () {
    const continuousFn = { fn: this.scanCtl, param: { ...arguments } }
    const { libId, vipId } = this.data.options
    const { studentId, options } = this.data
    const bookList = getGlobalVal(`presidentBorrowBook_${options.userId}_${options.libId}_${studentId}`) || []
    console.log(`presidentBorrowBook_${options.userId}_${options.libId}_${studentId}`)
    console.log(bookList)
    InitBorrowCar({ data: { vipId: studentId, libId }, continuousFn }).then(res => {
      const { canBorrowNum, borrowNumTotal } = res.data
      wx.showToast({
        title: `您还可以借${canBorrowNum}本书`,
        icon: 'none'
      })
      // if (canBorrowNum ==0) return
      // // if (this.data.bookList.length > 0) {
      // //   navigateTo({ url: 'president/pages/borrow_car/borrow_car', paras: { canBorrowNum } })
      // //   return
      // // }
      // if (canBorrowNum > 0) {
      //   this.scanFn()
      // }
      console.log(bookList)
      if (bookList.length > 0) {
        navigateTo({ url: 'president/pages/borrow_car/borrow_car', paras: { canBorrowNum } })
        return
      }
      if (canBorrowNum -bookList.length > 0) {
        this.scanFn()
      }
      this.setData({ ...res.data })
    })
  },
  /**
 * 调用微信扫一扫
 */
  scanFn: function () {
    wx.scanCode({
      success: res => {
        const url = res.result
        const detailsId = url.split('_')[1].split('.')[0]
        if (!detailsId) {
          wx.showToast({
            title: qrcodeInvalidToastText,
            icon: 'none'
          })
          return
        }
        this.scanningBooksFn(detailsId)
      }
    })
  },

  /**
   * 获取书籍数据
   */
  getData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { pageNo, pageSize, list, childName } = this.data
    const { libId } = this.data.options
    AgencyVipList({ data: { libId, pageNo, pageSize, childName }, continuousFn }).then(res => {
      const { list, pages } = res.data
      let listTemp = []
      if (pageNo == 1) {
        listTemp = [].concat(list)
      } else {
        listTemp = [].concat(this.data.list, list)
      }
      const correctListTemp = (res => {
        console.log(res)
        var d = []
        for (let i in res) {
          res[i].number = 0
        }
        return res
      })(listTemp)
      this.setData({ list: correctListTemp, totalNumbers:pages, pageNo: list.length == pageSize ? pageNo + 1 : pageNo, isAll: list.length < pageSize })
      cb && cb(res)
    }).catch(res => {
      cb && cb(res)
    })
  },
  /**
   * 扫一扫借书
   */
  scanningBooksFn: function (detailsId) {
    const continuousFn = { fn: this.scanningBooksFn, param: { ...arguments } }
    const { vipId } = this.data.options
    const { canBorrowNum, bookList, studentId } = this.data
    ScanningBooksTwo({ data: { detailsId, vipId: studentId }, continuousFn }).then(res => {
      const { detailsId} = res.data;
      for (var i in bookList) {
        if (detailsId == bookList[i].detailsId) {
          wx.showToast({
            title: '此二维码已经扫过',
            icon: 'none'
          })
        }
      }
      if (detailsId) {
        navigateTo({ url: 'president/pages/borrow_car/borrow_car', paras: { ...res.data, canBorrowNum } })
      }
    }).catch(res => {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
    })
  }
})