// pages/fenlei/fenlei.js
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 全局变量引用
    ossImageUrl: '',
    
    // 搜索相关
    searchText: '',
    showSearchResult: false,
    searchResults: [],
    isSearching: false,
    
    // 页面数据
    shangpinleixing: [],
    shangpinzhuanqu: [],
    shangpinliebiao: [],
    
    // 状态控制
    selectedLeixingId: null,
    selectedZhuanquId: null,
    filteredZhuanquList: [],   // 当前类型下的专区列表
    filteredShangpinList: [],  // 当前专区下的商品列表
    zhuanquByLeixing: {},      // 类型->专区映射对象
    shangpinByZhuanqu: {},     // 专区->商品映射对象
    zhuanquGoodsCount: {},     // 专区商品数量统计
    
    // UI状态
    isLoading: false,
    hasInitialized: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取全局变量
    this.setData({
      ossImageUrl: app.globalData.ossImageUrl
    })
    
    // 初始化数据
    this.initPageData()
  },
  onShow() {
    // 原有代码...
    
    // 🆕 注册通知组件
    this.registerNotificationComponent();
},

// 🆕 新增：注册通知组件
registerNotificationComponent() {
    const app = getApp();
    const notificationComp = this.selectComponent('#global-notification');
    
    if (notificationComp && notificationComp.showNotification) {
        console.log('🏪 商城页面注册通知组件');
        app.globalData.globalNotification = {
            show: (data) => notificationComp.showNotification(data),
            hide: () => notificationComp.hideNotification()
        };
    }
},

  /**
   * 初始化页面数据
   */
  initPageData() {
    const that = this
    this.setData({ isLoading: true })
    
    // 检查全局变量是否已有数据
    if (app.globalData.shangpinleixing && app.globalData.shangpinleixing.length > 0) {
      this.initFromGlobalData()
    } else {
      this.loadAllShangpinData()
    }
  },

  /**
   * 从全局变量初始化数据
   */
  initFromGlobalData() {
    const leixingList = app.globalData.shangpinleixing || []
    const zhuanquList = app.globalData.shangpinzhuanqu || []
    const shangpinList = app.globalData.shangpinliebiao || []
    
    // 构建映射关系对象
    const zhuanquByLeixing = {}
    const shangpinByZhuanqu = {}
    const zhuanquGoodsCount = {}
    
    // 1. 构建专区映射 (按类型分组)
    zhuanquList.forEach(zhuanqu => {
      const leixingId = zhuanqu.leixing_id
      if (!zhuanquByLeixing[leixingId]) {
        zhuanquByLeixing[leixingId] = []
      }
      zhuanquByLeixing[leixingId].push(zhuanqu)
    })
    
    // 2. 构建商品映射 (按专区分组)并统计数量
    shangpinList.forEach(shangpin => {
      const zhuanquId = shangpin.zhuanqu_id
      if (zhuanquId) {
        if (!shangpinByZhuanqu[zhuanquId]) {
          shangpinByZhuanqu[zhuanquId] = []
          zhuanquGoodsCount[zhuanquId] = 0
        }
        
        // 处理价格显示
        const jiage = parseFloat(shangpin.jiage) || 0
        const priceInteger = Math.floor(jiage)
        let priceDecimal = '00'
        
        const decimalPart = (jiage - priceInteger).toFixed(2)
        if (decimalPart > 0) {
          priceDecimal = decimalPart.toString().split('.')[1]
        }
        
        shangpinByZhuanqu[zhuanquId].push({
          id: shangpin.id,
          biaoqian: shangpin.biaoqian,
          jiage: jiage,
          priceInteger: priceInteger,
          priceDecimal: priceDecimal,
          tupian_url: shangpin.tupian_url,
          duiwai_xiaoliang: shangpin.duiwai_xiaoliang || 0
        })
        
        zhuanquGoodsCount[zhuanquId] += 1
      }
    })
    
    // 设置初始选中状态（第一个类型和第一个专区）
    const firstLeixing = leixingList[0]
    let firstZhuanquId = null
    
    if (firstLeixing && zhuanquByLeixing[firstLeixing.id]) {
      firstZhuanquId = zhuanquByLeixing[firstLeixing.id][0]?.id || null
    }
    
    this.setData({
      shangpinleixing: leixingList,
      shangpinzhuanqu: zhuanquList,
      shangpinliebiao: shangpinList,
      zhuanquByLeixing: zhuanquByLeixing,
      shangpinByZhuanqu: shangpinByZhuanqu,
      zhuanquGoodsCount: zhuanquGoodsCount,
      selectedLeixingId: firstLeixing?.id || null,
      selectedZhuanquId: firstZhuanquId
    }, () => {
      // 筛选数据
      this.filterData()
      this.setData({ isLoading: false, hasInitialized: true })
    })
  },

  /**
   * 加载所有商品数据
   */
  loadAllShangpinData() {
    const that = this
    wx.request({
      url: app.globalData.apiBaseUrl + '/shangpin/shangpinhuoqu/',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        if (res.statusCode === 200 && res.data) {
          const data = res.data
          
          // 存储到全局变量
          app.globalData.shangpinleixing = data.shangpinleixing || []
          app.globalData.shangpinzhuanqu = data.shangpinzhuanqu || []
          app.globalData.shangpinliebiao = data.shangpinliebiao || []
          
          // 从全局变量初始化
          that.initFromGlobalData()
        } else {
          that.handleLoadError()
        }
      },
      fail(error) {
        console.error('加载商品数据失败:', error)
        that.handleLoadError()
      }
    })
  },

  /**
   * 处理加载错误
   */
  handleLoadError() {
    wx.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
    this.setData({ isLoading: false })
  },

  /**
   * 筛选数据
   */
  filterData() {
    const { selectedLeixingId, selectedZhuanquId, zhuanquByLeixing, shangpinByZhuanqu } = this.data
    
    // 1. 筛选专区列表
    const filteredZhuanquList = zhuanquByLeixing[selectedLeixingId] || []
    
    // 2. 筛选商品列表
    let filteredShangpinList = []
    if (selectedZhuanquId) {
      filteredShangpinList = shangpinByZhuanqu[selectedZhuanquId] || []
    } else if (filteredZhuanquList.length > 0) {
      // 如果没有选中的专区，默认显示第一个专区的商品
      const firstZhuanquId = filteredZhuanquList[0].id
      filteredShangpinList = shangpinByZhuanqu[firstZhuanquId] || []
      this.setData({ selectedZhuanquId: firstZhuanquId })
    }
    
    this.setData({
      filteredZhuanquList: filteredZhuanquList,
      filteredShangpinList: filteredShangpinList
    })
  },

  /**
   * 选择商品类型
   */
  selectLeixing(e) {
    const leixingId = e.currentTarget.dataset.id
    
    if (this.data.selectedLeixingId === leixingId) {
      return
    }
    
    // 获取该类型下的第一个专区
    const zhuanquList = this.data.zhuanquByLeixing[leixingId] || []
    const firstZhuanquId = zhuanquList.length > 0 ? zhuanquList[0].id : null
    
    this.setData({
      selectedLeixingId: leixingId,
      selectedZhuanquId: firstZhuanquId
    }, () => {
      this.filterData()
    })
  },

  /**
   * 选择商品专区
   */
  selectZhuanqu(e) {
    const zhuanquId = e.currentTarget.dataset.id
    
    if (this.data.selectedZhuanquId === zhuanquId) {
      return
    }
    
    this.setData({
      selectedZhuanquId: zhuanquId
    }, () => {
      // 筛选商品列表
      const filteredShangpinList = this.data.shangpinByZhuanqu[zhuanquId] || []
      this.setData({
        filteredShangpinList: filteredShangpinList
      })
    })
  },

  /**
   * 搜索框输入事件
   */
  onSearchInput(e) {
    this.setData({
      searchText: e.detail.value
    })
  },

  /**
   * 点击搜索按钮
   */
  onSearchTap() {
    const searchText = this.data.searchText.trim()
    if (!searchText) {
      wx.showToast({
        title: '请输入搜索内容',
        icon: 'none'
      })
      return
    }
    
    // 开始搜索
    this.startSearch(searchText)
  },

  /**
   * 键盘搜索事件（回车键）
   */
  onSearchConfirm(e) {
    const searchText = e.detail.value.trim()
    if (!searchText) {
      wx.showToast({
        title: '请输入搜索内容',
        icon: 'none'
      })
      return
    }
    
    this.setData({
      searchText: searchText
    })
    
    // 开始搜索
    this.startSearch(searchText)
  },

  /**
   * 执行搜索
   */
  startSearch(searchText) {
    this.setData({
      isSearching: true,
      showSearchResult: true
    })
    
    // 本地搜索
    const allShangpin = this.data.shangpinliebiao
    const results = []
    
    for (const item of allShangpin) {
      if (item.biaoqian && item.biaoqian.toLowerCase().includes(searchText.toLowerCase())) {
        // 处理价格显示
        const jiage = parseFloat(item.jiage) || 0
        const priceInteger = Math.floor(jiage)
        let priceDecimal = '00'
        
        const decimalPart = (jiage - priceInteger).toFixed(2)
        if (decimalPart > 0) {
          priceDecimal = decimalPart.toString().split('.')[1]
        }
        
        results.push({
          id: item.id,
          biaoqian: item.biaoqian,
          jiage: jiage,
          priceInteger: priceInteger,
          priceDecimal: priceDecimal,
          tupian_url: item.tupian_url,
          leixing_name: this.getLeixingName(item.leixing_id),
          zhuanqu_name: this.getZhuanquName(item.zhuanqu_id)
        })
      }
    }
    
    this.setData({ 
      searchResults: results,
      isSearching: false 
    })
  },

  /**
   * 清空搜索
   */
  onClearSearch() {
    this.setData({
      searchText: '',
      showSearchResult: false,
      searchResults: []
    })
  },

  /**
   * 根据类型ID获取类型名称
   */
  getLeixingName(leixingId) {
    const leixingList = this.data.shangpinleixing
    for (const item of leixingList) {
      if (item.id === leixingId) {
        return item.jieshao
      }
    }
    return ''
  },

  /**
   * 根据专区ID获取专区名称
   */
  getZhuanquName(zhuanquId) {
    const zhuanquList = this.data.shangpinzhuanqu
    for (const item of zhuanquList) {
      if (item.id === zhuanquId) {
        return item.mingzi
      }
    }
    return ''
  },

  /**
   * 跳转到商品详情页
   */
  goToDetail(e) {
    const shangpinId = e.currentTarget.dataset.id
    if (!shangpinId) return
    
    wx.navigateTo({
      url: `/pages/shangpinxiangqing/shangpinxiangqing?id=${shangpinId}`
    })
  },

  /**
   * 刷新所有数据
   */
  onRefresh() {
    wx.showLoading({
      title: '刷新中...',
      mask: true
    })
    
    // 清空全局变量
    app.globalData.shangpinleixing = []
    app.globalData.shangpinzhuanqu = []
    app.globalData.shangpinliebiao = []
    
    this.loadAllShangpinData()
    
    setTimeout(() => {
      wx.hideLoading()
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 1500
      })
    }, 1000)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '阿龙电竞 - 商品分类',
      path: '/pages/fenlei/fenlei'
    }
  }
})