/**
 * 购物车页面
 * 支持勾选、数量修改、删除、结算
 */
const api = require('../../utils/api');
const decor = require('../../utils/decor');

Page({
  data: {
    decorEnabled: false,
    decorComponents: [],
    cartItems: [],
    allSelected: true,
    totalAmount: '0.00',
    selectedCount: 0,
    loading: true
  },

  onShow() {
    decor.init(this, 'cart');
    this.loadCart();
  },

  async loadCart() {
    this.setData({ loading: true });
    try {
      const list = await api.getCartList();
      // 解析specs字符串为数组
      const items = (list || []).map(item => ({
        ...item,
        specs: typeof item.specs === 'string' ? JSON.parse(item.specs || '[]') : (item.specs || []),
        price: parseFloat(item.sku_price || item.price || 0).toFixed(2)
      }));
      this.setData({ cartItems: items });
      this.calcTotal();
    } catch (err) {
      if (err.message && err.message.includes('登录')) {
        this.setData({ cartItems: [], loading: false });
      }
    } finally {
      this.setData({ loading: false });
    }
  },

  calcTotal() {
    const { cartItems } = this.data;
    const selected = cartItems.filter(i => i.selected);
    const total = selected.reduce((s, i) => {
      return s + parseFloat(i.sku_price || i.price || 0) * (i.quantity || 1);
    }, 0);
    this.setData({
      totalAmount: total.toFixed(2),
      selectedCount: selected.length,
      allSelected: cartItems.length > 0 && cartItems.every(i => i.selected)
    });

    // 更新角标
    const app = getApp();
    const count = cartItems.reduce((s, c) => s + (c.quantity || 1), 0);
    app.globalData.cartCount = count;
    if (count > 0) {
      wx.setTabBarBadge({ index: 2, text: String(count > 99 ? '99+' : count) });
    } else {
      wx.removeTabBarBadge({ index: 2 });
    }
  },

  async onToggleSelect(e) {
    const id = e.currentTarget.dataset.id;
    const items = this.data.cartItems.map(i => {
      if (i.id === id) i.selected = !i.selected;
      return i;
    });
    this.setData({ cartItems: items });
    this.calcTotal();

    // 同步后端
    const item = items.find(i => i.id === id);
    if (item) {
      try { await api.toggleCartSelect({ id, selected: item.selected }); } catch(e) {}
    }
  },

  async onToggleAll() {
    const newVal = !this.data.allSelected;
    const items = this.data.cartItems.map(i => ({ ...i, selected: newVal }));
    this.setData({ cartItems: items });
    this.calcTotal();
    try { await api.selectAllCart({ selected: newVal }); } catch(e) {}
  },

  async onDecrease(e) {
    const id = e.currentTarget.dataset.id;
    const item = this.data.cartItems.find(i => i.id === id);
    if (!item || item.quantity <= 1) {
      // 数量为1时减操作改为删除
      wx.showModal({
        title: '提示',
        content: '是否删除该商品？',
        success: (res) => {
          if (res.confirm) this.deleteItem(id);
        }
      });
      return;
    }
    const newQty = item.quantity - 1;
    this.updateQuantity(id, newQty);
  },

  async onIncrease(e) {
    const id = e.currentTarget.dataset.id;
    const item = this.data.cartItems.find(i => i.id === id);
    if (item) {
      this.updateQuantity(id, item.quantity + 1);
    }
  },

  async updateQuantity(id, quantity) {
    try {
      await api.updateCart(id, { quantity });
      const items = this.data.cartItems.map(i => {
        if (i.id === id) i.quantity = quantity;
        return i;
      });
      this.setData({ cartItems: items });
      this.calcTotal();
    } catch(e) {}
  },

  async deleteItem(id) {
    try {
      await api.deleteCart(id);
      const items = this.data.cartItems.filter(i => i.id !== id);
      this.setData({ cartItems: items });
      this.calcTotal();
    } catch(e) {}
  },

  async onClear() {
    wx.showModal({
      title: '确认清空',
      content: '清空购物车中的所有商品？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await api.clearCart();
            this.setData({ cartItems: [] });
            this.calcTotal();
          } catch(e) {}
        }
      }
    });
  },

  onCheckout() {
    const selected = this.data.cartItems.filter(i => i.selected);
    if (selected.length === 0) {
      wx.showToast({ title: '请选择商品', icon: 'none' });
      return;
    }
    const items = selected.map(i => ({
      product_id: i.product_id,
      sku_id: i.sku_id,
      quantity: i.quantity,
      name: i.product_name,
      price: i.sku_price || i.price,
      image: i.product_image || i.image,
      cart_id: i.id
    }));
    wx.navigateTo({
      url: '/pages/checkout/checkout?items=' + encodeURIComponent(JSON.stringify(items))
    });
  },

  goHome() {
    wx.switchTab({ url: '/pages/index/index' });
  },

  onDecorNav(e) {
    decor.onNav(this, e, {});
  },

  onDecorProduct(e) {
    const id = e.currentTarget.dataset.id;
    if (id) {
      if (typeof wx.getStorageSync === 'function') {
        try { wx.setStorageSync('_decor_cat_restore', this.data.decorEnabled ? true : false); } catch (q) {}
      }
      wx.navigateTo({ url: '/pages/product/product?id=' + id });
    }
  },
  onClaimCoupon(e) {
    const decor = require('../../utils/decor');
    decor.claimCoupon(this, e);
  },
  onDecorCategory(e) {
    if (typeof wx.switchTab === 'function') wx.switchTab({ url: '/pages/category/category' });
  }
});
