<template>
  <div class="dish-management">
    <el-card class="main-card">
      <!-- 顶部操作 -->
      <template #header>
        <div class="card-header">
          <el-row :gutter="20" align="middle">
            <el-col :span="12">
              <el-input 
                v-model="searchQuery" 
                placeholder="输入菜品ID或名称搜索" 
                clearable 
                @input="handleSearchInput"
                class="search-input"
              >
              </el-input>
            </el-col>
            <el-col :span="6" class="text-right">
              <!-- 调整按钮顺序和间距 -->
              <el-button type="primary" @click="handleAdd" class="add-btn">
                <el-icon><Plus /></el-icon>新增菜品
              </el-button>
              </el-col>
              <el-col :span="6" class="text-right">
              <el-button 
                type="success" 
                @click="handleExport"
                class="export-btn"
                :loading="exportLoading"
              >
                <el-icon><Download /></el-icon>导出Excel
              </el-button>
            </el-col>
          </el-row>
        </div>
      </template>

      <!-- 分类导航 -->
      <el-row :gutter="20" class="menu-container">
        <el-col :span="4">
          <el-menu
            default-active="products-1-1"
            class="category-menu"
            @select="handleMenuSelect"
          >
            <!-- 菜品 -->
            <el-sub-menu index="products-1">
              <template #title><el-icon><Food /></el-icon>菜品</template>
              <el-menu-item index="products-1-1">川菜</el-menu-item>
              <el-menu-item index="products-1-2">粤菜</el-menu-item>
              <el-menu-item index="products-1-3">湘菜</el-menu-item>
              <el-menu-item index="products-1-4">海鲜</el-menu-item>
              <el-menu-item index="products-1-5">西餐</el-menu-item>
              <el-menu-item index="products-1-6">家常菜</el-menu-item>
              <el-menu-item index="products-1-7">主食</el-menu-item>
            </el-sub-menu>

            <!-- 饮品 -->
            <el-sub-menu index="products-5">
              <template #title><el-icon><ColdDrink /></el-icon>饮品</template>
              <el-menu-item index="products-5-1">咖啡</el-menu-item>
              <el-menu-item index="products-5-2">茶饮</el-menu-item>
              <el-menu-item index="products-5-3">果汁 </el-menu-item>
              <el-menu-item index="products-5-4">奶茶</el-menu-item>
              <el-menu-item index="products-5-5">酒品</el-menu-item>
            </el-sub-menu>

            <!-- 甜点小食 -->
            <el-sub-menu index="products-6">
              <template #title><el-icon><Fries /></el-icon>甜点小食</template>
              <el-menu-item index="products-6-1">蛋糕</el-menu-item>
              <el-menu-item index="products-6-2">布丁</el-menu-item>
              <el-menu-item index="products-6-3">炸物</el-menu-item>
              <el-menu-item index="products-6-4">冰淇淋</el-menu-item>
              <el-menu-item index="products-6-5">健康轻食</el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-col>

        <!-- 菜品展示区域 -->
        <el-col :span="20">
          <el-card class="account-card">
            <el-table :data="currentDishList" border style="width: 100%" class="account-table">
              <!-- 菜品图片列 -->
              <el-table-column label="菜品图片" width="80" align="center">
                <template #default="{ row }">
                  <el-image
                    :src="row.imageUrl || 'https://via.placeholder.com/50x50'"
                    :alt="row.dishName"
                    class="dish-img"
                    :preview-src-list="[row.imageUrl]"
                  />
                </template>
              </el-table-column>

              <el-table-column prop="dishId" label="菜品ID" width="120" />
              <el-table-column prop="dishName" label="菜品名称" />
              <el-table-column prop="price" label="价格(元)" width="120" align="right">
                <template #default="{ row }">
                  {{ row.price.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="stock" label="库存" width="80" align="center" />
              <!-- 修复：根据数据库中的实际状态显示 -->
              <el-table-column prop="status" label="状态" width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.status === '在售' ? 'success' : 'info'" effect="dark">
                    {{ row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="上架时间" width="180">
                <template #default="{ row }">
                  {{ formatDateTime(row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column prop="updatedAt" label="更新时间" width="180">
                <template #default="{ row }">
                  {{ formatDateTime(row.updatedAt) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" align="center">
                <template #default="{ row }">
                  <el-button link type="primary" @click="handleEdit(row)" class="action-btn">
                    <el-icon><Edit /></el-icon>编辑
                  </el-button>
                  <el-button link type="danger" @click="handleDelete(row)" class="action-btn">
                    <el-icon><Delete /></el-icon>删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-pagination
              v-model:current-page="pagination.page"
              v-model:page-size="pagination.pageSize"
              :total="pagination.total"
              layout="total, prev, pager, next, jumper"
              class="pagination"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增/编辑菜品弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="dishForm.dishId ? '编辑菜品' : '新增菜品'" width="40%" class="account-dialog">
      <el-form :model="dishForm" ref="formRef" :rules="rules" label-width="120px" class="account-form">
        <!-- 菜品名称 -->
        <el-form-item label="菜品名称" prop="dishName">
          <el-input v-model="dishForm.dishName" autocomplete="off" placeholder="请输入菜品名称" />
        </el-form-item>

        <!-- 价格 -->
        <el-form-item label="价格(元)" prop="price">
          <el-input-number 
            v-model="dishForm.price" 
            :precision="2" 
            :step="0.1" 
            :min="0" 
            controls-position="right" 
            style="width: 100%"
          />
        </el-form-item>

        <!-- 库存 -->
        <el-form-item label="库存" prop="stock">
          <el-input-number 
            v-model="dishForm.stock" 
            :min="0" 
            controls-position="right" 
            style="width: 100%"
          />
        </el-form-item>

        <!-- 图片地址 -->
        <el-form-item label="图片地址" prop="imageUrl">
          <el-input v-model="dishForm.imageUrl" placeholder="请输入图片URL" />
          <div class="preview-container" v-if="dishForm.imageUrl">
            <div class="preview-label">图片预览</div>
            <el-image 
              :src="dishForm.imageUrl" 
              class="image-preview"
              fit="cover"
            />
          </div>
        </el-form-item>

        <!-- 菜品描述 -->
        <el-form-item label="菜品描述" prop="description">
          <el-input v-model="dishForm.description" type="textarea" :rows="3" placeholder="请输入菜品描述" />
        </el-form-item>

        <!-- 分类 -->
        <el-form-item label="菜品分类" prop="category">
          <el-input v-model="dishForm.category" placeholder="请输入菜品分类" />
        </el-form-item>

        <!-- 标签 -->
        <el-form-item label="菜品标签" prop="tag">
          <el-input v-model="dishForm.tag" placeholder="多个标签用逗号分隔" />
        </el-form-item>

        <!-- 菜品状态 -->
        <el-form-item label="菜品状态" prop="status">
          <el-radio-group v-model="dishForm.status">
            <el-radio label="在售">在售</el-radio>
            <el-radio label="停售">停售</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="handleConfirm" class="confirm-btn">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import {
  Food,
  ColdDrink,
  Fries,
  Edit,
  Delete,
  Search,
  Plus,
  Download // 新增导出图标
} from '@element-plus/icons-vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

// 搜索相关
const searchQuery = ref('');
const isSearching = ref(false);

// 分页配置
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});

// 导出加载状态
const exportLoading = ref(false);

// 存储菜品数据
const dishList = ref([]);

// 当前选中的菜单项
const currentCategory = ref('products-1-1');

// 分类映射表（菜单index -> 后端category）
const categoryMap = {
  'products-1-1': '川菜',
  'products-1-2': '粤菜',
  'products-1-3': '湘菜',
  'products-1-4': '海鲜',
  'products-1-5': '西餐',
  'products-1-6': '家常菜',
  'products-1-7': '主食',
  'products-5-1': '咖啡',
  'products-5-2': '茶饮',
  'products-5-3': '果汁',
  'products-5-4': '奶茶',
  'products-5-5': '酒品',
  'products-6-1': '蛋糕',
  'products-6-2': '布丁',
  'products-6-3': '炸物',
  'products-6-4': '冰淇淋',
  'products-6-5': '健康轻食',
};

// 动态计算当前展示的菜品数据
const currentDishList = computed(() => {
  return dishList.value;
});

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};

// 获取菜品数据（按分类）
const fetchDishes = async (category, page, size) => {
  try {
    const response = await axios.get(`http://localhost:8080/admin/dishes/category/${category}`, {
      params: {
        page: page,
        size: size
      }
    });

    pagination.value.total = response.data.total;
    dishList.value = response.data.records;
    isSearching.value = false;
  } catch (error) {
    console.error('获取菜品数据失败：', error);
    ElMessage.error('获取菜品数据失败');
  }
};

// 搜索菜品（支持ID和名称）
const searchDishes = async (keyword, page, size) => {
  try {
    const response = await axios.get('http://localhost:8080/admin/dishes/search', {
      params: {
        keyword: keyword,
        page: page,
        size: size
      }
    });
    
    pagination.value.total = response.data.total;
    dishList.value = response.data.records;
    isSearching.value = true;
  } catch (error) {
    console.error('搜索菜品失败:', error);
    ElMessage.error('搜索菜品失败');
  }
};

// 新增/编辑菜品相关代码
const dialogFormVisible = ref(false);
const formRef = ref();
const dishForm = ref({
  dishId: null,
  dishName: '',
  price: 0,
  stock: 0,
  imageUrl: '',
  description: '',
  category: '',
  tag: '',
  status: '在售' // 默认状态为"在售"
});

// 表单验证规则
const rules = ref({
  dishName: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', message: '价格必须是数字', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', message: '库存必须是数字', trigger: 'blur' }
  ],
  imageUrl: [{ required: true, message: '请输入图片地址', trigger: 'blur' }],
  category: [{ required: true, message: '请输入菜品分类', trigger: 'blur' }],
  status: [{ required: true, message: '请选择菜品状态', trigger: 'change' }]
});

// 导出Excel处理函数
const handleExport = async () => {
  exportLoading.value = true;
  try {
    const category = categoryMap[currentCategory.value];
    const response = await axios.get(
      `http://localhost:8080/admin/dishes/export/${category}`,
      {
        responseType: 'blob' // 重要：指定响应类型为blob
      }
    );
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `菜品数据_${category}.xlsx`);
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败: ' + error.message);
  } finally {
    exportLoading.value = false;
  }
};

// 处理新增操作
const handleAdd = () => {
  dialogFormVisible.value = true;
  dishForm.value = {
    dishId: null,
    dishName: '',
    price: 0,
    stock: 0,
    imageUrl: '',
    description: '',
    category: '',
    tag: '',
    status: '在售' // 新增菜品默认状态为"在售"
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 处理编辑操作
const handleEdit = (row) => {
  dialogFormVisible.value = true;
  // 复制所有字段，包括后端新增的字段
  dishForm.value = { 
    ...row,
    price: parseFloat(row.price)
  };
};

// 确认新增/编辑操作
const handleConfirm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      const url = dishForm.value.dishId 
        ? `http://localhost:8080/admin/dishes/${dishForm.value.dishId}` 
        : 'http://localhost:8080/admin/dishes';
      
      const method = dishForm.value.dishId ? 'put' : 'post';

      axios[method](url, dishForm.value)
        .then(response => {
          if (response.status >= 200 && response.status < 300) {
            ElMessage.success(dishForm.value.dishId ? '菜品更新成功' : '菜品新增成功');
            dialogFormVisible.value = false;
            
            // 刷新数据
            if (isSearching.value) {
              searchDishes(searchQuery.value, pagination.value.page, pagination.value.pageSize);
            } else {
              fetchDishes(
                categoryMap[currentCategory.value], 
                pagination.value.page, 
                pagination.value.pageSize
              );
            }
          } else {
            ElMessage.error('菜品操作失败');
          }
        })
        .catch(error => {
          console.error('请求失败:', error);
          ElMessage.error('请求失败，请稍后重试');
        });
    }
  });
};

// 删除菜品
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除菜品 "${row.dishName}" 吗？此操作不可逆！`,
    '删除确认',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    axios.delete(`http://localhost:8080/admin/dishes/${row.dishId}`)
      .then(response => {
        if (response.status >= 200 && response.status < 300) {
          ElMessage.success('删除成功');
          if (isSearching.value) {
            searchDishes(searchQuery.value, pagination.value.page, pagination.value.pageSize);
          } else {
            fetchDishes(
              categoryMap[currentCategory.value], 
              pagination.value.page, 
              pagination.value.pageSize
            );
          }
        } else {
          ElMessage.error('删除失败，请稍后重试');
        }
      })
      .catch(error => {
        console.error('删除菜品失败:', error);
        ElMessage.error('删除失败，请稍后重试');
      });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 搜索输入变化时触发
const handleSearchInput = (val) => {
  if (val.trim() === '') {
    fetchDishes(
      categoryMap[currentCategory.value], 
      pagination.value.page, 
      pagination.value.pageSize
    );
  }
};

// 事件处理
const handleMenuSelect = (index) => {
  currentCategory.value = index;
  pagination.value.page = 1;
  if (searchQuery.value) {
    searchQuery.value = '';
  }
  fetchDishes(categoryMap[index], 1, pagination.value.pageSize);
};

const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  if (isSearching.value) {
    searchDishes(searchQuery.value, 1, size);
  } else {
    fetchDishes(categoryMap[currentCategory.value], 1, size);
  }
};

