/**
 * 商品评价 / 追评
 * 模式: mode=create(首次评价) | mode=followup(追评)
 * 对齐后端 /api/review/create + /api/review/follow-up
 */
const api = require('../../utils/api');

Page({
  data: {
    mode: 'create',
    orderId: null,
    orderNo: '',
    items: [],
    // 每件商品的评价数据: { [itemId]: { rating, content } }
    reviewMap: {},
    submitting: false
  },

  onLoad(options) {
    this.setData({
      mode: options.mode || 'create',
      orderId: options.orderId ? Number(options.orderId) : null,
      orderNo: options.orderNo || ''
    });
    wx.setNavigationBarTitle({ title: this.data.mode === 'followup' ? '追加评价' : '商品评价' });
    if (this.data.orderNo) {
      this.loadOrder();
    }
  },

  async loadOrder() {
    wx.showLoading({ title: '加载中...', mask: true });
    try {
      const order = await api.getOrderDetail(this.data.orderNo);
      this.setData({ items: order.items || [] }, () => this.buildInitialStars());
    } catch (e) {}
    finally { wx.hideLoading(); }
  },

  onRating(e) {
    const itemId = e.currentTarget.dataset.id;
    const rating = Number(e.currentTarget.dataset.rating);
    const stars = [1, 2, 3, 4, 5].map(i => i <= rating);
    this.setData({
      ['reviewMap.' + itemId + '.rating']: rating,
      ['reviewMap.' + itemId + '.stars']: stars
    });
  },

  onContent(e) {
    const itemId = e.currentTarget.dataset.id;
    this.setData({ ['reviewMap.' + itemId + '.content']: e.detail.value });
  },

  buildInitialStars() {
    // 初始化每件商品默认5星
    const reviewMap = {};
    (this.data.items || []).forEach(it => {
      reviewMap[it.id] = { rating: 5, stars: [true, true, true, true, true], content: '' };
    });
    this.setData({ reviewMap });
  },

  async submit() {
    if (this.data.submitting) return;
    const { items, reviewMap, mode, orderId } = this.data;
    let ok = 0;
    this.setData({ submitting: true });
    wx.showLoading({ title: '提交中...', mask: true });

    try {
      for (const item of items) {
        const data = reviewMap[item.id];
        if (!data || !data.rating) continue; // 未评价商品跳过
        if (mode === 'followup') {
          await api.followUpReview({
            order_id: item.order_id,
            content: data.content || ''
          });
        } else {
          await api.createReview({
            product_id: item.product_id,
            order_id: orderId || item.order_id,
            rating: data.rating,
            content: data.content || '',
            images: []
          });
        }
        ok++;
      }
      wx.hideLoading();
      if (ok > 0) {
        wx.showToast({ title: '评价成功', icon: 'success' });
        setTimeout(() => wx.navigateBack(), 1200);
      } else {
        wx.showToast({ title: '请至少评价一个商品', icon: 'none' });
      }
    } catch (e) {
      wx.hideLoading();
      // 内部已 toast
    } finally {
      this.setData({ submitting: false });
    }
  },

  noop() {}
});
