<template>
  <div class="material-category-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>物资类别管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加类别
          </el-button>
        </div>
      </template>
      
      <el-table :data="categories" v-loading="loading">
        <el-table-column prop="name" label="类别名称" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="sortOrder" label="排序" width="100" align="center" />
        <el-table-column prop="isActive" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'info'" size="small">
              {{ row.isActive ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" text size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- Create/Edit Dialog -->
    <el-dialog v-model="showDialog" :title="dialogTitle" width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="类别名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类别名称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入类别描述（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="状态" prop="isActive" v-if="editingCategory">
          <el-switch v-model="form.isActive" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { materialCategoriesApi } from '@/api'
import type { MaterialCategory } from '@/api/materialCategories'

const loading = ref(false)
const saving = ref(false)
const showDialog = ref(false)
const categories = ref<MaterialCategory[]>([])
const editingCategory = ref<MaterialCategory | null>(null)
const formRef = ref<FormInstance>()

const form = reactive({
  name: '',
  description: '',
  sortOrder: 0,
  isActive: true
})

const dialogTitle = computed(() => editingCategory.value ? '编辑类别' : '添加类别')

const rules: FormRules = {
  name: [{ required: true, message: '请输入类别名称', trigger: 'blur' }],
  sortOrder: [{ required: true, message: '请输入排序', trigger: 'blur' }]
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleString('zh-CN')
}

async function loadCategories() {
  loading.value = true
  try {
    categories.value = await materialCategoriesApi.getAll(false) // 加载所有类别，包括禁用的
  } catch {
    ElMessage.error('加载类别列表失败')
  } finally {
    loading.value = false
  }
}

function handleAdd() {
  editingCategory.value = null
  form.name = ''
  form.description = ''
  form.sortOrder = 0
  form.isActive = true
  showDialog.value = true
}

function handleEdit(category: MaterialCategory) {
  editingCategory.value = category
  form.name = category.name
  form.description = category.description || ''
  form.sortOrder = category.sortOrder
  form.isActive = category.isActive
  showDialog.value = true
}

async function handleDelete(category: MaterialCategory) {
  try {
    await ElMessageBox.confirm(`确定要删除类别"${category.name}"吗？`, '确认删除', {
      type: 'warning'
    })
    await materialCategoriesApi.delete(category.id)
    ElMessage.success('删除成功')
    await loadCategories()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

async function handleSave() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    saving.value = true
    try {
      if (editingCategory.value) {
        await materialCategoriesApi.update(editingCategory.value.id, {
          name: form.name,
          description: form.description || undefined,
          sortOrder: form.sortOrder,
          isActive: form.isActive
        })
        ElMessage.success('更新成功')
      } else {
        await materialCategoriesApi.create({
          name: form.name,
          description: form.description || undefined,
          sortOrder: form.sortOrder
        })
        ElMessage.success('创建成功')
      }
      showDialog.value = false
      await loadCategories()
    } catch (error: any) {
      ElMessage.error(error.response?.data?.message || '操作失败')
    } finally {
      saving.value = false
    }
  })
}

onMounted(() => {
  loadCategories()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
