// pages/zhanxun/index.js
const { request, serverName, imgServer } = require('../../utils/services');
const {
  newRequestFns,
  newServerName
} = require('../../utils/newServices.js');
const { Toast, qqmapsdk } = require('../../utils/util.js');
const { defaultImg, noExhibitionImg } = require('../../utils/images');
const WxParse = require('../../common/component/wxParse/wxParse.js');
const app = getApp();

const distItems = [
  {
    name: '按距离排序',
    id: '距离排序',
    idx: 1
  },
  {
    name: '按热度排序',
    id: '热度排序',
    idx: 2
  }
]
const typeItems = [
  {
    name: '展览中',
    id: '展览中',
    idx: 1
  },
  {
    name: '即将开始',
    id: '即将开始',
    idx: 2
  },
  {
    name: '已结束',
    id: '已结束',
    idx: 3
  },
  {
    name: '全部状态',
    id: '全部状态',
    idx: 0
  }
]

Page({
  data: {
    tabs: ['线上看展', '线下展讯'],
    activeIndex: 0,
    loading: false,
    imgServer,
    defaultImg,
    noExhibitionImg,
    // 线上看展数据
    onlineExhibitionList: [],
    onlineCurrentPage: 1,
    onlineLastPage: false,
    onlineLikes: {},
    // 线下展讯数据
    offlineExhibitionList: [],
    offlineCurrentPage: 1,
    offlineLastPage: false,
    navItem: distItems,
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    locationName: "北京",
    locationNameDesp: "",
    isLike: false,
    showConfirm: false,
    tag: "",
    commodityImgs: [
      '../../imgs/testImg/thumbSmallImg.jpg',
      '../../imgs/testImg/thumbSmallImg.jpg',
    ],
    type: 5,
    testImg: '../../imgs/testImg/fdkz.png',
    getLocationBtn: false,
    isShow: false,
    exhiNum: 0,
    activeDist: '距离排序',
    activeType: '展览中'
  },

  onLoad: function () {
    this.setData({
      serverName,
      defaultImg,
      noExhibitionImg,
      imgServer
    });
    // 检查 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.getLocationName(); 初始进来不在获取位置信息
    // 初始加载线上看展数据
    this.getOnlineExhibitionList(1);
  },

  tabClick: function (e) {
    const index = e.currentTarget.id;
    this.setData({
      activeIndex: index
    });
    
    // 切换到线上看展
    if (index == 0) {
      if (this.data.onlineExhibitionList.length === 0) {
        this.getOnlineExhibitionList(1);
      }
    } 
    // 切换到线下展讯
    else {
      if (this.data.offlineExhibitionList.length === 0) {
        this.getOfflineExhibitionList(1);
      }
    }
  },

  // 获取线上看展数据
  getOnlineExhibitionList: function (page) {
    this.setData({
      loading: true
    });
    
    newRequestFns["getExhibitionList"]({
      page: page,
      type: 1 // 线上看展类型
    }, '', res => {
      let tempContent = this.data.onlineExhibitionList || [];
      let { pageData: exhibitionList, total } = res.data.data;
      
      // 判断是否为最后一页（返回空数组表示没有更多数据）
      let isLastPage = !exhibitionList || exhibitionList.length === 0;

      if (isLastPage) {
        this.setData({
          loading: false,
          onlineLastPage: true // 标记为最后一页
        });
        return;
      }
      
      exhibitionList.forEach((currentValue) => {
        currentValue.product ? currentValue.product.link = escape(currentValue.product.link) : '';
        currentValue.product ? currentValue.product.imageUrl = escape(currentValue.product.imageUrl) : '';
        
        // 处理状态标签逻辑
        if (!currentValue.statusText && currentValue.endTime) {
          // 如果没有 statusText，根据 endTime 判断是否已结束
          const today = new Date();
          const endDate = new Date(currentValue.endTime);
          
          // 将日期设置为当天的开始时间进行比较
          today.setHours(0, 0, 0, 0);
          endDate.setHours(0, 0, 0, 0);
          
          if (endDate < today) {
            currentValue.statusText = '已结束';
            currentValue.isExpired = true;
          }
        } else if (currentValue.statusText === '热门') {
          currentValue.isHot = true;
        }
      });
      
      // 拼接新数据
      let newOnlineExhibitionList = page === 1 ? exhibitionList : tempContent.concat(exhibitionList);
      
      this.setData({
        onlineCurrentPage: page,
        onlineLastPage: false, // 有数据时设为false
        loading: false,
        onlineExhibitionList: newOnlineExhibitionList,
      });
      
      wx.stopPullDownRefresh();
    }, err => {
      this.setData({
        loading: false
      });
    });
  },

  // 获取线下展讯数据
  getOfflineExhibitionList: function (page) {
    let { locationName, activeDist, activeType } = this.data;
    let loginSessionKey = wx.getStorageSync("token");
    let sort = distItems.find(item => item.id === activeDist).idx;
    let type = typeItems.find(item => item.id === activeType).idx;
    
    this.setData({
      loading: true
    });
    
    newRequestFns["getExhibitionListOffline"]({
      page: page,
      loginSessionKey,
      city: locationName,
      sort: sort,
      type: type,
      lng: this.data.longitude,
      lat: this.data.latitude,
    }, '', res => {
      let tempContent = this.data.offlineExhibitionList || [];
      let { pageData: exhibitionList, total } = res.data.data;
      
      // 判断是否为最后一页（返回空数组表示没有更多数据）
      let isLastPage = !exhibitionList || exhibitionList.length === 0;

      if (isLastPage) {
        this.setData({
          loading: false,
          offlineLastPage: true, // 标记为最后一页
          exhiNum: total || 0
        });
        wx.stopPullDownRefresh();
        if (total <= 3) {
          this.offlineRecommend();
        }
        return;
      }
      
      exhibitionList.forEach((currentValue) => {
        currentValue.product ? currentValue.product.link = escape(currentValue.product.link) : '';
        
        // 处理状态标签逻辑
        if (!currentValue.statusText && currentValue.endTime) {
          // 如果没有 statusText，根据 endTime 判断是否已结束
          const today = new Date();
          const endDate = new Date(currentValue.endTime);
          
          // 将日期设置为当天的开始时间进行比较
          today.setHours(0, 0, 0, 0);
          endDate.setHours(0, 0, 0, 0);
          
          if (endDate < today) {
            currentValue.statusText = '已结束';
            currentValue.isExpired = true;
          }
        } else if (currentValue.statusText === '热门') {
          currentValue.isHot = true;
        }
      });
      
      // 拼接新数据
      let newOfflineExhibitionList = page === 1 ? exhibitionList : tempContent.concat(exhibitionList);
      
      this.setData({
        offlineCurrentPage: page,
        offlineLastPage: false, // 有数据时设为false
        loading: false,
        offlineExhibitionList: newOfflineExhibitionList,
        exhiNum: total
      });
      
      wx.stopPullDownRefresh();
      
      if (total <= 3) {
        this.offlineRecommend();
      }
    }, err => {
      this.setData({
        loading: false
      });
    });
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    if (this.data.activeIndex == 0) {
      this.setData({
        onlineExhibitionList: [],
        onlineCurrentPage: 1
      });
      this.getOnlineExhibitionList(1);
    } else {
      this.setData({
        offlineExhibitionList: [],
        offlineCurrentPage: 1
      });
      this.getOfflineExhibitionList(1);
    }
  },

  // 上拉加载更多
  onReachBottom: function () {
    if (this.data.loading) return;
    
    if (this.data.activeIndex == 0) {
      if (!this.data.onlineLastPage) {
        this.getOnlineExhibitionList(this.data.onlineCurrentPage + 1);
      }
    } else {
      if (!this.data.offlineLastPage) {
        this.getOfflineExhibitionList(this.data.offlineCurrentPage + 1);
      }
    }
  },

  // 收藏/取消收藏展览
  addLike: function (e) {
    let { type, id, idx, listType } = e.currentTarget.dataset;
    let exhibitionList = listType === 'online' ? this.data.onlineExhibitionList : this.data.offlineExhibitionList;
    let { collectedArr } = app.globalData;
    let hasItem = true;

    if (listType === 'online') {
      let onlineLikes = this.data.onlineLikes;
      onlineLikes[id] = !onlineLikes[id];
      this.setData({
        onlineLikes: onlineLikes
      });
    }

    Toast.showToast2('loading');

    let loginSessionKey = wx.getStorageSync('token') || "";
    newRequestFns['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) {
            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;
        
        if (listType === 'online') {
          this.setData({
            onlineExhibitionList: exhibitionList
          });
        } else {
          this.setData({
            offlineExhibitionList: exhibitionList
          });
        }
      }
    }, err => {
      // 错误处理
    }, complete => {
      Toast.hideLoading();
    });
  },
  
  // 获取位置名称
  // getLocationName: function() {
  //   console.log(11111)
  //   wx.getLocation({
  //     type: 'wgs84',
  //     success: (res) => {
  //       this.setData({
  //         latitude: res.latitude,
  //         longitude: res.longitude
  //       });
  //       console.log(res, 22222)
  //       qqmapsdk.reverseGeocoder({
  //         location: {
  //           latitude: res.latitude,
  //           longitude: res.longitude
  //         },
  //         success: (res) => {
  //           let { city: locationName } = res.result.address_component;
  //           console.log(locationName, 'locationName')
  //           locationName = locationName.substring(0, 2);
  //           app.globalData.city = locationName;
            
  //           this.setData({
  //             locationName,
  //             locationNameDesp: locationName
  //           });
  //         },
  //         fail: function (res) {
  //           this.setData({
  //             locationName: ""
  //           });
  //         }
  //       });
  //     },
  //     fail: () => {
  //       console.log(33333)
  //       this.setData({
  //         getLocationBtn: true
  //       });
  //     }
  //   });
  // },
  
  // 线下推荐
  offlineRecommend: function () {
    // wx.getLocation({
    //   type: 'wgs84',
    //   success: (res) => {
    //     this.setData({
    //       latitude: res.latitude,
    //       longitude: res.longitude
    //     });
    //   }
    // });
    
    let { latitude: lat, longitude: lng } = this.data;
    newRequestFns["offlineRecommend"]({
      lat,
      lng,
    }, "", res => {
      this.setData({
        ExhibitionPopular: res.data.data
      });
    }, err => {
      // 错误处理
    });
  },
  
  // 前往搜索页面
  to_search: function() {
    // 检查 globalData 是否已有位置信息
    if (app.globalData.latitude && app.globalData.longitude && app.globalData.locationName) {
      // 已有位置信息，直接跳转
      wx.navigateTo({
        url: '../tongcheng/search/index'
      });
      return;
    }

    // 没有位置信息，显示弹窗
    wx.showModal({
      title: '获取你的位置信息',
      content: '将获取你的具体位置信息，用于推荐你所在定位附近的展览',
      confirmText: '同意',
      cancelText: '拒绝',
      success: (res) => {
        if (res.confirm) {
          // 用户点击同意，获取位置信息
          wx.getLocation({
            type: 'wgs84',
            success: (locationRes) => {
              // 设置坐标到 globalData 和页面数据
              app.globalData.latitude = locationRes.latitude;
              app.globalData.longitude = locationRes.longitude;
              this.setData({
                latitude: locationRes.latitude,
                longitude: locationRes.longitude
              });
              
              // 使用腾讯地图逆地址解析获取城市名称
              qqmapsdk.reverseGeocoder({
                location: {
                  latitude: locationRes.latitude,
                  longitude: locationRes.longitude
                },
                success: (geoRes) => {
                  let { city: locationName } = geoRes.result.address_component;
                  locationName = locationName.substring(0, 2);
                  
                  // 保存到 globalData
                  app.globalData.city = locationName;
                  app.globalData.locationName = locationName;
                  
                  this.setData({
                    locationName,
                    locationNameDesp: locationName
                  });
                  // 获取当前城市的展览列表
                  this.getOfflineExhibitionList(1);
                  // 获取位置成功，跳转到搜索页面
                  wx.navigateTo({
                    url: '../tongcheng/search/index'
                  });
                },
                fail: (geoErr) => {
                  // 逆地址解析失败，使用默认城市（北京），直接跳转
                  app.globalData.city = "北京";
                  app.globalData.locationName = "北京";
                  this.setData({
                    locationName: "北京"
                  });
                  wx.navigateTo({
                    url: '../tongcheng/search/index'
                  });
                }
              });
            },
            fail: (locationErr) => {
              // 获取位置失败，保持默认城市（北京），直接跳转
              console.log('获取位置失败:', locationErr);
              app.globalData.city = "北京";
              app.globalData.locationName = "北京";
              this.setData({
                getLocationBtn: true,
                locationName: "北京"
              });
              wx.navigateTo({
                url: '../tongcheng/search/index'
              });
            }
          })
        } else if (res.cancel) {
          // 用户点击拒绝，保持默认城市（北京），直接跳转
          app.globalData.city = "北京";
          app.globalData.locationName = "";
          wx.navigateTo({
            url: '../tongcheng/search/index'
          });
        }
      },
      fail: function (res) {
        // 弹窗失败，直接跳转
        wx.navigateTo({
          url: '../tongcheng/search/index'
        });
      }
    })
  },
  
  // 展览搜索
  to_search_exhibition: function () {
    wx.navigateTo({
      url: '../yuezhan/search/index'
    });
  },
  
  // 显示下拉菜单
  showDrop: function(e) {
    let tag = e.target.dataset.id;
    let name = e.target.dataset.test;
    
    if (tag === 'type') {
      this.setData({
        navItem: {
          type: tag,
          name: name,
          arr: typeItems
        },
        isShow: !this.data.isShow
      });
    } else {
      this.setData({
        navItem: {
          type: tag,
          name: name,
          arr: distItems
        },
        isShow: !this.data.isShow
      });
    }
  },
  
  // 关闭下拉菜单
  onIsclose: function(e) {
    this.setData({
      isShow: e.detail
    });
  },
  
  // 选择下拉菜单项
  getActiveItem: function(e) {
    let { activeDist, activeType } = e.detail;
    
    this.setData({
      activeDist,
      activeType,
      offlineExhibitionList: []
    });
    
    this.getOfflineExhibitionList(1);
  },
  
  // 关闭确认对话框
  closeDialog: function() {
    this.setData({
      showConfirm: false
    });
  },
  
  // 获取附近列表
  getNearByList: function (page) {
    let { locationName, latitude, longitude } = this.data;
    let loginSessionKey = wx.getStorageSync("token");
    console.log(locationName, latitude, longitude, 666)
    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.userLocation']) {
          Toast.showToast('tip', "无法获取用户位置", () => {
            return;
          });
          this.setData({
            getLocationBtn: true
          });
        } else {
          this.setData({
            loading: true,
            getLocationBtn: false
          });
          
          if (!longitude && !latitude) {
            wx.getLocation({
              success: res => {
                let longitude = res.longitude;
                let latitude = res.latitude;
                
                newRequestFns["getNearByList"]({
                  page: page,
                  loginSessionKey,
                  city: locationName,
                  lng: longitude,
                  lat: latitude
                }, '', res => {
                  let tempContent = this.data.offlineExhibitionList || [];
                  let { pageData: exhibitionList, total } = res.data.data;

                                     // 判断是否为最后一页（返回空数组表示没有更多数据）
                   let isLastPage = !exhibitionList || exhibitionList.length === 0;

                   if (isLastPage) {
                     this.setData({
                       loading: false,
                       offlineLastPage: true
                     });
                     wx.stopPullDownRefresh();
                     return;
                   }

                   // 拼接新数据
                   let newExhibitionList = page === 1 ? exhibitionList : tempContent.concat(exhibitionList);

                   this.setData({
                     offlineCurrentPage: page,
                     offlineLastPage: false, // 有数据时设为false
                     loading: false,
                     longitude,
                     latitude,
                     offlineExhibitionList: newExhibitionList,
                   });
                  
                  wx.stopPullDownRefresh();
                }, err => {
                  // 错误处理
                });
              }
            });
          } else {
            newRequestFns["getNearByList"]({
              page: page,
              loginSessionKey,
              city: locationName,
              lng: longitude,
              lat: latitude
            }, '', res => {
              let tempContent = this.data.offlineExhibitionList || [];
              let { pageData: exhibitionList, total } = res.data.data;

                             // 判断是否为最后一页（返回空数组表示没有更多数据）
               let isLastPage = !exhibitionList || exhibitionList.length === 0;

               if (isLastPage) {
                 this.setData({
                   loading: false,
                   offlineLastPage: true
                 });
                 wx.stopPullDownRefresh();
                 return;
               }

               // 拼接新数据
               let newExhibitionList = page === 1 ? exhibitionList : tempContent.concat(exhibitionList);

               this.setData({
                 offlineCurrentPage: page,
                 offlineLastPage: false, // 有数据时设为false
                 loading: false,
                 offlineExhibitionList: newExhibitionList,
               });
              
              wx.stopPullDownRefresh();
            }, err => {
              // 错误处理
            });
          }
        }
      }
    });
  },
  
  onShow: function() {
    let { city, clickToSelect, collectedArr, collectedChange } = app.globalData;
    
    if (clickToSelect) {
      this.setData({
        locationName: city || "北京",
        offlineExhibitionList: [],
        offlineCurrentPage: 1
      });
      
      if (this.data.activeIndex == 1) {
        this.getOfflineExhibitionList(1);
      }
    }
    
    if (collectedChange) {
      // 更新线上看展收藏状态
      if (this.data.onlineExhibitionList.length > 0) {
        let onlineExhibitionList = this.data.onlineExhibitionList;
        for (let i = 0; i < onlineExhibitionList.length; i++) {
          for (let j = 0; j < collectedArr.length; j++) {
            if (collectedArr[j].collectedId == onlineExhibitionList[i].id) {
              onlineExhibitionList[i].hasCollect = collectedArr[j].status;
              if (onlineExhibitionList[i].hasCollect) {
                onlineExhibitionList[i].collectionsCount += 1;
              } else {
                onlineExhibitionList[i].collectionsCount -= 1;
              }
              if (onlineExhibitionList[i].collectionsCount < 0) {
                onlineExhibitionList[i].collectionsCount = 0;
              }
            }
          }
        }
        this.setData({ onlineExhibitionList });
      }
      
      // 更新线下展讯收藏状态
      if (this.data.offlineExhibitionList.length > 0) {
        let offlineExhibitionList = this.data.offlineExhibitionList;
        for (let i = 0; i < offlineExhibitionList.length; i++) {
          for (let j = 0; j < collectedArr.length; j++) {
            if (collectedArr[j].collectedId == offlineExhibitionList[i].id) {
              offlineExhibitionList[i].hasCollect = collectedArr[j].status;
              if (offlineExhibitionList[i].hasCollect) {
                offlineExhibitionList[i].collectionsCount += 1;
              } else {
                offlineExhibitionList[i].collectionsCount -= 1;
              }
              if (offlineExhibitionList[i].collectionsCount < 0) {
                offlineExhibitionList[i].collectionsCount = 0;
              }
            }
          }
        }
        this.setData({ offlineExhibitionList });
      }
    }
    
    app.globalData.clickToSelect = false;
    app.globalData.collectedChange = false;
  },
  
  onShareAppMessage: function () {
    // 分享功能
  }
})