// pages/category/category.js
const app = getApp()
import { createPage } from '../../utils/base-page.js';

Page(createPage({
  data: {
    ossImageUrl: '',
    searchText: '',
    showSearchResult: false,
    searchResults: [],
    isSearching: false,
    shangpinleixing: [],
    shangpinzhuanqu: [],
    shangpinliebiao: [],
    selectedLeixingId: null,
    selectedZhuanquId: null,
    filteredZhuanquList: [],
    filteredShangpinList: [],
    zhuanquByLeixing: {},
    shangpinByZhuanqu: {},
    zhuanquGoodsCount: {},
    isLoading: false,
    hasInitialized: false
  },

  onLoad(options) {
    this.setData({
      ossImageUrl: app.globalData.ossImageUrl
    })
    this.initPageData()
  },

  onShow() {
    this.registerNotificationComponent();
  },

  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 = {}

    zhuanquList.forEach(zhuanqu => {
      const leixingId = zhuanqu.leixing_id
      if (!zhuanquByLeixing[leixingId]) {
        zhuanquByLeixing[leixingId] = []
      }
      zhuanquByLeixing[leixingId].push(zhuanqu)
    })

    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
    const filteredZhuanquList = zhuanquByLeixing[selectedLeixingId] || []
    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: []
    })
  },

  getLeixingName(leixingId) {
    const leixingList = this.data.shangpinleixing
    for (const item of leixingList) {
      if (item.id === leixingId) {
        return item.jieshao
      }
    }
    return ''
  },

  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/product-detail/product-detail?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/category/category'
    }
  }
}))
