import Toast from 'tdesign-miniprogram/toast/index';
import { getCloudImageTempUrl,getSingleCloudImageTempUrl } from '../../../utils/cloudImageHandler';
import { getCates,getSwipe } from '../../../services/cate/cate';

Page({
  data: {
    cates: [],
   // cateId: '1', // 初始化为字符串类型
    imgSrcs: [],
    current: 1,
    autoplay: false,
    navigation: { type: 'dots' },
    swiperImageProps: { mode: 'aspectFill' },
    swiperHeight: 400 
  },
  async init() {
    try {
      console.log("开始初始化分类数据...");
      const cates = await getCates();
      this.setData({ cates });
      console.log("分类数据设置完成");
    } catch (e) {
      console.error('获取商品分类列表失败', e);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '获取商品分类列表失败',
        duration: 1000,
        icon: '',
      });
    }
  },

  onShow() {
    this.getTabBar().init();
  },
  onChange(e) {
    console.log("完整事件对象:", JSON.stringify(e, null, 2));
    // 更健壮的ID获取逻辑，增强对各种可能数据结构的支持
    let cateId;
    
    // 检查多个可能的来源，增加对直接ID的检查
    if (e?.detail?.item?._id) {
      cateId = e.detail.item._id;
    } else if (e?.detail?.id) {
      cateId = e.detail.id;
    } else if (e?.currentTarget?.dataset?.item?._id) {
      cateId = e.currentTarget.dataset.item._id;
    } else if (e?.detail?._id) {
      cateId = e.detail._id;
    } else if (e?._id) {
      cateId = e._id;
    }
    
    console.log("获取到的分类ID:", cateId);
    
    if (!cateId) {
      console.error("未能获取到有效的分类ID", { eventStructure: Object.keys(e || {}), detailKeys: Object.keys(e?.detail || {}) });
      Toast({
        context: this,
        selector: '#t-toast',
        message: '获取分类信息失败',
        duration: 1000,
        icon: '',
      });
      return;
    }
    
    // 确保是字符串类型
    const stringCateId = String(cateId);
    //this.setData({cateId: stringCateId});
    
    // 确保导航时使用正确的参数
    wx.navigateTo({
      url: `/pages/goods/list/index?cateId=${encodeURIComponent(stringCateId)}`,
    });
  },
  onLoad() {
    this.init(true);
    this.loadSwiper();
  },

  async loadSwiper() {
    try {
      const { images } = await getSwipe();
      console.log("获取到的轮播图数据:", images);
      
      // 确保images是数组格式
      let handledImages = [];
      if (Array.isArray(images)) {
        // 如果是本地模拟环境，可以直接使用images数组
        if (this.data.useMock) {
          handledImages = images;
        } else {
          // 如果是实际环境，需要处理云存储图片URL
          handledImages = await getCloudImageTempUrl(images);
        }
      }
      console.log("handledImages:",handledImages);
      this.setData({ imgSrcs: handledImages });
    } catch (error) {
      console.error("加载轮播图失败:", error);
    }
  },

});
