// parents/pages/search/search.js
import { routers, viewImage, sharePage, isFn, getGlobalVal } from '../../../utils/util.js'
import { SearchIndex, SearchBookList, ThemeSearch, AddWishBooks, GoodIndexSearch, IndexSearchHis, ClearSearchHis} from '../../../utils/api.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const { globalData, hasLibraryService, hasVipService } = getApp()
const { baseImgUrl, thumbnail, qrcodeInvalidToastText, borrowToastText, reservationsToastText, wishToastText } = globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    thumbnail,
    baseImgUrl,
    borrowToastText,
    reservationsToastText,
    wishToastText,
    isLoaded: 1,
    pageSize: 10,
    pageNo: 1,
    isAll: 0,
    isShow: 0,
    list:[],
    itemIndex: 0,
    items: ['按周阅读量排序', '按借阅热度排序', '按借阅量TOP10排序'],
    content: '',
    isReturn: 0,
    isType:false,
    isRecord:true,
    nodataArray: {
      text: "搜索无结果"
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    options.vipId = getGlobalVal('vipId', `vipId_${getGlobalVal('userId')}`)
    options.libId = getGlobalVal('library').id || 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 () {
    this.getIndexSearchHis()
    // this.getData(res => {
    //   this.setData({ isLoaded: 1 })
    // })
  },

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

  },

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

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const { isAll, options } = this.data
    const { type = 1 } = options
    if (isAll) return
    this.getData()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (isFn(sharePage)) return sharePage()
  },
  /**
    * 获取历史记录
    */
  getIndexSearchHis: function (cb) {
    const continuousFn = { fn: this.getIndexSearchHis, param: { ...arguments } }
    IndexSearchHis({ data: {}, continuousFn }).then(res => {
      const { searchHis } = res.data
      this.setData({ contentList: searchHis })
    })
  },

  /**
   * 获取搜索数据
   */
  getData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { content, options, pageNo, pageSize, itemIndex } = this.data
    const { libId, type, child_theme } = options
    var that=this;
    wx.showLoading({
      title: '加载中',
    })
    const Fn = [GoodIndexSearch, SearchBookList, ThemeSearch]
    const data = [{ libId, searchTitle:content, pageNo, pageSize }, { libId, content, pageNo, pageSize, type: itemIndex + 1 }, { libId, content, pageNo, pageSize, childTheme: child_theme }]
    Fn[type - 1]({ data: data[type - 1], continuousFn}).then(res => {
      wx.hideLoading()
      if (type == 1) {
        const { list } = res.data
        const oneTemp = (res => {
          for (let i in res) {
            if (res[i].summary.length > 30) {
              res[i].summary = res[i].summary.slice(0, 30) + '...'
            } else {
              res[i].summary = res[i].summary
            }
          }
          return res
        })(list)
        let listTemp = []
        if (pageNo == 1) {
          listTemp = [].concat(oneTemp)
        } else {
          listTemp = [].concat(that.data.list, oneTemp)
        }
        that.setData({ list: listTemp, pageNo: list.length == pageSize ? pageNo + 1 : pageNo, isAll: list.length < pageSize,isType:true })
      } else if (type ==2) {
        const { list } = res.data
        let listTemp = []
        if (pageNo == 1) {
          listTemp = [].concat(list)
        } else {
          listTemp = [].concat(that.data.list, list)
        }
        that.setData({ list: listTemp, pageNo: list.length == pageSize ? pageNo + 1 : pageNo, isAll: list.length < pageSize })
      } else if (type == 3) {
        const { bookList } = res.data
        let listTemp = []
        if (pageNo == 1) {
          listTemp = [].concat(bookList)
        } else {
          listTemp = [].concat(that.data.list, bookList)
        }
        that.setData({ list: listTemp, pageNo: list.length == pageSize ? pageNo + 1 : pageNo, isAll: list.length < pageSize }) 
      }
      cb && cb(res)
    }).catch(res => {
      cb && cb(res)
    })
  },

  /**
   * 输入搜索值
   */
  inputSearchCtl: function (e) {
    const { value } = e.detail
    const { content } = this.data
    if (content == value) {
      return
    }
    // var contentList = wx.getStorageSync('contentList')||[];
    // contentList.unshift(content)
    // wx.setStorageSync('contentList', contentList)
    this.setData({ content: value, pageNo: 1,isRecord:false})
    this.getData()
  },

  /**
   * 清除搜索值
   */
  clearSearchCtl: function () {
    this.setData({ content: '' })
  },

  /**
   * 提交搜索值
   */
  submitSearchCtl: function () {
    this.setData({ isReturn: 1, pageNo: 1 })
    this.getData()
  },
   /**
   * 删除
   */
  deleteTips:function(){
    const continuousFn = { fn: this.deleteTips, param: { ...arguments } }
    ClearSearchHis({ data: {}, continuousFn }).then(res => {
      wx.showToast({
        title: '删除成功'
      })
      this.setData({ contentList: [] })
    })
    
  },

  /**
   * 展示选择框
   */
  showItemCtl: function () {
    const { isShow } = this.data
    if (isShow) {
      return
    }
    this.setData({ isShow: 1 })
  },

  /**
  * 展示选择框
  */
  selectItemCtl: function (e) {
    const { index } = e.currentTarget.dataset
    const { itemIndex, items } = this.data
    if (index == itemIndex) {
      return
    }
    this.setData({ itemIndex: index, isShow: 0, pageNo: 1 })
    this.getData()
  },

  /**
   * 借阅 预约 加入心愿单
   */
  submitCtl: function (e) {
    const continuousFn = { fn: this.submitCtl, param: { ...arguments } }
    if (!hasVipService() || !hasLibraryService()) return
    const { type, number } = e.currentTarget.dataset
    const { vipId, libId } = this.data.options
    AddWishBooks({ data: { isbn13: number, libId, type, vipId }, continuousFn }).then(res => {
      wx.showToast({
        title: `${type == 1 ? '借阅' : type == 2 ? '加入心愿' : type == 3 ? '预约' : ''}成功`
      })
      this.getData()

    })
  }
})