// pages/yuezhan/search/index.js
const { request, serverName, imgServer } = require('../../../utils/services');
const { Toast } = require('../../../utils/util');
const { defaultImg, noExhibitionImg, noExhibitionHallImg } = require('../../../utils/images');

const app = getApp();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: ['展览', '展馆'],
    testImg: '../../../imgs/testImg/thumbSmallImg2.jpg',
    avatar: '../../../imgs/testImg/1.jpg',
    activeIndex:0,
    animationData: "",
    isLike:false,
    loading:false,
    currentPage:1,
    exhibitionList:[],
    pavilionList:[],
    totalElements:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      searchText: options.searchText,
      serverName,
      imgServer
    });
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        this.setData({
          latitude: res.latitude||0,
          longitude: res.longitude||0
        })
      },
      complete:()=>{
        this.loadData()
      }
    })
    // this.getKeywordCode()
    
    this.setData({
      noExhibitionImg,
      noExhibitionHallImg,
      defaultImg
    })

  },

  keywordSearch:function(e){
    let { keyword } = e.currentTarget.dataset;
    this.setData({
      searchText: keyword
    })
    console.log("s",e)
    this.loadData();
  },

  getKeywordCode:function(){
    request["getKeywordCode"]({}, "", res => {
      if (res.data.code > -1) {
        let {data:keyword} = res.data;
        this.setData({
          keyword
        })
        wx.stopPullDownRefresh();
        console.log(res)
      }
    }, err => {

    }, complete => {

    })
  },

  loadData: function () {
    // 通过activeIndex 判断应该load哪部分的数据
    const { activeIndex } = this.data;
    this.setData({
      exhibitionList: [],
      pavilionList: []
    });
    if (activeIndex == 0) {
      this.getExhibitionSearch(1);
      if (this.data.exhibitionList.length < 5){
        this.popular();
      }
    }
    else if (activeIndex == 1) {
      this.getPavilionSearch(1);
    }
    else {
      return
    }
  },

  addLike: function (e) {
    let { type, id, idx } = e.currentTarget.dataset;
    console.log(idx, type, id)
    let { collectedArr, collectedChange } = app.globalData, hasItem = true;

    let exhibitionList = this.data.exhibitionList;

    console.log('type', type)

    Toast.showToast2('loading');

    let loginSessionKey = wx.getStorageSync('token') || "";
    // if (loginSessionKey){
    request['isCollect']({
      loginSessionKey,
      exhibitionId: id,
      type: Number(type),
    }, "post", res => {
      if (res.data.code > -1) {
        for (let i = 0; i < collectedArr.length; i++) {
          if (collectedArr[i].collectedId && id == collectedArr[i].collectedId) {
            console.log("true")
            collectedArr[i] = {
              collectedId: id,
              status: res.data.data.hasCollect,
            }
            hasItem = false;
          }
        }
        if (hasItem) {
          collectedArr.push({
            collectedId: id,
            status: res.data.data.hasCollect,
          })
        }

        app.globalData.collectedArr = collectedArr;
        app.globalData.collectedChange = true;
        exhibitionList[idx].hasCollect = res.data.data.hasCollect
        this.setData({
          exhibitionList: exhibitionList
        })
      }

    }, err => {

    }, complete => {
      Toast.hideLoading();
    })
    // }

    console.log(this.data.exhibitionList)
  },

  getExhibitionSearch:function(page){
    let name = this.data.searchText||"";
    this.setData({
      loading: true
    })
    let { latitude: lat, longitude: lng } = this.data;

    request["getExhibitionSearch"]({
      name,
      lat,
      lng,
      page
    },"",res=>{
      if(res.data.code>-1){
        let tempContent = this.data.exhibitionList
          ? this.data.exhibitionList
          : [];
        let { last: lastPage, totalPages, content: exhibitionList } = res.data.data;

        exhibitionList.forEach((currentValue) => {
          currentValue.distance = Math.ceil(currentValue.distance);
          currentValue.product ? currentValue.product.link = escape(currentValue.product.link) : '';
        })

        this.setData({
          currentPage: res.data.data.number+1,
          lastPage,
          loading: false,
          exhibitionList: tempContent.concat(exhibitionList),
          totalElements: res.data.data.totalElements
        });
        console.log(exhibitionList)
        wx.stopPullDownRefresh();
        console.log(res)
      }
    },err=>{
      
    }, complete => {

    })
  },

  getPavilionSearch: function (page) {
    let name = this.data.searchText || "";
    this.setData({
      loading: true
    })
    let { latitude: lat, longitude: lng } = this.data;

    request["getPavilionSearch"]({
      name,
      lat,
      lng,
      page
    }, "", res => {
      if (res.data.code > -1) {
        let tempContent = this.data.pavilionList
          ? this.data.pavilionList
          : [];
        let { last: lastPage, totalPages, content: pavilionList } = res.data.data;

        this.setData({
          currentPage: res.data.data.number+1,
          lastPage,
          loading: false,
          pavilionList: tempContent.concat(pavilionList),
        });
        console.log(pavilionList)
        wx.stopPullDownRefresh();
        console.log(res)
      }
    }, err => {

    }, complete => {

    })
  },

  searchByText: function () {
    this.loadData()
  },

  bindInput: function (event) {
    var obj = {},
      key = event.target.dataset['key'];
    // Toast.showToast('success', event.detail.value);
    obj[key] = event.detail.value;
    this.setData(obj);
    console.log(this.data.searchText)
  },

  loadMore: function () {
    const { activeIndex } = this.data;
    // const loadDataFn =
    //   activeIndex == 0 ? this.loadOneToOrderData : this.loadClassroomData;
    let loadDataFn;
    if ( activeIndex == 0) {
      loadDataFn = this.getExhibitionSearch;
    }
    else if ( activeIndex == 1) {
      loadDataFn = this.getPavilionSearch;
    }
    else {
      return
    }

    if (!this.data.lastPage) {
      this.setData({
        loading: true
      });
      console.log(this.data.currentPage + 1)
      loadDataFn(this.data.currentPage + 1);
    } else {
      return;
    }
  },

  popular : function(){
    let { latitude: lat, longitude: lng } = this.data;

    request["recommend"]({
      lat,
      lng,
    }, "", res => {
      this.setData({
        ExhibitionPopular: res.data.data
      })
    }, err => {

    }, complete => {

    })
  },

  onReachBottom: function () {
    if (!this.data.loading) {
      this.loadMore();
      console.log('reach Bottom');
    }

  },

  tabClick: function (e) {
    let { activeIndex } = this.data;
      this.setData({
        loading: true,
        activeIndex: e.currentTarget.id
      })

      this.loadData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let { collectedArr, collectedChange } = app.globalData;
    let { exhibitionList } = this.data
    let isLogin = app.globalData.isLogin;


    // this.setData({
    //   exhibitionList: []
    // });
    // this.getBanner();
    // this.getList(1);
    this.setData({
      isLogin
    })

    if (collectedChange) {
      for (let i = 0; i < exhibitionList.length; i++) {
        for (let j = 0; j < collectedArr.length; j++) {
          if (collectedArr[j].collectedId == exhibitionList[i].id) {
            exhibitionList[i].hasCollect = collectedArr[j].status
            if (exhibitionList[i].hasCollect) {
              exhibitionList[i].collectionsCount += 1;
            }
            else {
              exhibitionList[i].collectionsCount -= 1;
            }
          }
        }
        // console.log(collectedArr.status, collectedArr.collectedId)

      }
      this.setData({
        exhibitionList,

      })
    }
    // app.globalData.clickToSelect = false;
    // app.globalData.collectedChange = false;

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

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

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.loadData();
  },



  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})