<template>
  <view class="food-card">
    <view class="food-item">
      <image class="food-image" :src="food.images" mode="aspectFill" @click="handleFoodClick" />
      <view class="food-info">
        <view class="food-header">
          <view class="food-title">{{ food.name }}</view>
          <view class="food-price">
            <text class="price-symbol">¥</text>
            <text class="price-main">{{ getPriceMain(food.totalPrice) }}</text>
            <text class="price-decimal" v-if="getPriceDecimal(food.totalPrice)">.{{ getPriceDecimal(food.totalPrice) }}</text>
          </view>
        </view>
        <view class="food-desc">{{ food.description }}</view>
        <view class="food-tags" v-if="normalizedTags.length">
          <view v-for="(tag, tagIndex) in normalizedTags" :key="tagIndex" class="food-tag" :class="tag.type">
            {{ tag.text }}
          </view>
        </view>
      </view>
    </view>
    <view class="food-footer">
      <view class="food-sales">
        <image :src="getFileUrl('img/icon/star.png')" mode="aspectFill" class="star-icon"></image>
        <text class="sales-text">月售:{{ food.monthlySales || 0 }}</text>
      </view>
      <view class="food-actions">
        <view class="action-btn minus" :class="{ disabled: food.quantity === 0 }" @click="handleDecrease" hover-class="hover-active">
          <image :src="getFileUrl('img/icon/reduce1.png')" mode="aspectFit" class="action-icon" v-show="food.quantity == 0"></image>
          <image :src="getFileUrl('img/icon/reduce2.png')" mode="aspectFit" class="action-icon" v-show="food.quantity != 0"></image>
        </view>
        <view class="quantity">{{ food.quantity || 0 }}</view>
        <view class="action-btn plus" @click="handleIncrease" hover-class="hover-active">
          <image :src="getFileUrl('img/icon/add2.png')" mode="widthFix" class="action-icon" v-show="food.quantity < 99"></image>
          <image :src="getFileUrl('img/icon/add1.png')" mode="widthFix" class="action-icon" v-show="food.quantity >= 99"></image>
        </view>
      </view>
    </view>

  </view>
</template>

<script setup>
import { computed } from "vue";
import { getFileUrl } from "@/utils/file.js";
import { go } from "@/utils/utils.js";

const props = defineProps({
  food: {
    type: Object,
    required: true,
    default: () => ({
      id: null,
      name: '',
      price: 0,
      desc: '',
      image: '',
      tags: [],
      monthlySales: 0,
      quantity: 0
    })
  },
  /** 桌号ID，跳转详情页时传入以便加购 */
  tableId: { type: [String, Number], default: '' }
});

const emit = defineEmits(['increase', 'decrease']);

// 后端返回的 tags 统一为 [{ text, type }] 便于绑定（兼容多种字段名与格式）
const normalizedTags = computed(() => {
  const food = props.food;
  let raw = food?.tags ?? food?.tagList ?? food?.tagNames ?? food?.labels ?? food?.tag;
  if (raw == null) return [];

  // 第一步：先把各种类型统一转为数组
  let arr = [];
  if (Array.isArray(raw)) {
    arr = raw;
  } else if (typeof raw === 'string') {
    const trimmed = raw.trim();
    if (trimmed.startsWith('[')) {
      try {
        arr = JSON.parse(trimmed);
        if (!Array.isArray(arr)) arr = [];
      } catch {
        arr = trimmed ? [trimmed] : [];
      }
    } else {
      arr = trimmed ? trimmed.split(/[,，、\s]+/).map(s => s.trim()).filter(Boolean) : [];
    }
  } else if (raw && typeof raw === 'object') {
    arr = Array.isArray(raw.list) ? raw.list : Array.isArray(raw.items) ? raw.items : [];
  }

  // 第二步：将数组每一项转为 { text, type }
  return arr.map(item => {
    if (item == null) return { text: '', type: '' };
    if (typeof item === 'string') return { text: item, type: '' };
    if (typeof item === 'number') return { text: String(item), type: '' };
    return {
      text: item.text ?? item.tagName ?? item.name ?? item.label ?? item.title ?? '',
      type: item.type ?? item.tagType ?? ''
    };
  }).filter(t => t.text !== '' && t.text != null);
});

