// pages/product-detail/product-detail.js
const app = getApp()
import { ensureLogin } from '../../utils/login'
import { backfillUserProfileCache } from '../../utils/role-tab-bar'

Page({
  data: {
    ossImageUrl: '',
    apiBaseUrl: '',

    shangpinId: '',
    shangpinTitle: '',
    shangpinPrice: '',

    shangpinData: null,
    isLoading: true,
    loadError: false,

    // 页面字段映射
    fieldMapping: {
      tupian: 'tupian',
      biaoti: 'biaoti',
      jiage: 'jiage',
      xiangqing: 'xiangqing',
      xiadanxuzhi: 'xiadanxuzhi',
      guize: 'guize',
      xiaoliang: 'xiaoliang',
      kucun: 'kucun',
      fenlei: 'fenlei',
      pingfen: 'pingfen'
    }
  },

  onLoad(options) {
    this.setData({
      ossImageUrl: app.globalData.ossImageUrl,
      apiBaseUrl: app.globalData.apiBaseUrl,
      shangpinId: options.id || '',
      shangpinTitle: options.title || '',
      shangpinPrice: options.price || ''
    })

    if (!this.data.shangpinId) {
      wx.showToast({
        title: '商品不存在',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }

    this.loadShangpinDetail()
  },
  onShow() {
    backfillUserProfileCache(app);
    this.registerNotificationComponent();
  },

  registerNotificationComponent() {
    const app = getApp();
    const notificationComp = this.selectComponent('#global-notification');

    if (notificationComp && notificationComp.showNotification) {
      app.globalData.globalNotification = {
        show: (data) => notificationComp.showNotification(data),
        hide: () => notificationComp.hideNotification()
      };
    }
  },

  loadShangpinDetail() {
    const that = this
    const { shangpinId, apiBaseUrl } = this.data
    
    this.setData({ isLoading: true, loadError: false })
    
    wx.request({
      url: apiBaseUrl + '/shangpin/xiangqinghuoqu/',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        shangpin_id: shangpinId
      },
      success(res) {
        if (res.statusCode === 200 && res.data && res.data.code === 0) {
          const shangpinData = res.data.data || {}

          // 处理价格
          if (shangpinData.jiage) {
            const jiage = parseFloat(shangpinData.jiage) || 0
            const priceInteger = Math.floor(jiage)
            let priceDecimal = '00'
            
            const decimalPart = (jiage - priceInteger).toFixed(2)
            if (decimalPart > 0) {
              priceDecimal = decimalPart.toString().split('.')[1]
            }
            
            shangpinData.priceInteger = priceInteger
            shangpinData.priceDecimal = priceDecimal
          }
          
          // 处理图片URL
          if (shangpinData.tupian && !shangpinData.tupian.startsWith('http')) {
            shangpinData.tupian = that.data.ossImageUrl + shangpinData.tupian
          }
          
          // 处理规则图片URL
          if (shangpinData.guize && !shangpinData.guize.startsWith('http')) {
            shangpinData.guize = that.data.ossImageUrl + shangpinData.guize
          }
          
          // 处理销量显示
          if (shangpinData.xiaoliang) {
            shangpinData.xiaoliangText = that.formatXiaoliang(shangpinData.xiaoliang)
          }
          
          // 处理库存显示
          if (shangpinData.kucun) {
            shangpinData.kucunText = shangpinData.kucun + '件'
            shangpinData.kucunClass = shangpinData.kucun > 0 ? 'kucun-normal' : 'kucun-none'
          }
          
          // 设置页面标题
          if (shangpinData.biaoti) {
            wx.setNavigationBarTitle({
              title: '商品详情'
            })
          }
          
          that.setData({
            shangpinData: shangpinData,
            isLoading: false
          })
        } else {
          that.handleLoadError(res.data?.msg || '加载失败')
        }
      },
      fail() {
        that.handleLoadError('网络错误，请重试')
      }
    })
  },

  formatXiaoliang(xiaoliang) {
    const num = parseInt(xiaoliang) || 0
    
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + '万+'
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + '千+'
    } else {
      return num + ''
    }
  },

  handleLoadError(errorMsg) {
    this.setData({
      isLoading: false,
      loadError: true
    })
    
    wx.showToast({
      title: errorMsg || '加载失败',
      icon: 'none',
      duration: 2000
    })
    
    // 3秒后自动返回
    setTimeout(() => {
      wx.navigateBack()
    }, 3000)
  },

  previewImage() {
    const { shangpinData } = this.data
    if (!shangpinData || !shangpinData.tupian) return
    
    wx.previewImage({
      current: shangpinData.tupian,
      urls: [shangpinData.tupian]
    })
  },

  async onOrderClick() {
    const { shangpinData, shangpinId } = this.data
    
    // 检查库存
    if (shangpinData && shangpinData.kucun <= 0) {
      wx.showToast({
        title: '商品已售罄',
        icon: 'none'
      })
      return
    }
    
    // 验证必要数据
    if (!shangpinData || !shangpinData.biaoti) {
      wx.showToast({
        title: '商品信息不完整',
        icon: 'none'
      })
      return
    }

    try {
      await ensureLogin()
    } catch (e) {
      return
    }
    
    const orderData = {
      id: shangpinId,
      title: shangpinData.biaoti,
      price: shangpinData.jiage,
      priceInteger: shangpinData.priceInteger,
      priceDecimal: shangpinData.priceDecimal,
      image: shangpinData.tupian,
      kucun: shangpinData.kucun || 0,
      xiaoliang: shangpinData.xiaoliang || 0
    }
    
    wx.navigateTo({
      url: `/pages/submit/submit?data=${encodeURIComponent(JSON.stringify(orderData))}`
    })
  },

  onRefresh() {
    this.loadShangpinDetail()
  },

  goToKefu() {
    wx.navigateTo({ url: '/pages/cs-chat/cs-chat' })
  },

  onShareAppMessage() {
    const { shangpinData, shangpinId } = this.data
    
    return {
      title: shangpinData?.biaoti || '阿龙电竞 - 商品详情',
      path: `/pages/product-detail/product-detail?id=${shangpinId}`,
      imageUrl: shangpinData?.tupian || ''
    }
  },

  onUnload() {
  }
})