<template>
  <div class="leixing-page">
    <!-- 左侧竖向导航栏 -->
    <div class="sidebar">
      <div class="sidebar-title">菜品分类</div>
      <el-scrollbar class="sidebar-scroll">
        <el-menu
          default-active="main"
          class="sidebar-menu"
          mode="vertical"
          @select="handleSelect"
        >
 <!-- 菜品大类 -->
          <el-sub-menu index="dishes">
            <template #title>菜品</template>
            <el-menu-item index="staple">
              <span>主食</span>
            </el-menu-item>
            <el-menu-item index="chuan" >
              <span>川菜</span>
            </el-menu-item>
            <el-menu-item index="yue" >
              <span>粤菜</span>
            </el-menu-item>
            <el-menu-item index="xiang">
              <span>湘菜</span>
            </el-menu-item>
            <el-menu-item index="seafood">
              <span>海鲜</span>
            </el-menu-item>
            <el-menu-item index="western">
              <span>西餐</span>
            </el-menu-item>
            <el-menu-item index="home">
              <span>家常菜</span>
            </el-menu-item>
          </el-sub-menu>

          <!-- 饮品大类 -->
          <el-sub-menu index="drinks">
            <template #title>饮品</template>
            <el-menu-item index="coffee">
              <span>咖啡</span>
            </el-menu-item>
            <el-menu-item index="tea">
              <span>茶饮</span>
            </el-menu-item>
            <el-menu-item index="juice">
              <span>果汁</span>
            </el-menu-item>
            <el-menu-item index="milktea">
              <span>奶茶</span>
            </el-menu-item>
            <el-menu-item index="alcohol">
              <span>酒品</span>
            </el-menu-item>
          </el-sub-menu>

          <!-- 甜品小吃大类 -->
          <el-sub-menu index="desserts">
            <template #title>甜品小吃</template>
            <el-menu-item index="cake">
              <span>蛋糕</span>
            </el-menu-item>
            <el-menu-item index="pudding">
              <span>布丁</span>
            </el-menu-item>
            <el-menu-item index="fried">
              <span>炸物</span>
            </el-menu-item>
            <el-menu-item index="icecream">
              <span>冰淇淋</span>
            </el-menu-item>
            <el-menu-item index="healthy">
              <span>健康轻食</span>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-scrollbar>
    </div>

    <!-- 右侧内容区 -->
    <div class="content">
      <div class="page-title">
        <span v-if="currentCategoryName">{{ currentCategoryName }} - 菜品列表</span>
        <span v-else>全部菜品</span>
      </div>
  <!-- 如果没有菜品 -->
  <div v-if="filteredProducts.length === 0" class="no-products">
    <p>没有该类菜品</p>
  </div>
      <el-row :gutter="20" class="products-grid">
        <el-col :span="6" v-for="product in filteredProducts" :key="product.dishId">
          <el-card shadow="hover" class="product-card">
            <img :src="product.imageUrl" class="product-img" />
            <h3>菜名: {{ product.dishName }}</h3>
            <p>{{ product.description }}</p>
             <p>价格: ¥{{ product.price }}</p>
            <el-button type="primary" @click="goToDetail(product.dishId)">查看菜品详情</el-button>
          </el-card>
        </el-col>
      </el-row>
      <div v-if="isBottom" class="bottom-tip">已经到底了</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';  
import { ElMessage } from 'element-plus';
// 定义类型
interface Dish {
  dishId: number;
  dishName: string;
  category: string;
  price: number;
  stock: number;
  status: string;
  description: string;
  imageUrl: string;
  sales: number;
}
const categoryMap: Record<string, string> = {
  chuan: '川菜',
  yue: '粤菜',
  xiang: '湘菜',
  staple: '主食',
  seafood: '海鲜',
  western: '西餐',
  home: '家常菜',
  coffee: '咖啡',
  tea: '茶饮',
  juice: '果汁',
  milktea: '奶茶',
  alcohol: '酒品',
  cake: '蛋糕',
  pudding: '布丁',
  fried: '炸物',
  icecream: '冰淇淋',
  healthy: '健康轻食',
};

