// president//pages/library_books/library_books.js
import { routers, viewImage, sharePage, isFn, getGlobalVal } from '../../../utils/util.js'
import { GetBooksInlibrary, CallOutList, CallInList, GetBooksTab } from '../../../utils/api.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const { globalData } = getApp()
const { baseImgUrl, thumbnail } = globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl,
    thumbnail,
    isLoaded: 0,
    hiddenModel: false,
    screenModel: false,
    pageSize: 5,
    isShowPromptModel: true,
    pageNo: 1,
    isAll: 0,
    isSelect: false,
    isDown: false,
    gradeList: [],
    themeList: [],
    isLoad: false,
    isShai: false,
    parentCode: [],
    classList: [],
    bookList: [],
    childList: [],
    itemIndex: 0,
    isCheck: 0,
    number: 0,
    themeListindex: '',
    stat: 2,
    list: [
      // {
      //   "heat": "2",
      //   "local_image": "/2017/05/07/412623a8c9d6b5a0f92c6152d863c2f2a32d08cc78e72afb7d15d01ca172f9e3.jpg",
      //   "isbn13": "9787539191508",
      //   "book_info_id": "000c1b25-285e-42ce-8819-17edfd1ece54",
      //   "book_size": 2,
      //   "book_detail_id": "0d2d09cb-7817-4ef2-8fa5-e860810aaa80",
      //   "theme": "大语文-传统国学",
      //   "title": "谚语集锦"
      // },
      // {
      //   "heat": "0",
      //   "local_image": "/2017/05/04/79df39e1-af29-4fe7-89ca-944435d0ac4f.jpg",
      //   "isbn13": "9787543566804",
      //   "book_info_id": "004881ee-3658-47be-b358-106b1d2d4b57",
      //   "book_size": 1,
      //   "book_detail_id": "1b8a2d9f-8550-4437-b14b-eba34b736b8c",
      //   "theme": "科学探究",
      //   "title": "人人都有写作天赋/美国中小学生人文和科学阅读系列"
      // }
    ],
    HeaderbookList: [
      {
        name: '在馆书籍',
        amount: '',
        unit: '本'
      },
      {
        name: '外借书籍',
        amount: '',
        unit: '人'
      },
    ],
    footerData: {
      actIndex: 0,
      list: [
        {
          text: '在馆书籍',
          icon: '../../../assets/zai_guan_shu_ji_gray.png',
          actIcon: '../../../assets/zai_guan_shu_ji_blue.png',
          url: 'president/pages/library_books/library_books',
          zindex: 3
        },
        {
          text: '好书推荐',
          icon: '../../../assets/wish_gray.png',
          actIcon: '../../../assets/wish_blue.png',
          url: 'president/pages/good_books_new/good_books_new',
          zindex: 3
        },
        {
          text: '调书清单',
          icon: '../../../assets/diao_shu_qing_dan_gray.png',
          actIcon: '../../../assets/diao_shu_qing_dan_blue.png',
          url: 'president/pages/book_inventory/book_inventory',
          zindex: 3
        }
      ]
    },
    nodataArray: {
      text: "暂无数据"
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    options.vipId = getGlobalVal('vipId', `vipId_${getGlobalVal('userId')}`)
    options.libId = getGlobalVal('list').length > 0 ? getGlobalVal('list')[0].libId : ''
    this.setData(options)


  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const show = wx.getStorageSync('isfirstLogin')
    this.setData({ isfirstLogin: show })
    this.getBookHeader(res => {
      this.getData(res => {
        this.setData({ isLoaded: 1 })
      })
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

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

  },

  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () {
    this.setData({ pageNo: 1 })
    this.getData(() => {
      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 })
      })
    }
  },
  /**
    * 搜索页面
    */
  inputSearchPage: function () {
    navigateTo({
      url: 'president/pages/search_books/search_books',
    })
  },
  selectNavCtl: function (e) {
    const { index } = e.currentTarget.dataset
    const {vipId,libId}=this.data
    if (index == 0) {
      navigateTo({
        url: 'president/pages/book_classification/book_classification',
      })
    }
    if (index == 1) {
      navigateTo({
        url: 'president/pages/borrow_record/borrow_record',paras: { vipId,libId }
      })
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (isFn(sharePage)) return sharePage()
  },
  /**
   * 提示框隐藏
   */
  screenShowModel: function () {
    this.setData({ screenModel: false })
  },

  /**
   * 筛选
   */
  getScreen: function () {
    this.setData({ screenModel: true })
  },
  /**
   * 热度排序
   */
  selectHot: function () {
    const { itemIndex } = this.data
    var idx = itemIndex != 1 ? 1 : 0
    this.setData({ itemIndex: idx, pageNo: 1 })
    wx.showLoading({
      title: '加载中',
    })
    this.getData(() => {
      wx.hideLoading();
    })
  },
  /**
* 关闭提示框
*/
  MessageconfirmClose: function () {
    wx.setStorageSync('isfirstLogin', false)
    this.setData({ isfirstLogin: false })
  },
  /**
   * 选择年级
   */
  selectGrade: function (e) {
    const { index } = e.currentTarget.dataset
    const { isCheck, gradeList, classList } = this.data
    const temp = {}
    temp[`gradeList[${index}].isCheck`] = gradeList[index].isCheck != 1 ? 1 : 0
    this.setData(temp)
    if (gradeList[index].isCheck == 1) {
      classList.push({
        grade: gradeList[index].grade
      })
    } else if (gradeList[index].isCheck == 0) {
      for (var i in classList) {
        if (gradeList[index].grade == classList[i].grade) {
          classList.splice(i, 1)
        }
      }
    }
    this.setData({ classList })
  },

  /**
  * 选择主题
  */
  selectTheme: function (e) {
    const { index, key, type } = e.currentTarget.dataset
    const { isCheck, themeList, bookList = [], childList = [] } = this.data
    const temp = {}
    if (type == 1) {
      temp[`themeList[${index}].isCheck`] = themeList[index].isCheck != 1 ? 1 : 0
      this.setData(temp)
      if (themeList[index].isCheck == 1) {

        bookList.push({
          code: themeList[index].code,
          name: themeList[index].name,
          childList
        })
      } else if (themeList[index].isCheck == 0) {
        for (var i in bookList) {
          if (themeList[index].code == bookList[i].code) {
            bookList.splice(i, 1)
          }
        }
      }

    } else {
      temp[`themeList[${index}].childList[${key}].isCheck`] = themeList[index].childList[key].isCheck != 1 ? 1 : 0
      this.setData(temp)
      for (var i in themeList) {
        for (var j in themeList[i].childList) {
          if (themeList[i].childList[j].isCheck == 1) {
            if (themeList[i].code == themeList[index].code) {
              childList.push({
                code: themeList[i].childList[j].code
              })
            }
            bookList.push({
              code: themeList[i].code,
              childList
            })

          }
        }
      }
    }
    this.setData({ bookList })
    console.log(bookList)
  },
  /**
  * 重置
  */
  getReset: function () {
    const { themeList, gradeList } = this.data
    const temp = {}
    for (var i in gradeList) {
      temp[`gradeList[${i}].isCheck`] = 0
    }
    for (var i in themeList) {
      temp[`themeList[${i}].isCheck`] = 0
      for (var j in themeList[i].childList) {
        temp[`themeList[${i}].childList[${j}].isCheck`] = 0
      }
    }
    this.setData(temp)
    this.setData({ classList: [], bookList: [], isShai: false })
  },
  /**
  * 提交
  */
  getSubmit: function () {
    const { classList, bookList, isSelect, isShai } = this.data
    // if (classList.length == 0) {
    //   wx.showToast({
    //     title: `请选择年级`,
    //     icon: 'none'
    //   })
    //   return
    // }
    if (classList.length > 0 || bookList.length > 0) {
      this.setData({ isShai: true })
    } else {
      this.setData({ isShai: false })
    }
    this.setData({ pageNo: 1, stat: 1 })
    this.getData(res => {
      this.setData({ isSelect: !isSelect, screenModel: false })
    })

  },
  /**
 * 在馆书籍头部与标签
 */
  getBookHeader: function (cb) {
    const continuousFn = { fn: this.getBookHeader, param: { ...arguments } }
    const { libId, HeaderbookList } = this.data
    GetBooksTab({ data: { libId }, continuousFn }).then(res => {
      const { booksSize, serviceVipSize, borrowingSize, themeList, gradeList } = res.data
      var temp = {};
      temp[`HeaderbookList[${0}].amount`] = booksSize
      temp[`HeaderbookList[${1}].amount`] = borrowingSize
      this.setData(temp)
      wx.setStorageSync('booksSize', booksSize);
      this.setData({ themeList, gradeList })
      if (isFn(cb)) cb(res)
    }).catch(res => {
      if (isFn(cb)) cb()
    })
  },
  /**
   * 在馆书籍
   */
  getData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { pageNo, pageSize, itemIndex, classList, bookList, stat, libId, number, list = [] } = this.data
    GetBooksInlibrary({ data: { libId, pageNo, pageSize, type: ~~itemIndex + 1, stat, gradeList: classList, themeList: bookList }, continuousFn }).then(res => {
      const { list } = res.data
      let listTemp = []
      if (pageNo == 1) {
        listTemp = [].concat(list)
      } else {
        listTemp = [].concat(this.data.list, list)
      }
      // console.log(listTemp)
      this.setData({ list: listTemp, pageNo: list.length == pageSize ? pageNo + 1 : pageNo, isAll: list.length < pageSize })
      cb && cb(res)
    }).catch(res => {
      cb && cb(res)
    })
  },

})