<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dailyMealPlanApi } from '@/api/meal.js'
import { customerApi } from '@/api/crm.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const customers = ref([])

const searchForm = reactive({ customer_id: '', plan_date: '', meal_type: '', status: '' })
const pagination = reactive({ page: 1, per_page: 30 })

const form = reactive({ id: null, customer_id: '', plan_date: '', meal_type: 1, dishes: [], special_note: '' })
const isEdit = ref(false)

const mealTypeMap = { 1: '早餐', 2: '午餐', 3: '下午茶', 4: '晚餐', 5: '宵夜' }
const statusMap = { 0: '待备餐', 1: '已备餐', 2: '已送达', 3: '未用' }
const statusType = { 0: 'info', 1: 'warning', 2: 'success', 3: 'danger' }

async function fetchList() {
  loading.value = true
  try { const res = await dailyMealPlanApi.getList({ ...searchForm, ...pagination }); tableData.value = res.data?.list || res.data?.data || []; total.value = res.data?.total || 0 } finally { loading.value = false }
}

async function fetchCustomers() { try { const res = await customerApi.getList({ per_page: 500, status: 3 }); customers.value = res.data?.list || res.data?.data || [] } catch {} }

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() { Object.assign(searchForm, { customer_id: '', plan_date: '', meal_type: '', status: '' }); handleSearch() }
function handleAdd() { isEdit.value = false; Object.assign(form, { id: null, customer_id: '', plan_date: '', meal_type: 1, dishes: [], special_note: '' }); dialogVisible.value = true }

async function handleSubmit() {
  submitLoading.value = true
  try {
    if (isEdit.value) { await dailyMealPlanApi.update(form.id, form) } else { await dailyMealPlanApi.create(form) }
    ElMessage.success(isEdit.value ? '更新成功' : '创建成功'); dialogVisible.value = false; fetchList()
  } finally { submitLoading.value = false }
}

async function handleDeliver(row) {
  await ElMessageBox.confirm('确认已送达？', '送达确认', { type: 'info' })
  await dailyMealPlanApi.deliver(row.id); ElMessage.success('已标记送达'); fetchList()
}

async function handleStatusChange(row, status) {
  await dailyMealPlanApi.updateStatus(row.id, { status }); ElMessage.success('状态更新成功'); fetchList()
}

async function handleDelete(row) {
  await ElMessageBox.confirm('确定删除该排餐吗？', '删除确认', { type: 'warning' })
  await dailyMealPlanApi.delete(row.id); ElMessage.success('删除成功'); fetchList()
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }
onMounted(() => { fetchList(); fetchCustomers() })
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-select v-model="searchForm.customer_id" placeholder="选择客户" clearable filterable style="width:180px"><el-option v-for="c in customers" :key="c.id" :label="c.name" :value="c.id" /></el-select>
      <el-date-picker v-model="searchForm.plan_date" type="date" value-format="YYYY-MM-DD" placeholder="日期" style="width:160px" />
      <el-select v-model="searchForm.meal_type" placeholder="餐型" clearable style="width:120px"><el-option v-for="(v,k) in mealTypeMap" :key="k" :label="v" :value="Number(k)" /></el-select>
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width:120px"><el-option v-for="(v,k) in statusMap" :key="k" :label="v" :value="Number(k)" /></el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3"></div>
        <el-button type="primary" @click="handleAdd">新增排餐</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column label="客户" min-width="100"><template #default="{ row }">{{ row.customer?.name || '-' }}</template></el-table-column>
          <el-table-column prop="plan_date" label="日期" width="110" />
          <el-table-column label="餐型" width="80" align="center"><template #default="{ row }">{{ mealTypeMap[row.meal_type] }}</template></el-table-column>
          <el-table-column prop="special_note" label="特殊备注" min-width="150" show-overflow-tooltip />
          <el-table-column label="评分" width="70" align="center"><template #default="{ row }">{{ row.review?.score || '-' }}</template></el-table-column>
          <el-table-column label="状态" width="90" align="center"><template #default="{ row }"><el-tag :type="statusType[row.status]" size="small">{{ statusMap[row.status] }}</el-tag></template></el-table-column>
          <el-table-column label="操作" width="220" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.status<2" size="small" type="success" text @click="handleDeliver(row)">送达</el-button>
              <el-dropdown v-if="row.status<2" trigger="click" @command="(cmd) => handleStatusChange(row, cmd)" style="margin:0 8px">
                <el-button size="small" type="warning" text>状态</el-button>
                <template #dropdown><el-dropdown-menu><el-dropdown-item v-for="(v,k) in statusMap" :key="k" :command="Number(k)">{{ v }}</el-dropdown-item></el-dropdown-menu></template>
              </el-dropdown>
              <el-button v-if="row.status===0" size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page" :total="total" :page-sizes="[10,30,50]" layout="total,sizes,prev,pager,next,jumper" background @current-change="handlePageChange" @size-change="handleSizeChange" />
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="isEdit?'编辑排餐':'新增排餐'" width="550px" destroy-on-close>
      <el-form :model="form" label-width="80px">
        <el-form-item label="客户"><el-select v-model="form.customer_id" filterable style="width:100%"><el-option v-for="c in customers" :key="c.id" :label="c.name" :value="c.id" /></el-select></el-form-item>
        <el-form-item label="日期"><el-date-picker v-model="form.plan_date" type="date" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item>
        <el-form-item label="餐型"><el-select v-model="form.meal_type" style="width:100%"><el-option v-for="(v,k) in mealTypeMap" :key="k" :label="v" :value="Number(k)" /></el-select></el-form-item>
        <el-form-item label="特殊备注"><el-input v-model="form.special_note" type="textarea" :rows="3" placeholder="如：忌辣、素食等" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="dialogVisible=false">取消</el-button><el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button></template>
    </el-dialog>
  </div>
</template>
