// 牛只交易首页
const app = getApp();

Page({
  data: {
    userInfo: null,
    bannerList: [],
    categoryList: [],
    hotProducts: [],
    recentProducts: [],
    marketStats: {
      totalProducts: 0,
      todayDeals: 0,
      avgPrice: 0
    },
    loading: true,
    refreshing: false
  },

  onLoad() {
    this.checkLogin();
  },

  onShow() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      });
      this.loadData();
    }
  },

  onPullDownRefresh() {
    this.setData({ refreshing: true });
    this.loadData().finally(() => {
      this.setData({ refreshing: false });
      wx.stopPullDownRefresh();
    });
  },

  // 检查登录状态
  checkLogin() {
    if (!app.globalData.userInfo) {
      wx.navigateTo({
        url: '/pages/auth/login'
      });
      return;
    }
    
    this.setData({
      userInfo: app.globalData.userInfo
    });
    this.loadData();
  },

  // 加载数据
  async loadData() {
    try {
      this.setData({ loading: true });
      
      await Promise.all([
        this.loadBanners(),
        this.loadCategories(),
        this.loadHotProducts(),
        this.loadRecentProducts(),
        this.loadMarketStats()
      ]);
    } catch (error) {
      console.error('加载数据失败：', error);
      app.showError('加载数据失败');
    } finally {
      this.setData({ loading: false });
    }
  },

  // 加载轮播图
  async loadBanners() {
    try {
      const res = await app.request({
        url: '/banners',
        method: 'GET',
        data: { type: 'home' }
      });
      
      this.setData({
        bannerList: res.data.list || []
      });
    } catch (error) {
      console.error('加载轮播图失败：', error);
    }
  },

  // 加载分类
  async loadCategories() {
    try {
      const res = await app.request({
        url: '/categories',
        method: 'GET'
      });
      
      this.setData({
        categoryList: res.data.list || []
      });
    } catch (error) {
      console.error('加载分类失败：', error);
    }
  },

  // 加载热门商品
  async loadHotProducts() {
    try {
      const res = await app.request({
        url: '/products',
        method: 'GET',
        data: {
          sort: 'hot',
          limit: 6
        }
      });
      
      this.setData({
        hotProducts: res.data.list || []
      });
    } catch (error) {
      console.error('加载热门商品失败：', error);
    }
  },

  // 加载最新商品
  async loadRecentProducts() {
    try {
      const res = await app.request({
        url: '/products',
        method: 'GET',
        data: {
          sort: 'latest',
          limit: 10
        }
      });
      
      this.setData({
        recentProducts: res.data.list || []
      });
    } catch (error) {
      console.error('加载最新商品失败：', error);
    }
  },

  // 加载市场统计
  async loadMarketStats() {
    try {
      const res = await app.request({
        url: '/market/stats',
        method: 'GET'
      });
      
      this.setData({
        marketStats: res.data || {}
      });
    } catch (error) {
      console.error('加载市场统计失败：', error);
    }
  },

  // 轮播图点击
  onBannerTap(e) {
    const { banner } = e.currentTarget.dataset;
    if (banner.link_type === 'product') {
      wx.navigateTo({
        url: `/pages/market/detail?id=${banner.link_value}`
      });
    } else if (banner.link_type === 'category') {
      wx.navigateTo({
        url: `/pages/market/list?category=${banner.link_value}`
      });
    } else if (banner.link_type === 'url') {
      wx.navigateTo({
        url: `/pages/common/webview?url=${encodeURIComponent(banner.link_value)}`
      });
    }
  },

  // 分类点击
  onCategoryTap(e) {
    const { category } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/market/list?category=${category.id}`
    });
  },

  // 商品点击
  onProductTap(e) {
    const { product } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/market/detail?id=${product.id}`
    });
  },

  // 搜索
  onSearch() {
    wx.navigateTo({
      url: '/pages/market/search'
    });
  },

  // 发布商品
  onPublish() {
    wx.navigateTo({
      url: '/pages/market/publish'
    });
  },

  // 查看更多热门
  onViewMoreHot() {
    wx.navigateTo({
      url: '/pages/market/list?sort=hot'
    });
  },

  // 查看更多最新
  onViewMoreRecent() {
    wx.navigateTo({
      url: '/pages/market/list?sort=latest'
    });
  },

  // 查看全部商品
  onViewAllProducts() {
    wx.switchTab({
      url: '/pages/market/list'
    });
  },

  // 格式化价格
  formatPrice(price) {
    return app.formatPrice(price);
  },

  // 格式化时间
  formatTime(timestamp) {
    return app.formatTime(timestamp);
  },

  // 格式化数量
  formatNumber(num) {
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + '万';
    }
    return num.toString();
  }
});