<template>
  <div class="product-list">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span>菜品管理</span>
            <el-tag type="success" effect="dark" class="branch-tag">{{
              branch.branch_name
            }}</el-tag>
          </div>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加菜品
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="菜品名称">
            <el-input
              v-model="searchForm.dishName"
              placeholder="请输入菜品名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="分类">
            <el-select
              v-model="searchForm.category"
              placeholder="请选择分类"
              clearable
              style="width: 150px"
            >
              <el-option label="主食" value="主食" />
              <el-option label="小菜" value="小菜" />
              <el-option label="汤类" value="汤类" />
              <el-option label="饮品" value="饮品" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="在售" value="在售" />
              <el-option label="停售" value="停售" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" style="width: 100%" v-loading="loading" border stripe>
        <el-table-column prop="dishId" label="ID" width="80" align="center" />
        <el-table-column prop="dishName" label="菜品名称" min-width="150">
          <template #default="scope">
            <div class="dish-info">
              <el-image
                v-if="scope.row.imageUrl"
                :src="scope.row.imageUrl"
                style="width: 40px; height: 40px; border-radius: 4px; margin-right: 10px"
                fit="cover"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <span>{{ scope.row.dishName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="100" align="center" />
        <el-table-column prop="price" label="价格" width="100" align="center">
          <template #default="scope">
            <span class="price">￥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.stock > 10 ? 'success' : scope.row.stock > 0 ? 'warning' : 'danger'"
            >
              {{ scope.row.stock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '在售' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sales" label="销量" width="80" align="center" />
        <el-table-column prop="tag" label="标签" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.tag" size="small" type="info">
              {{ scope.row.tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)" type="info" link>
              查看
            </el-button>
            <el-button size="small" @click="handleEdit(scope.row)" type="primary" link>
              编辑
            </el-button>
            <el-button
              size="small"
              @click="handleToggleStatus(scope.row)"
              :type="scope.row.status === '在售' ? 'warning' : 'success'"
              link
            >
              {{ scope.row.status === '在售' ? '停售' : '上架' }}
            </el-button>
            <el-button size="small" @click="handleDelete(scope.row)" type="danger" link>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 菜品详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="菜品详情" width="600px">
      <div v-if="currentDish" class="dish-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="菜品ID">{{ currentDish.dishId }}</el-descriptions-item>
          <el-descriptions-item label="菜品名称">{{ currentDish.dishName }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{ currentDish.category }}</el-descriptions-item>
          <el-descriptions-item label="价格">￥{{ currentDish.price }}</el-descriptions-item>
          <el-descriptions-item label="库存">{{ currentDish.stock }}</el-descriptions-item>
          <el-descriptions-item label="销量">{{ currentDish.sales }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentDish.status === '在售' ? 'success' : 'danger'">
              {{ currentDish.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="标签">
            <el-tag v-if="currentDish.tag" type="info">{{ currentDish.tag }}</el-tag>
            <span v-else>无</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDateTime(currentDish.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">
            {{ formatDateTime(currentDish.updatedAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ currentDish.description || '无描述' }}
          </el-descriptions-item>
        </el-descriptions>
        <div v-if="currentDish.imageUrl" class="dish-image">
          <h4>菜品图片</h4>
          <el-image :src="currentDish.imageUrl" style="width: 200px; height: 200px" fit="cover">
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑菜品对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑菜品" width="800px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜品名称" prop="dishName">
              <el-input v-model="editForm.dishName" placeholder="请输入菜品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="editForm.category" placeholder="请选择分类" style="width: 100%">
                <el-option label="主食" value="主食" />
                <el-option label="小菜" value="小菜" />
                <el-option label="汤类" value="汤类" />
                <el-option label="饮品" value="饮品" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number
                v-model="editForm.price"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="请输入价格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input-number
                v-model="editForm.stock"
                :min="0"
                style="width: 100%"
                placeholder="请输入库存"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="editForm.status">
                <el-radio value="在售">在售</el-radio>
                <el-radio value="停售">停售</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签">
              <el-input v-model="editForm.tag" placeholder="请输入标签" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="图片URL">
          <el-input v-model="editForm.imageUrl" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入菜品描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加菜品对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加菜品" width="800px">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜品名称" prop="dishName">
              <el-input v-model="addForm.dishName" placeholder="请输入菜品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="addForm.category" placeholder="请选择分类" style="width: 100%">
                <el-option label="主食" value="主食" />
                <el-option label="小菜" value="小菜" />
                <el-option label="汤类" value="汤类" />
                <el-option label="饮品" value="饮品" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number
                v-model="addForm.price"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="请输入价格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input-number
                v-model="addForm.stock"
                :min="0"
                style="width: 100%"
                placeholder="请输入库存"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="addForm.status">
                <el-radio value="在售">在售</el-radio>
                <el-radio value="停售">停售</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签">
              <el-input v-model="addForm.tag" placeholder="请输入标签" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="图片URL">
          <el-input v-model="addForm.imageUrl" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="addForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入菜品描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveAdd">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Plus, Picture } from '@element-plus/icons-vue'
import axios from 'axios'

// 接口类型定义
interface Dish {
  dishId: number
  dishName: string
  category: string
  price: number
  stock: number
  status: '在售' | '停售'
  description?: string
  imageUrl?: string
  sales: number
  tag?: string
  isDeleted: number
  deletedAt?: string
  createdAt: string
  updatedAt: string
}

interface SearchForm {
  dishName: string
  category: string
  status: string
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// 响应式数据
const loading = ref(false)
const tableData = ref<Dish[]>([])
const detailDialogVisible = ref(false)
const editDialogVisible = ref(false)
const addDialogVisible = ref(false)
const currentDish = ref<Dish | null>(null)
const editFormRef = ref<FormInstance>()
const addFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive<SearchForm>({
  dishName: '',
  category: '',
  status: '',
})

// 分页数据
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 5,
  total: 0,
})

// 编辑表单
const editForm = reactive({
  dishId: 0,
  dishName: '',
  category: '',
  price: 0,
  stock: 0,
  status: '在售' as '在售' | '停售',
  description: '',
  imageUrl: '',
  tag: '',
})

// 添加表单
const addForm = reactive({
  dishName: '',
  category: '',
  price: 0,
  stock: 0,
  status: '在售' as '在售' | '停售',
  description: '',
  imageUrl: '',
  tag: '',
})

const branch = reactive({
  branch_id: 1,
  branch_name: '中山路总店',
  branch_address: '广东省深圳市福田区中山路123号',
  branch_phone: '0755-88888888',
  branch_start: '08:00',
  branch_end: '22:00',
  branch_status: '营业中',
  branch_boss: 'ACC001',
  is_deleted: 0,
  deleted_at: null,
  created_at: '2025-06-15 13:29:22',
  updated_at: '2025-06-15 15:21:51',
})

// 编辑表单验证规则
const editRules = {
  dishName: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

// 添加表单验证规则
const addRules = {
  dishName: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

// API 基础URL
const API_BASE_URL = 'http://localhost:8080/api'

// 获取菜品列表
const fetchDishes = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      dishName: searchForm.dishName,
      category: searchForm.category,
      status: searchForm.status,
    }

    // 使用店铺ID查询对应菜单菜品
    const response = await axios.get(`${API_BASE_URL}/dishes/branch/${branch.branch_id}`, {
      params,
    })
    tableData.value = response.data.data.records
    pagination.total = response.data.data.total
  } catch (error) {
    console.error('获取菜品列表失败:', error)
    ElMessage.error('获取菜品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取店铺所有菜品（不分页）
const fetchAllDishes = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/dishes/branch/${branch.branch_id}/all`)
    return response.data.data
  } catch (error) {
    console.error('获取所有菜品失败:', error)
    ElMessage.error('获取所有菜品失败')
    return []
  }
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchDishes()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    dishName: '',
    category: '',
    status: '',
  })
  pagination.currentPage = 1
  fetchDishes()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchDishes()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchDishes()
}

// 添加菜品
const handleAdd = () => {
  // 重置添加表单
  Object.assign(addForm, {
    dishName: '',
    category: '',
    price: 0,
    stock: 0,
    status: '在售',
    description: '',
    imageUrl: '',
    tag: '',
  })
  addDialogVisible.value = true
}

// 查看详情
const handleView = (dish: Dish) => {
  currentDish.value = dish
  detailDialogVisible.value = true
}

// 编辑菜品
const handleEdit = (dish: Dish) => {
  Object.assign(editForm, {
    dishId: dish.dishId,
    dishName: dish.dishName,
    category: dish.category,
    price: dish.price,
    stock: dish.stock,
    status: dish.status,
    description: dish.description || '',
    imageUrl: dish.imageUrl || '',
    tag: dish.tag || '',
  })
  editDialogVisible.value = true
}

// 保存编辑
const handleSaveEdit = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate((valid) => {
    if (valid) {
      saveEditDish()
    }
  })
}

// 保存编辑数据
const saveEditDish = async () => {
  try {
    // 在表单数据中添加店铺ID
    const dishData = { ...editForm, branchId: branch.branch_id }
    const response = await axios.put(`${API_BASE_URL}/dishes/${editForm.dishId}`, dishData)
    ElMessage.success('编辑成功')
    editDialogVisible.value = false
    fetchDishes()
  } catch (error) {
    console.error('编辑失败:', error)
    ElMessage.error('编辑失败')
  }
}

// 切换状态
const handleToggleStatus = async (dish: Dish) => {
  try {
    const newStatus = dish.status === '在售' ? '停售' : '在售'
    await axios.patch(`${API_BASE_URL}/dishes/${dish.dishId}/status`, {
      status: newStatus,
      branchId: branch.branch_id,
    })
    ElMessage.success(`${newStatus === '在售' ? '上架' : '停售'}成功`)
    fetchDishes()
  } catch (error) {
    console.error('状态切换失败:', error)
    ElMessage.error('状态切换失败')
  }
}

// 删除菜品
const handleDelete = async (dish: Dish) => {
  try {
    await ElMessageBox.confirm(`确定要删除菜品"${dish.dishName}"吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 删除时传递店铺ID参数
    await axios.delete(`${API_BASE_URL}/dishes/${dish.dishId}`, {
      params: { branchId: branch.branch_id },
    })
    ElMessage.success('删除成功')
    fetchDishes()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 保存添加
const handleSaveAdd = async () => {
  if (!addFormRef.value) return

  await addFormRef.value.validate((valid) => {
    if (valid) {
      saveAddDish()
    }
  })
}

// 保存添加数据
const saveAddDish = async () => {
  try {
    // 添加时需要传递店铺ID
    const dishData = { ...addForm, branchId: branch.branch_id }
    const response = await axios.post(`${API_BASE_URL}/dishes`, dishData)
    ElMessage.success('添加成功')
    addDialogVisible.value = false
    fetchDishes()
  } catch (error) {
    console.error('添加失败:', error)
    ElMessage.error('添加失败')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchDishes()
})
</script>

<style scoped>
.product-list {
  padding: 0px;
}

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

.header-left {
  display: flex;
  align-items: center;
}

.branch-tag {
  margin-left: 10px;
}

.search-bar {
  margin-bottom: 5px;
}

.search-form {
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}

.dish-info {
  display: flex;
  align-items: center;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-wrapper {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.dish-detail {
  margin-bottom: 10px;
}

.dish-image {
  margin-top: 10px;
  text-align: center;
}

.dish-image h4 {
  margin-bottom: 10px;
}
</style>
