/**
 * 商品详情页
 * 功能：轮播、价格/名称、规格选择、评价列表、收藏、加入购物车/立即购买
 */
const api = require('../../utils/api');

Page({
  data: {
    product: {},
    images: [],
    specs: [],
    selectedSpecs: [],  // 选中的规格值数组
    skus: [],
    currentPrice: '0.00',
    currentSku: null,
    cartLoading: false,
    isFavorited: false,
    reviewsList: [],
    reviewsStats: { total: 0, avg_rating: 0 }
  },

  onLoad(options) {
    const id = options.id;
    if (id) {
      this.loadProduct(id);
      this.checkFavorite(id);
      // 记录浏览足迹（需登录）
      const app = getApp();
      if (app.checkLogin()) {
        api.addBrowseHistory(id).catch(() => {});
      }
    }
  },

  async loadProduct(id) {
    wx.showLoading({ title: '加载中...', mask: true });
    try {
      const product = await api.getProductDetail(id);
      
      const images = product.images && product.images.length > 0 
        ? product.images 
        : (product.image ? [product.image] : []);

      const specs = product.specs || [];
      const selectedSpecs = specs.map(() => '');

      this.setData({
        product,
        images,
        specs,
        skus: product.skus || [],
        selectedSpecs,
        currentPrice: product.price
      });

      // 如果有规格，默认选中第一组
      if (specs.length > 0) {
        this.selectDefaultSpec(specs, product.skus);
      }

      // 加载评价
      this.loadReviews(id);
    } catch (err) {
      console.error('商品加载失败:', err);
      wx.showToast({ title: '商品加载失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },

  async checkFavorite(id) {
    try {
      const result = await api.getFavorites({ product_id: id });
      if (result && result.some) {
        this.setData({ isFavorited: true });
      }
    } catch (e) { /* ignore */ }
  },

  selectDefaultSpec(specs, skus) {
    // 默认选中各规格的第一个值
    const selected = specs.map(s => s.values[0] || '');
    this.setData({ selectedSpecs: selected });
    this.matchSku(selected);
  },

  onSpecTap(e) {
    const { specIndex, value } = e.currentTarget.dataset;
    const selected = [...this.data.selectedSpecs];
    selected[specIndex] = selected[specIndex] === value ? '' : value;
    this.setData({ selectedSpecs: selected });
    this.matchSku(selected);
  },

  matchSku(selectedSpecs) {
    const { skus } = this.data;
    if (!skus || skus.length === 0) return;

    // 找到匹配的SKU
    const matched = skus.find(sku => {
      const skuSpecs = typeof sku.specs === 'string' ? JSON.parse(sku.specs || '[]') : (sku.specs || []);
      if (skuSpecs.length !== selectedSpecs.length) return false;
      return skuSpecs.every((s, i) => s === selectedSpecs[i]);
    });

    if (matched) {
      this.setData({
        currentSku: matched,
        currentPrice: matched.price
      });
    } else {
      this.setData({
        currentSku: null,
        currentPrice: this.data.product.price
      });
    }
  },

  async loadReviews(productId) {
    try {
      const result = await api.getProductReviews(productId, { pageSize: 3 });
      if (result) {
        this.setData({
          reviewsList: result.list || [],
          reviewsStats: result.stats || { total: 0, avg_rating: 0 }
        });
      }
    } catch (e) { /* ignore */ }
  },

  async onLikeReview(e) {
    const app = getApp();
    if (!app.checkLogin()) { app.requireLogin(); return; }
    const id = e.currentTarget.dataset.id;
    try {
      const res = await api.toggleReviewLike({ review_id: id });
      if (res) {
        const list = this.data.reviewsList.map(r => {
          if (r.id == id) {
            return { ...r, is_liked: res.liked, like_count: res.like_count };
          }
          return r;
        });
        this.setData({ reviewsList: list });
      }
    } catch (err) { /* 内部已 toast */ }
  },

  async onAddCart() {
    const app = getApp();
    if (!app.checkLogin()) return;

    this.setData({ cartLoading: true });
    try {
      await api.addCart({
        product_id: this.data.product.id,
        sku_id: this.data.currentSku ? this.data.currentSku.id : null,
        quantity: 1
      });
      wx.showToast({ title: '已加入购物车', icon: 'success' });
    } catch (err) {
      // error handled by api.js
    } finally {
      this.setData({ cartLoading: false });
    }
  },

  onBuyNow() {
    const app = getApp();
    if (!app.checkLogin()) return;

    const { product, currentSku } = this.data;
    const items = [{
      product_id: product.id,
      sku_id: currentSku ? currentSku.id : null,
      quantity: 1,
      name: product.name,
      price: currentSku ? currentSku.price : product.price,
      image: product.image
    }];

    wx.navigateTo({ url: '/pages/checkout/checkout?items=' + encodeURIComponent(JSON.stringify(items)) });
  },

  async onFavorite() {
    const app = getApp();
    if (!app.checkLogin()) return;

    const { product, isFavorited } = this.data;
    try {
      if (isFavorited) {
        await api.removeFavorite(product.id);
        this.setData({ isFavorited: false });
        wx.showToast({ title: '已取消收藏', icon: 'success' });
      } else {
        await api.addFavorite(product.id);
        this.setData({ isFavorited: true });
        wx.showToast({ title: '收藏成功', icon: 'success' });
      }
    } catch (err) { /* handled */ }
  },

  onShare() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  onShareAppMessage() {
    const { product } = this.data;
    return {
      title: product.name || '省胜优铺 精选好物',
      path: `/pages/product/product?id=${product.id}`
    };
  },

  onImageError(e) {
    e.target.src = '/assets/images/empty.png';
  }
});