const products = ref<Dish[]>([]);  // 存储所有的菜品
const filteredProducts = ref<Dish[]>([]);  // 存储经过过滤后的菜品
const categories = ref<string[]>([]);  // 存储菜品分类
const currentCategoryName = ref<string>('');  // 当前选择的分类名称
const isBottom = ref(false);  // 是否到底了
const selectedCategory = ref('川菜');
const selectedStoreId = localStorage.getItem('selectedStoreId');
// 获取所有菜品数据
const fetchDishes = async (category: string) => {
  const branchId = localStorage.getItem('selectedStoreId');
  if (!branchId) {
    ElMessage.error('未选择门店');
    return;
  }

  try {
    const res = await axios.get('/api/user/dishes/category', {//ok
      params: {
        category, 
        branchId
      }
    });
    products.value = res.data;

    if (products.value.length === 0) {
      ElMessage.warning('该分类下没有菜品');
    }

  } catch (err: any) {
    console.error('获取菜品失败:', err);
    if (err.response?.status === 404) {
      ElMessage.warning(err.response.data.message || '未找到该类菜品');
    } else {
      ElMessage.error('获取菜品失败');
    }
  }
};

// 获取所有菜品分类
const fetchcategories = async () => {
  try {
    const response = await axios.get('/api/user/dishes/categories');//ok
    categories.value = response.data;
  } catch (error) {
    console.error('获取分类数据失败:', error);
  }
};

const filterByCategory = async (category: string) => {
  const branchId = localStorage.getItem('selectedStoreId');  // 获取门店ID
  if (!branchId) {
    ElMessage.error('未选择门店');
    return;
  }

  try {
    currentCategoryName.value = category;  // 更新当前分类名称
    const response = await axios.get('/api/user/dishes/category', {//ok
      params: {
        category,
        branchId,
      }
    });

    filteredProducts.value = response.data;

    if (filteredProducts.value.length === 0) {
      ElMessage.warning('该分类下没有菜品');
    }

  } catch (error) {
    console.error('分类过滤失败:', error);
    ElMessage.error('加载菜品失败，请稍后再试');
  }
};

// 处理选择分类的事件
const handleSelect = (index: string) => {
  const categoryName = categoryMap[index] || index;
  filterByCategory(categoryName);
};
// 路由跳转到详情页
const router = useRouter();

function goToDetail(id: number) {
  router.push(`/user/detail/${id}`);
}

// 页面加载时调用获取数据的方法
onMounted(() => {
  fetchDishes(selectedCategory.value);
  fetchcategories();
});
</script>

<style scoped>
.leixing-page {
  display: flex;
  height: 100vh;
}

.sidebar {
  width: 240px;
  background-color: #5c4033;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
}

.sidebar-title {
  padding: 20px;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  text-align: center;
  background-color: #fff9db;
  border-bottom: 1px solid #ebeef5;
}

.sidebar-scroll {
  flex: 1;
  overflow-y: auto;
}

.sidebar-menu {
  border-right: none;
}
::v-deep(.el-sub-menu__title) {
  background-color: #f5a723;
  color: #000000;
  font-size: 20px;
  font-weight: 500;
  padding-left: 20px;
}
.sidebar-menu .el-menu-item {
  font-size: 20px;
  font-weight: 500;
  padding-left: 20px; /* 调整内边距，使文字居中 */
  background-color: #fccc0a;
  color: #000;
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.products-grid {
  margin-bottom: 30px;
}

.product-card {
  height: 100%;
}

.product-img {
  width: 100%;
  height: 180px;
  object-fit: cover;
}

.bottom-tip {
  text-align: center;
  padding: 20px;
  color: #000000;
  font-size: 16px;
}
.product-card .el-button {
  color: #000 !important;
  background-color: #fccc0a !important;
  border-color: #fccc0a !important;
}
.product-card {
  background-color: #fff8e1; /* 淡黄色背景 */
}
</style>