// pages/dingdan/dingdan.js
const app = getApp()
import request from '../../utils/request.js'

Page({
  data: {
    // 订单状态tab配置
    dingdanZhuangtaiTabs: [
      { name: '全部', key: 'all', zhuangtaiList: [1, 2, 3, 4, 5, 6, 7, 8] },
      { name: '已下单', key: 'yixiadan', zhuangtaiList: [1, 7] },
      { name: '进行中', key: 'jinxingzhong', zhuangtaiList: [2] },
      { name: '争议订单', key: 'zhengyi', zhuangtaiList: [4, 5, 6] },
      { name: '已完成', key: 'yiwancheng', zhuangtaiList: [3] },
      { name: '结算中', key: 'jiesuanzhong', zhuangtaiList: [8] }
    ],
    
    // 当前选中的tab索引
    xuanzhongTabIndex: 0,
    // 当前选中的tab的key
    currentTabKey: 'all',
    
    // 每个tab对应的订单数据
    dingdanShuju: {
      all: { list: [], page: 1, hasMore: true, isLoading: false },
      yixiadan: { list: [], page: 1, hasMore: true, isLoading: false },
      jinxingzhong: { list: [], page: 1, hasMore: true, isLoading: false },
      zhengyi: { list: [], page: 1, hasMore: true, isLoading: false },
      yiwancheng: { list: [], page: 1, hasMore: true, isLoading: false },
      jiesuanzhong: { list: [], page: 1, hasMore: true, isLoading: false }
    },
    
    // 个人中心传递过来的type参数
    gerenzhongxinType: '',
    
    // 是否显示加载更多
    xianshiJiazaigengduo: false,
    
    // 页面加载状态
    isLoading: true
  },

  onLoad(options) {
    const type = options.type || ''
    
    wx.setNavigationBarTitle({
      title: '我的订单'
    })
    
    this.qingkongGerenzhongxinJishu(type)
    
    const tabIndex = this.yingsheTypeToTabIndex(type)
    const tabKey = this.data.dingdanZhuangtaiTabs[tabIndex].key
    
    this.setData({
      gerenzhongxinType: type,
      xuanzhongTabIndex: tabIndex,
      currentTabKey: tabKey,
      isLoading: false
    })
    
    this.jiazaiDingdanShuju(tabIndex)
  },
  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()
        };
    }
},


  qingkongGerenzhongxinJishu(type) {
    const jishuMap = {
      'daifuwu': 'daifuwu',
      'fuwuzhong': 'fuwuzhong',
      'yiwancheng': 'yiwancheng',
      'yituikuan': 'yituikuan'
    }
    
    const jishuKey = jishuMap[type]
    if (jishuKey && app.globalData.dingdanTiaoshu) {
      app.globalData.dingdanTiaoshu[jishuKey] = 0
    }
  },

  yingsheTypeToTabIndex(type) {
    const yingsheMap = {
      'daifuwu': 1,
      'fuwuzhong': 2,
      'yiwancheng': 4,
      'yituikuan': 3
    }
    
    return yingsheMap[type] || 0
  },

  switchDingdanTab(e) {
    const tabIndex = e.currentTarget.dataset.index
    if (tabIndex === this.data.xuanzhongTabIndex) return
    
    const tabKey = this.data.dingdanZhuangtaiTabs[tabIndex].key
    
    this.setData({
      xuanzhongTabIndex: tabIndex,
      currentTabKey: tabKey
    })
    
    this.jiazaiDingdanShuju(tabIndex)
  },

  async jiazaiDingdanShuju(tabIndex, isLoadMore = false) {
    const tab = this.data.dingdanZhuangtaiTabs[tabIndex]
    const tabKey = tab.key
    
    const tabData = this.data.dingdanShuju[tabKey]
    
    const page = isLoadMore ? tabData.page + 1 : 1
    
    if (tabData.isLoading) return
    
    // 重置逻辑：如果不是加载更多，清空已有数据
    if (!isLoadMore) {
      this.setData({
        [`dingdanShuju.${tabKey}.list`]: [],
        [`dingdanShuju.${tabKey}.page`]: 1
      })
    }
    
    this.setData({
      [`dingdanShuju.${tabKey}.isLoading`]: true
    })
    
    wx.showLoading({
      title: isLoadMore ? '加载更多...' : '加载订单...',
      mask: true
    })
    
    try {
      const requestData = {
        zhuangtai_list: tab.zhuangtaiList,
        page: page,
        page_size: 10
      }
      
      
      
      const res = await request({
        url: '/dingdan/dingdanhuoqu',
        method: 'POST',
        data: requestData,
        header: {
          'content-type': 'application/json'
        }
      })
      
      
      
      wx.hideLoading()
      
      // ✅ 关键修正：res是直接返回的数据对象，不是res.data
      if (res && res.data.code === 0) {
        // ✅ 关键修正：直接使用res.data.list
        const newDingdanList = res.data.data.list || []
        const hasMore = res.data.data.has_more || false
        
        
        
        // 处理图片URL，拼接完整路径
        const processedList = newDingdanList.map(item => {
          let tupianUrl = item.tupian || ''
          
          // 如果图片URL不是完整路径，拼接ossImageUrl
          if (tupianUrl && !tupianUrl.startsWith('http')) {
            const ossImageUrl = app.globalData.ossImageUrl || ''
            tupianUrl = ossImageUrl + tupianUrl
          }
          
          const zhuangtaiZh = this.getZhuangtaiZhongwen(item.zhuangtai)
          
          
          return {
            ...item,
            tupian: tupianUrl,
            zhuangtaiZh: zhuangtaiZh
          }
        })
        
        const currentList = this.data.dingdanShuju[tabKey].list
        const updatedList = isLoadMore 
          ? [...currentList, ...processedList]
          : processedList
        
        this.setData({
          [`dingdanShuju.${tabKey}.list`]: updatedList,
          [`dingdanShuju.${tabKey}.page`]: page,
          [`dingdanShuju.${tabKey}.hasMore`]: hasMore,
          [`dingdanShuju.${tabKey}.isLoading`]: false,
          xianshiJiazaigengduo: hasMore
        })
        
      } else {
        wx.showToast({
          title: res ? (res.msg || '加载失败') : '请求失败',
          icon: 'none',
          duration: 2000
        })
        
        this.setData({
          [`dingdanShuju.${tabKey}.isLoading`]: false
        })
      }
      
    } catch (error) {
      console.error('加载订单数据失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: '网络请求失败，请重试',
        icon: 'none',
        duration: 2000
      })
      
      this.setData({
        [`dingdanShuju.${tabKey}.isLoading`]: false
      })
    }
  },

  getZhuangtaiZhongwen(zhuangtai) {
    const zhuangtaiMap = {
      1: '已下单',
      2: '进行中',
      3: '已完成',
      4: '退款中',
      5: '已退款',
      6: '退款失败',
      7: '指定中',
      8: '结算中'
    }
    
    return zhuangtaiMap[zhuangtai] || '未知状态'
  },

  onReachBottom() {
    const tabKey = this.data.currentTabKey
    const tabData = this.data.dingdanShuju[tabKey]
    
    if (tabData.hasMore && !tabData.isLoading) {
      const tabIndex = this.data.xuanzhongTabIndex
      this.jiazaiDingdanShuju(tabIndex, true)
    }
  },

  goToDingdanXiangqing(e) {
    const dingdanItem = e.currentTarget.dataset.item
    if (!dingdanItem) return
    
    const dingdanDataStr = encodeURIComponent(JSON.stringify(dingdanItem))
    
    wx.navigateTo({
      url: `/pages/dingdanxiangqing/dingdanxiangqing?dingdanData=${dingdanDataStr}`
    })
  },

  onImageError(e) {
    const index = e.currentTarget.dataset.index
    const tabKey = this.data.currentTabKey
    
    const defaultImage = app.globalData.lunbozhanwei || '/images/default.jpg'
    
    this.setData({
      [`dingdanShuju.${tabKey}.list[${index}].tupian`]: defaultImage
    })
  }
})