 // pages/yuezhan/search/index.js
const { request, serverName } = require('../../../utils/services');
const { Toast, removeArrItem } = require('../../../utils/util.js');

const { defaultImg, noExhibitionImg, noCollectionImg } = require('../../../utils/images');
const app = getApp();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    testImg: '../../../imgs/testImg/fdkz.png',
    avatar: '../../../imgs/testImg/1.jpg',
    isLike: false,
    likeNum: 526,
    myCollected:[],
    noCollectionImg
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        this.setData({
          latitude: res.latitude||0,
          longitude: res.longitude||0
        })
      },
      complete:()=>{
        this.getCollectedExhibitions()
      }
    })

    this.setData({
      serverName,
      defaultImg,
      noExhibitionImg
    })
  },
  tapToDetail:function(e){
    console.log(e);
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `../../zl_detail/index?id=${id}`,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  onPullDownRefresh: function () {
    this.setData({
      myCollected: [],
    });
    this.getCollectedExhibitions()
  },

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

    console.log('type', type)

    if (type==true){
      wx.showModal({
        title: '提示',
        content: '确定取消收藏吗？',
        showCancel: true,
        cancelText: '关闭',
        cancelColor: '',
        confirmText: '确定',
        confirmColor: '',
        success: res=> {
          if (res.cancel) {
            return;
          }
          if (res.confirm) {
            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;

                myCollected[idx].hasCollect = res.data.data.hasCollect
                this.setData({
                  myCollected: myCollected
                })
              }

            }, err => {

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

            console.log(this.data.myCollected)
          }
        },
        fail: function(res) {},
        complete: function(res) {},
      })
    }else{
      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) {
          console.log("sdwdwd", myCollected[idx].hasCollect);
          console.log('asd', res.data.data.hasCollect)
          myCollected[idx].hasCollect = res.data.data.hasCollect
          this.setData({
            myCollected: myCollected
          })
        }

      }, err => {

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

      console.log(this.data.myCollected)
    }

    
  },

  getCollectedExhibitions:function(){
    let loginSessionKey = wx.getStorageSync("token")||"";
    let { latitude: lat, longitude: lng } = this.data;

    request["collectExhibitions"]({
      lat,
      lng,
      loginSessionKey
    },"",res=>{
      if(res.data.code>-1){
        let { data:myCollected} = res.data;
        for (let i = 0; i <myCollected.length;i++){
          // myCollected[i].createTime =myCollected[i].createTime.substring(5, 10)
        }
        this.setData({
          myCollected
        })
        console.log(myCollected)
      }

    }, err => {

     }, 
    complete=>{
      wx.stopPullDownRefresh();


    })
  },



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

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

    // this.setData({
    //   myCollected: []
    // });
    // this.getBanner();
    // this.getList(1);
    console.log('dwdwasda', isLogin)
    this.setData({
      isLogin
    })

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

      }
      this.setData({
        myCollected,
        
      })
    }

  },

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

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

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

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