const handlePageChange = (page) => {
  if (isSearching.value) {
    searchDishes(searchQuery.value, page, pagination.value.pageSize);
  } else {
    fetchDishes(categoryMap[currentCategory.value], page, pagination.value.pageSize);
  }
};

// 监听搜索框变化
watch(searchQuery, (newVal) => {
  if (newVal) {
    searchDishes(newVal, 1, pagination.value.pageSize);
  } else {
    fetchDishes(
      categoryMap[currentCategory.value], 
      1, 
      pagination.value.pageSize
    );
  }
});

// 组件挂载时加载默认分类数据
onMounted(() => {
  fetchDishes(categoryMap[currentCategory.value], 1, pagination.value.pageSize);
});
</script>

<style scoped>
.dish-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.main-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
}

.main-card :deep(.el-card__header) {
  background: linear-gradient(120deg, #f0f7ff, #e6f7ff);
  border-radius: 12px 12px 0 0;
  padding: 16px 24px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.search-input {
  max-width: 400px;
}

.search-input :deep(.el-input__inner) {
  border-radius: 20px;
  height: 40px;
  padding-left: 40px;
}

.search-input :deep(.el-input__prefix) {
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #888;
}

/* 调整按钮顺序和间距 */
.text-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px; /* 添加按钮间距 */
}

.add-btn {
  border-radius: 20px;
  padding: 10px 20px;
  font-weight: 600;
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.25);
  background: linear-gradient(45deg, #409eff, #64b5f6);
  border: none;
  transition: all 0.3s;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(64, 158, 255, 0.35);
}

.export-btn {
  border-radius: 20px;
  padding: 10px 20px;
  font-weight: 600;
  box-shadow: 0 4px 10px rgba(103, 194, 58, 0.25);
  background: linear-gradient(45deg, #67c23a, #85ce61);
  border: none;
  transition: all 0.3s;
}

.export-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(103, 194, 58, 0.35);
}

.menu-container {
  margin-top: 12px;
}

.category-menu {
  height: 600px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.category-menu :deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  font-size: 15px;
  color: #5a5e66;
  transition: all 0.2s;
  border-radius: 8px;
  margin: 4px 8px;
  width: calc(100% - 16px);
}

.category-menu :deep(.el-menu-item):hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.category-menu :deep(.el-menu-item.is-active) {
  background: linear-gradient(90deg, #ecf5ff, #fff);
  color: #409eff;
  font-weight: 600;
  border-left: 4px solid #409eff;
}

.category-menu .el-icon {
  margin-right: 10px;
  font-size: 18px;
}

.account-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.account-card :deep(.el-card__body) {
  padding: 0;
}

.account-table {
  border-radius: 8px;
  overflow: hidden;
}

.account-table :deep(th) {
  background-color: #f5f7fa !important;
  color: #409eff;
  font-weight: 600;
}

.account-table :deep(tr:hover) {
  background-color: #f0f7ff !important;
}

.dish-img {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
  display: block;
  margin: 0 auto;
  background-color: #f5f5f5;
}

.action-btn {
  padding: 5px 8px;
  font-size: 13px;
  border-radius: 4px;
  margin: 0 2px;
}

.action-btn .el-icon {
  margin-right: 4px;
}

.pagination {
  padding: 20px;
  display: flex;
  justify-content: flex-end;
}

.account-dialog :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.account-form {
  padding: 0 20px;
}

.account-form .el-form-item {
  margin-bottom: 22px;
}

.account-form :deep(.el-input__inner),
.account-form :deep(.el-textarea__inner) {
  border-radius: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px 20px;
}

.cancel-btn {
  border-radius: 20px;
  padding: 8px 20px;
}

.confirm-btn {
  border-radius: 20px;
  padding: 8px 20px;
  background: linear-gradient(45deg, #409eff, #64b5f6);
  border: none;
  transition: all 0.3s;
}

.confirm-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.3);
}

.preview-container {
  margin-top: 10px;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 8px;
}

.preview-label {
  font-size: 12px;
  color: #888;
  margin-bottom: 5px;
}

.image-preview {
  width: 100px;
  height: 100px;
  border-radius: 6px;
  border: 1px solid #eee;
}

/* 确保在小屏幕下按钮组也能正确显示 */
@media (max-width: 768px) {
  .text-right {
    flex-wrap: wrap;
    justify-content: flex-end;
  }
  
  .text-right .el-button {
    margin-top: 10px;
  }
}
</style>