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

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

const searchForm = reactive({ name: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({
  id: null, name: '', description: '', week_num: 1, status: 1
})
const isEdit = ref(false)

const weekOptions = Array.from({ length: 6 }, (_, i) => ({ label: `第 ${i + 1} 周`, value: i + 1 }))
const statusMap = { 1: '启用', 0: '停用' }

const formRules = {
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  week_num: [{ required: true, message: '请选择适用周数', trigger: 'change' }]
}

async function fetchList() {
  loading.value = true
  try {
    const res = await mealTemplateApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } catch {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() { Object.assign(searchForm, { name: '' }); handleSearch() }

function handleAdd() {
  isEdit.value = false
  Object.assign(form, { id: null, name: '', description: '', week_num: 1, status: 1 })
  dialogVisible.value = true
}

async function handleEdit(row) {
  isEdit.value = true
  try {
    const res = await mealTemplateApi.getDetail(row.id)
    const data = res.data?.data || res.data || row
    Object.assign(form, {
      id: data.id, name: data.name, description: data.description || '',
      week_num: data.week_num, status: data.status ?? 1
    })
  } catch {
    Object.assign(form, { id: row.id, name: row.name, description: row.description || '', week_num: row.week_num, status: row.status ?? 1 })
  }
  dialogVisible.value = true
}

async function handleDelete(row) {
  await ElMessageBox.confirm(`确定删除模板「${row.name}」吗？`, '删除确认', { type: 'warning' })
  try {
    await mealTemplateApi.delete(row.id)
    ElMessage.success('删除成功')
    fetchList()
  } catch {
    ElMessage.error('删除失败')
  }
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) {
        await mealTemplateApi.update(form.id, form)
      } else {
        await mealTemplateApi.create(form)
      }
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      fetchList()
    } catch {
      ElMessage.error('操作失败')
    } finally {
      submitLoading.value = false
    }
  })
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

onMounted(() => fetchList())
</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-input v-model="searchForm.name" placeholder="模板名称" clearable style="width:200px" />
      <el-button type="primary" @click="handleSearch">
        <Icon icon="solar:magnifer-bold-duotone" class="mr-1" />查询
      </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-2">
          <span class="w-1 h-5 bg-rose-500 rounded-full inline-block"></span>
          <span class="font-semibold text-gray-700">排餐模板管理</span>
        </div>
        <el-button type="primary" @click="handleAdd">
          <Icon icon="solar:add-circle-bold-duotone" class="mr-1" />新建模板
        </el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column prop="name" label="模板名称" min-width="160" />
          <el-table-column label="适用周数" width="100" align="center">
            <template #default="{ row }">第 {{ row.week_num }} 周</template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
          <el-table-column label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">{{ statusMap[row.status] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
          <el-table-column label="操作" width="140" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button 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, 20, 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="520px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="如：产后第1周营养餐模板" />
        </el-form-item>
        <el-form-item label="适用周数" prop="week_num">
          <el-select v-model="form.week_num" style="width:100%">
            <el-option v-for="w in weekOptions" :key="w.value" :label="w.label" :value="w.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="模板描述">
          <el-input v-model="form.description" 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>
