// pages/search/search.js
const { api, alertTip } = require('../../lib/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prevPage:null,
    searchList: []

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let searchType=options.type
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];  //上一个页面
    this.setData({
      searchType,
      prevPage
    })
    this[this.data.searchType]()['search']('')
  },
  apiSearch(e){
    // 触发搜索
    let q=e.detail.value
    this[this.data.searchType]()['search'](q)
  },
  resultSelect(e) {
    // 选择结果
    let sItem=e.currentTarget.dataset.values
    this[this.data.searchType]()['result'](sItem)
  },
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },
  companyByName(){
    let that=this
    return {
      search(companyName){
        api.get('site/getByCompanyByName', { companyName})
          .then(({ items }) => {
            let newItems=items.map(item=>{
              item.itemName = item.province +'--'+ item.companyName
              return item
            })
            that.setData({
              searchList: newItems
            })
          })
          .catch(err => {
            alertTip(err)
          })
      },
      result(sItem){
        that.data.prevPage.setData({
          companyName: sItem.companyName,
          companyId: sItem.id,
          pointName: '',
          pointId: null,//二级网点
        })
        wx.navigateBack()
      }

    }
  },
  //网点
  byCompanyId(){
    let that = this
    return {
      search(companyName) {
        api.get('site/getByCompanyIdAndCompanyName', { companyId: that.data.prevPage.data.companyId, companyName })
          .then(({ items }) => {
            let newItems = items.map(item => {
              item.itemName = item.province + '--' + item.companyName
              return item
            })
            that.setData({
              searchList: newItems
            })
          })
          .catch(err => {
            alertTip(err)
          })
      },
      result(sItem) {
        that.data.prevPage.setData({
          pointName: sItem.companyName,
          pointId: sItem.id
        })
        wx.navigateBack()
      }

    }
  }
})