<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 基础配置
const baseURL = 'http://localhost:8080'

// 获取本地存储的accountId
const getAccountId = (): number | null => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  return userInfo ? userInfo.accountId : null
}

// 接口类型定义
interface Dish {
  dishId?: number
  dishName: string
  category: string
  price: number
  stock: number
  status: string
  description: string
  imageUrl: string
  sales?: number
  tag: string
}

interface ApiResponse<T> {
  code: number
  message: string
  data: T
}

interface PageData {
  records: Dish[]
  total: number
  current: number
  size: number
  pages: number
}

// 响应式数据
const dishes = ref<Dish[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentDish = ref<Dish>({
  dishName: '',
  category: '',
  price: 0,
  stock: 0,
  status: '在售',
  description: '',
  imageUrl: '',
  tag: ''
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索条件
const searchParams = ref({
  dishName: '',
  category: '',
  status: ''
})

// 分类选项
const categoryOptions = [
  '川菜', '粤菜', '湘菜', '海鲜', '西餐', '家常菜', '主食', 
  '咖啡', '茶饮', '果汁', '奶茶', '酒品', '蛋糕', '布丁', 
  '炸物', '冰淇淋', '健康轻食'
]

// 状态选项
const statusOptions = ['在售', '停售']

// 计算属性
const filteredDishes = computed(() => {
  return dishes.value.filter(dish => {
    return (!searchParams.value.dishName || dish.dishName.includes(searchParams.value.dishName)) &&
           (!searchParams.value.category || dish.category === searchParams.value.category) &&
           (!searchParams.value.status || dish.status === searchParams.value.status)
  })
})

// 获取菜品列表
const fetchDishes = async () => {
  loading.value = true
  try {
    const response = await axios.get<ApiResponse<PageData>>(`${baseURL}/branch/dishes`, {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        ...searchParams.value
      }
    })
    
    if (response.data.code === 200) {
      dishes.value = response.data.data.records
      total.value = response.data.data.total
      currentPage.value = response.data.data.current
    } else {
      ElMessage.error(response.data.message || '获取菜品列表失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试')
    console.error('获取菜品列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 打开新增对话框
const openAddDialog = () => {
  isEdit.value = false
  currentDish.value = {
    dishName: '',
    category: '',
    price: 0,
    stock: 0,
    status: '在售',
    description: '',
    imageUrl: '',
    tag: ''
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (dish: Dish) => {
  isEdit.value = true
  currentDish.value = { ...dish }
  dialogVisible.value = true
}

// 保存菜品
const saveDish = async () => {
  if (!currentDish.value.dishName.trim()) {
    ElMessage.warning('请输入菜品名称')
    return
  }
  
  if (!currentDish.value.category) {
    ElMessage.warning('请选择菜品分类')
    return
  }
  
  if (currentDish.value.price <= 0) {
    ElMessage.warning('请输入正确的价格')
    return
  }

  loading.value = true
  try {
    let response
    
    if (isEdit.value && currentDish.value.dishId) {
      // 更新菜品
      response = await axios.put<ApiResponse<{ dishId: number }>>(
        `${baseURL}/branch/dishes/${currentDish.value.dishId}`,
        currentDish.value
      )
    } else {
      // 新增菜品
      response = await axios.post<ApiResponse<{ dishId: number }>>(
        `${baseURL}/branch/dishes/`,
        currentDish.value
      )
    }
    
    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      dialogVisible.value = false
      await fetchDishes()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试')
    console.error('保存菜品失败:', error)
  } finally {
    loading.value = false
  }
}

// 删除菜品
const deleteDish = async (dish: Dish) => {
  try {
    await ElMessageBox.confirm('确定要删除这个菜品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    const response = await axios.delete<ApiResponse<null>>(`${baseURL}/branch/dishes/${dish.dishId}`)
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      await fetchDishes()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('网络错误，请重试')
      console.error('删除菜品失败:', error)
    }
  } finally {
    loading.value = false
  }
}

// 更新菜品状态
const updateDishStatus = async (dish: Dish, status: string) => {
  try {
    loading.value = true
    const response = await axios.patch<ApiResponse<null>>(
      `${baseURL}/branch/dishes/${dish.dishId}/status`,
      { status }
    )
    
    if (response.data.code === 200) {
      ElMessage.success('状态更新成功')
      dish.status = status
    } else {
      ElMessage.error(response.data.message || '状态更新失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试')
    console.error('更新状态失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索菜品
const searchDishes = () => {
  currentPage.value = 1
  fetchDishes()
}

// 重置搜索
const resetSearch = () => {
  searchParams.value = {
    dishName: '',
    category: '',
    status: ''
  }
  currentPage.value = 1
  fetchDishes()
}

// 页码改变
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchDishes()
}

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

// 初始化
onMounted(() => {
  fetchDishes()
})
</script>

<template>
  <div class="dish-management">
    <el-card class="search-card">
      <h2>菜品管理</h2>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchParams.dishName"
              placeholder="菜品名称"
              @keyup.enter="searchDishes"
              clearable
            />
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="searchParams.category"
              placeholder="菜品分类"
              clearable
            >
              <el-option
                v-for="category in categoryOptions"
                :key="category"
                :label="category"
                :value="category"
              />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="searchParams.status"
              placeholder="菜品状态"
              clearable
            >
              <el-option
                v-for="status in statusOptions"
                :key="status"
                :label="status"
                :value="status"
              />
            </el-select>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="searchDishes" :loading="loading">
              搜索
            </el-button>
            </el-col>
            <el-col :span="2">
            <el-button @click="resetSearch">重置</el-button>
            </el-col>
            <el-col :span="4">
            <el-button type="success" @click="openAddDialog">
              新增菜品
            </el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 菜品列表 -->
    <el-card class="table-card">
      <el-table :data="filteredDishes" v-loading="loading" stripe>
        <el-table-column prop="dishId" label="ID" width="80" />
        <el-table-column prop="dishName" label="菜品名称" min-width="120" />
        <el-table-column prop="category" label="分类" width="100" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="sales" label="销量" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '在售' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="tag" label="标签" width="120" />
        <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="openEditDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="scope.row.status === '在售'"
              type="warning"
              size="small"
              @click="updateDishStatus(scope.row, '停售')"
            >
              停售
            </el-button>
            <el-button
              v-else
              type="success"
              size="small"
              @click="updateDishStatus(scope.row, '在售')"
            >
              上架
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteDish(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑菜品' : '新增菜品'"
      width="600px"
    >
      <el-form :model="currentDish" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜品名称" required>
              <el-input v-model="currentDish.dishName" placeholder="请输入菜品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜品分类" required>
              <el-select v-model="currentDish.category" placeholder="请选择分类">
                <el-option
                  v-for="category in categoryOptions"
                  :key="category"
                  :label="category"
                  :value="category"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格" required>
              <el-input-number
                v-model="currentDish.price"
                :min="0"
                :precision="2"
                placeholder="请输入价格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存">
              <el-input-number
                v-model="currentDish.stock"
                :min="0"
                placeholder="请输入库存"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="currentDish.status">
                <el-option
                  v-for="status in statusOptions"
                  :key="status"
                  :label="status"
                  :value="status"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签">
              <el-input v-model="currentDish.tag" placeholder="请输入标签" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="图片URL">
          <el-input v-model="currentDish.imageUrl" placeholder="请输入图片链接" />
        </el-form-item>

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

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveDish" :loading="loading">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.dish-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-card h2 {
  margin: 0 0 20px 0;
  color: #303133;
}

.search-area {
  margin-bottom: 20px;
}

.table-card {
  min-height: 400px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

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

.el-input-number {
  width: 100%;
}

.el-select {
  width: 100%;
}

.el-table .cell {
  word-break: break-all;
}

.el-button + .el-button {
  margin-left: 10px;
}
</style>