
Component({
  externalClasses: ['custom-class'],

  properties: {
    category: {
      type: Array,
      value: [],
      observer: function(newVal) {
        // 确保category始终是数组
        if (!Array.isArray(newVal)) {
          this.setData({ category: [] });
        }
      }
    },
    advertisementImage: {
      type: String,
      value: '',
    },
    currentCateId: {
      type: String,
      value: '',
    },
    initActive: {
      type: Array,
      value: [],
      observer(newVal, oldVal) {
        if (newVal[0] !== oldVal[0]) {
          this.setActiveKey(newVal[0], 0);
        }
      },
    },
    isSlotRight: {
      type: Boolean,
      value: false,
    },
    level: {
      type: Number,
      value: 2,
    },
  },
  data: {
    activeKey: 0,
    subActiveKey: 0
  },
  attached() {
    if (this.properties.initActive && this.properties.initActive.length > 0) {
      this.setData({
        activeKey: this.properties.initActive[0],
        subActiveKey: this.properties.initActive[1] || 0,
      });
    }
  },
  methods: {
    onParentChange(event) {
      this.setActiveKey(event.detail.index, 0).then(() => {
        this.triggerEvent('change', [this.data.activeKey, this.data.subActiveKey]);
      });
    },
    onChildChange(event) {
      this.setActiveKey(this.data.activeKey, event.detail.index).then(() => {
        this.triggerEvent('change', [this.data.activeKey, this.data.subActiveKey]);
      });
    },
    changCategory(event) {
      console.log("组件内部事件对象:", event);
      const { item } = event.currentTarget.dataset;
      console.log("组件传递的item数据:", item);
      
      // 确保传递完整的item对象，包含_id属性
      this.triggerEvent('changeCategory', {
        item,
        id: item?._id // 额外提供id字段，增加数据获取的途径
      });
    },
    setActiveKey(key, subKey) {
      return new Promise((resolve) => {
        this.setData(
          {
            activeKey: key,
            subActiveKey: subKey,
          },
          () => {
            resolve();
          },
        );
      });
    },

  },
});