const handleFoodClick = () => {
  const id = props.food?.id ?? props.food?.cuisineId ?? '';
  if (!id) {
    uni.showToast({ title: '暂无菜品信息', icon: 'none' });
    return;
  }
  const tableId = props.tableId != null && props.tableId !== '' ? String(props.tableId) : '';
  const qty = props.food?.quantity ?? 0;
  const q = [`cuisineId=${encodeURIComponent(id)}`];
  if (tableId) q.push(`tableId=${encodeURIComponent(tableId)}`);
  q.push(`quantity=${encodeURIComponent(String(qty))}`);
  go(`/pages/foodDetail/index?${q.join('&')}`);
};

const handleIncrease = () => {
  if (props.food.quantity >= 99) return;
  emit('increase', props.food);
};

const handleDecrease = () => {
  if (props.food.quantity > 0) {
    emit('decrease', props.food);
  }
};

// 获取价格整数部分
const getPriceMain = (price) => {
  if (!price) return '0';
  const priceStr = String(price);
  const dotIndex = priceStr.indexOf('.');
  return dotIndex > -1 ? priceStr.substring(0, dotIndex) : priceStr;
};

// 获取价格小数部分
const getPriceDecimal = (price) => {
  if (!price) return '';
  const priceStr = String(price);
  const dotIndex = priceStr.indexOf('.');
  return dotIndex > -1 ? priceStr.substring(dotIndex + 1) : '';
};
</script>

<style lang="scss" scoped>
.food-card {
  padding: 20rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.food-item {
  display: flex;
}

.food-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 8rpx;
  flex-shrink: 0;
  background-color: #f5f5f5;
}

.food-info {
  flex: 1;
  margin-left: 20rpx;
  display: flex;
  flex-direction: column;
  position: relative;
}

.food-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.food-title {
  font-weight: bold;
  font-size: 32rpx;
  color: #151515;
  flex: 1;
  margin-right: 20rpx;
}

.food-price {
  display: flex;
  align-items: baseline;
  color: #E61F19;
  line-height: 1;
  flex-shrink: 0;

  .price-symbol {
    font-size: 20rpx;
    font-weight: bold;
  }

  .price-main {
    font-size: 32rpx;
    font-weight: bold;
  }

  .price-decimal {
    font-size: 24rpx;
    font-weight: bold;
  }
}

.food-desc {
  font-size: 24rpx;
  color: #797979;
  margin-bottom: 10rpx;
  line-height: 1.5;
}

.food-tags {
  display: flex;
  gap: 10rpx;
  margin-bottom: 10rpx;
}

.food-tag {
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
  font-size: 20rpx;
  color: #333;
  background-color: #f0f0f0;

  &.signature {
    background: linear-gradient(90deg, #FCB13F 0%, #FC793D 100%);
    color: #fff;
  }

  &.spicy {
    background: #2E2E2E;
    color: #fff;
  }
}

.food-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10rpx;
}

.food-sales {
  font-size: 22rpx;
  color: #999;
  display: flex;
  align-items: center;
  gap: 4rpx;

  .star-icon {
    width: 26rpx;
    height: 26rpx;
  }

  .sales-text {
    font-size: 22rpx;
    color: #999;
  }
}

.food-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 214rpx;
  height: 58rpx;
  background: #F8F8F8;
  border-radius: 56rpx;
  box-sizing: border-box;
  padding: 0 3rpx;
}

.action-btn {
  width: 52rpx;
  height: 52rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 600;
  transition: all 0.3s;
  background-color: #fff;

  .action-icon {
    width: 24rpx;
    height: 24rpx;
  }
}

.quantity {
  font-size: 28rpx;
  color: #333;
  min-width: 40rpx;
  text-align: center;
}
</style>
