// pages/user/my_comment/index.js
const { noCollectionImg } = require('../../../utils/images');
const {
  request,
  serverName
} = require('../../../utils/services');
const {
  newRequestFns,
  newServerName
} = require('../../../utils/newServices.js');
const {
  defaultImg,
  noExhibitionImg
} = require('../../../utils/images');

const {
  Toast
} = require('../../../utils/util.js');
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    testImg: '../../../imgs/testImg/fdkz.png',
    myBrowsed: [],
    noCollectionImg,
    currentPage: 1,
    loading: false,
    hasMore: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      serverName,
      noExhibitionImg,
      defaultImg
    })
    
    // 检查 globalData 是否已有位置信息
    if (app.globalData.latitude && app.globalData.longitude) {
      // 使用 globalData 中的经纬度
      this.setData({
        latitude: app.globalData.latitude,
        longitude: app.globalData.longitude
      });
      
      // 处理 city 设置
      if (app.globalData.locationName) {
        app.globalData.city = app.globalData.locationName;
      } else {
        app.globalData.city = "北京";
      }
      
      this.getBrowsedExhibitions(1);
    } 
    // else {
    //   // 没有位置信息，获取位置
    //   wx.getLocation({
    //     type:'wgs84',
    //     success: (res)=> {
    //       // 保存到 globalData
    //       app.globalData.latitude = res.latitude;
    //       app.globalData.longitude = res.longitude;
          
    //       this.setData({
    //         latitude:res.latitude||0,
    //         longitude:res.longitude||0
    //       })
    //     },
    //     complete:()=>{
    //       this.getBrowsedExhibitions(1)
    //     }
    //   })
    // }

  },
  onPullDownRefresh: function() {
    this.setData({
      myBrowsed: [],
      currentPage: 1,
      hasMore: true
    });
    this.getBrowsedExhibitions(1)
  },
  saveBrowsedExhibitions() {
    let {
      cookieIDs
    } = this.globalData;
    let ids = undefined;
    console.log(this.globalData)
    if (cookieIDs) {
      ids = cookieIDs.join(",") || undefined;
    } else {
      return
    }
    let loginSessionKey = wx.getStorageSync("token") || "";

    if (loginSessionKey) {
      newRequestFns["saveBrowsedExhibitions"]({
          ids: ids,
          loginSessionKey
        }, "", res => {
          if (res) {
            this.getBrowsedExhibitions(1)
          }
        }, err => {

        },
        complete => {

        })
    } else {
      return
    }

  },

  getBrowsedExhibitions: function(page = 1) {
    if (this.data.loading) return;
    
    let loginSessionKey = wx.getStorageSync("token") || "";
    // let ids = undefined;
    // console.log(app.globalData)
    // if (app.globalData.cookieIDs) {
    //   if (app.globalData.cookieIDs.length > 9) {
    //     app.globalData.cookieIDs = app.globalData.cookieIDs.slice(0, 10)
    //     // console.log(cookieIDs)

    //   }
    //   console.log(app.globalData.cookieIDs.join(","))

    //   for (let i = 0; i < app.globalData.cookieIDs.length;i++){
    //     if (app.globalData.cookieIDs[i] =='undefined'){
    //       app.globalData.cookieIDs.splice(i,1);
    //     }
    //   }
    //   ids = app.globalData.cookieIDs.join(",") || "";
      
    //   // console.log("asdasdas",ids)
    // } else {
    //   return
    // }
    
    this.setData({
      loading: true
    });
    
    let {latitude:lat,longitude:lng} = this.data
    newRequestFns["getTrace"]({
        pageNo: page,
        lat,
        lng,
        loginSessionKey
      }, "", res => {
        if (res.data.code > -1) {
          let newTraceData = res.data.data ? res.data.data.pageData : [];
          
          // 处理数据，添加detailType字段
          if (newTraceData && newTraceData.length > 0) {
            newTraceData.forEach(item => {
              // 根据业务逻辑设置detailType，这里假设根据某个字段判断
              // 如果有specific字段来区分展会和文物，请根据实际情况修改
              item.detailType = item.detailType || 1; // 默认为展会类型
            });
          }
          console.log(newTraceData, 999)
          let updatedMyBrowsed;
          if (page === 1) {
            // 第一页，直接替换
            updatedMyBrowsed = newTraceData || [];
          } else {
            // 后续页面，追加数据
            updatedMyBrowsed = [...this.data.myBrowsed, ...(newTraceData || [])];
          }
          
          // 判断是否还有更多数据
          let hasMore = newTraceData && newTraceData.length > 0;
          
          this.setData({
            myBrowsed: updatedMyBrowsed,
            currentPage: page,
            hasMore: hasMore,
            loading: false
          })
          console.log(updatedMyBrowsed, updatedMyBrowsed, 777)
        } else {
          this.setData({
            loading: false,
            hasMore: false
          });
        }

      }, err => {
        this.setData({
          loading: false
        });
      },
      complete => {
        wx.stopPullDownRefresh();
      })
  },

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

  },

  _getExhibitionsByIds() {

  },

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


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

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

      }
      this.setData({
        myBrowsed,

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

  },

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

  },

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

  },



  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (this.data.loading || !this.data.hasMore) return;
    this.getBrowsedExhibitions(this.data.currentPage + 1);
  },

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

  }
})