// 牛肉商城首页
const app = getApp();

Page({
  data: {
    userInfo: null,
    bannerList: [],
    categoryList: [],
    hotProducts: [],
    newProducts: [],
    recommendProducts: [],
    loading: true,
    refreshing: false,
    searchKeyword: ''
  },

  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.loadNewProducts(),
        this.loadRecommendProducts()
      ]);
    } catch (error) {
      console.error('加载数据失败：', error);
      app.showError('加载数据失败');
    } finally {
      this.setData({ loading: false });
    }
  },

  // 加载轮播图
  async loadBanners() {
    try {
      const res = await app.request({
        url: '/mall/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: '/mall/categories',
        method: 'GET',
        data: { level: 1, limit: 8 }
      });
      
      this.setData({
        categoryList: res.data.list || []
      });
    } catch (error) {
      console.error('加载分类失败：', error);
    }
  },

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

  // 加载新品推荐
  async loadNewProducts() {
    try {
      const res = await app.request({
        url: '/mall/products',
        method: 'GET',
        data: {
          sort: 'latest',
          limit: 4
        }
      });
      
      this.setData({
        newProducts: res.data.list || []
      });
    } catch (error) {
      console.error('加载新品推荐失败：', error);
    }
  },

  // 加载推荐商品
  async loadRecommendProducts() {
    try {
      const res = await app.request({
        url: '/mall/products/recommend',
        method: 'GET',
        data: { limit: 10 }
      });
      
      this.setData({
        recommendProducts: res.data.list || []
      });
    } catch (error) {
      console.error('加载推荐商品失败：', error);
    }
  },

  // 轮播图点击
  onBannerTap(e) {
    const { banner } = e.currentTarget.dataset;
    if (banner.link_type === 'product') {
      wx.navigateTo({
        url: `/pages/product/detail?id=${banner.link_value}`
      });
    } else if (banner.link_type === 'category') {
      wx.navigateTo({
        url: `/pages/product/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/product/list?category=${category.id}`
    });
  },

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

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索确认
  onSearchConfirm() {
    if (this.data.searchKeyword.trim()) {
      wx.navigateTo({
        url: `/pages/search/index?keyword=${encodeURIComponent(this.data.searchKeyword)}`
      });
    }
  },

  // 搜索页面
  onSearchTap() {
    wx.navigateTo({
      url: '/pages/search/index'
    });
  },

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

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

  // 查看全部分类
  onViewAllCategories() {
    wx.switchTab({
      url: '/pages/category/index'
    });
  },

  // 添加到购物车
  onAddToCart(e) {
    e.stopPropagation();
    const { product } = e.currentTarget.dataset;
    
    // 检查是否需要选择规格
    if (product.has_specs) {
      wx.navigateTo({
        url: `/pages/product/detail?id=${product.id}&action=addCart`
      });
    } else {
      app.addToCart(product, 1);
    }
  },

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

  // 格式化销量
  formatSales(sales) {
    if (sales >= 10000) {
      return (sales / 10000).toFixed(1) + '万';
    }
    return sales.toString();
  }
});