// pages/exhibition/index.js
const { museumApi } = require('../../utils/api.js');
const { navigateToWebview, urlImg } = require('../../utils/util.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    selectedType: 0, // 当前选中的类型：0-全部，1-室内，2-室外
    carouselList: [], // 轮播图数据
    carouselRenderList: [], // 组件使用的渲染列表
    carouselCurrent: 0,
    showCarouselIndicators: false,
    exhibitionList: [], // 展览列表数据
    loading: false, // 加载状态
    hasMore: true, // 是否还有更多数据
    currentPage: 1, // 当前页码
    pageSize: 10, // 每页数量
    urlImg: urlImg
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initData();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1,
        isShowTabar: true
      })
    }
  },

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.loadMore();
  },

  // 初始化数据
  async initData() {
    await this.getCarouselData();
    await this.getExhibitionList(false);
    wx.stopPullDownRefresh();
  },

  // 获取轮播图数据（type为0的前5条）
  async getCarouselData() {
    try {
      const response = await museumApi.getExhibitionList({
        pageNum: 1,
        pageSize: 5,
        type: 0,
        status: 1,
        recommend: 1
      });
      if (response && response.records) {
        const list = response.records || [];
        // 组件需要 image/url 两字段
        const renderList = list.map(item => ({
          image: urlImg + item.img,
          url: item.webSite || '',
          raw: item
        }));
        this.setData({
          carouselList: list,
          carouselRenderList: renderList
        });
      }
    } catch (error) {
      console.error('获取轮播图数据失败:', error);
    }
  },

  // 获取展览列表数据
  async getExhibitionList(isLoadMore = false) {
    if (this.data.loading) return;

    this.setData({ loading: true });

    try {
      const response = await museumApi.getExhibitionList({
        pageNum: isLoadMore ? this.data.currentPage : 1,
        pageSize: this.data.pageSize,
        type: this.data.selectedType
      });

      if (response && response.records) {
        let exhibitionList;
        if (isLoadMore) {
          // 加载更多，追加数据
          exhibitionList = [...this.data.exhibitionList, ...response.records];
        } else {
          // 重新加载，替换数据
          exhibitionList = response.records;
          this.setData({ currentPage: 1 });
        }

        this.setData({
          exhibitionList: exhibitionList,
          hasMore: response.records.length === this.data.pageSize
        });

        if (isLoadMore) {
          this.setData({
            currentPage: this.data.currentPage + 1
          });
        }
      }
    } catch (error) {
      console.error('获取展览列表失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 选择分类
  async selectCategory(e) {
    const type = e.currentTarget.dataset.type;
    if (this.data.selectedType === type) return;

    this.setData({
      selectedType: type,
      currentPage: 1,
      hasMore: true
    });

    // 重新获取列表数据
    await this.getExhibitionList(false);
  },

  // 加载更多
  async loadMore() {
    if (!this.data.hasMore || this.data.loading) return;
    await this.getExhibitionList(true);
  },

  // 展览项点击事件
  onExhibitionTap(e) {
    const item = e.currentTarget.dataset.item;
    this.goToDetail(item.exhibitId);
  },

  // 线上观展点击事件
  onOnlineExhibitionTap(e) {
    // e.stopPropagation(); // 阻止事件冒泡
    const webSite = 'https://www.4dmodel.com/SuperTwoCustom/KLMYscene/?m=SG-alDn3FU4jQ8';
    if (webSite) {
      console.log('跳转到webSite:', webSite);
      navigateToWebview(webSite,'open');
    } else {
      // this.goToDetail(item.exhibitId);
      console.log('webSite为空');
    }
  },

  // 组件：指示器/滑动变更
  onCarouselChange(e) {
    const { current } = e.detail || {};
    this.setData({ carouselCurrent: current });
  },

  // 组件：当前项（无 url）点击
  onExhibitionTapFromCarousel(e) {
    const { item } = e.detail || {};
    const raw = item && item.raw;
    if (raw && raw.exhibitId) {
      this.goToDetail(raw.exhibitId);
    }
  },

  // 组件：线上观展点击
  onOnlineExhibitionTapFromCarousel(e) {
    const { url } = e.detail || {};
    if (url) {
      console.log('跳转到线上观展:', url);
      navigateToWebview(url, 'open');
    } else {
      console.log('webSite为空');
    }
  },

  // 跳转到详情页面
  goToDetail(id) {
    navigateToWebview(`/allDetailsShow?isFrom=weixin&id=${id}&type=exhibition`);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '克拉玛依博物馆 - 展览',
      path: '/pages/exhibition/index'
    };
  },

  /**
   * 用户点击右上角分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: '克拉玛依博物馆 - 精彩展览等你来看',
      query: '',
      imageUrl: '' // 可以设置自定义分享图片
    };
  }
});