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

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

const searchForm = reactive({ type: '', status: '' })
const pagination = reactive({ page: 1, per_page: 50 })

const formRef = ref(null)
const form = reactive({ id: null, name: '', type: 1, parent_id: 0, level: 1, sort: 0, status: 1 })
const isEdit = ref(false)
const formRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }]
}
const typeMap = { 1: '收入', 2: '支出' }

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

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

function handleAdd() {
  isEdit.value = false
  Object.assign(form, { id: null, name: '', type: 1, parent_id: 0, level: 1, sort: 0, status: 1 })
  dialogVisible.value = true
}

async function handleEdit(row) {
  isEdit.value = true
  Object.assign(form, {
    id: row.id,
    name: row.name,
    type: row.type,
    parent_id: row.parent_id || 0,
    level: row.level || 1,
    sort: row.sort || 0,
    status: row.status
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) { await financeCategoryApi.update(form.id, form); ElMessage.success('更新成功') }
      else { await financeCategoryApi.create(form); ElMessage.success('创建成功') }
      dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleDelete(row) {
  await ElMessageBox.confirm(`确定删除分类「${row.name}」吗？`, '删除确认', { type: 'warning' })
  await financeCategoryApi.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())
</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.type" placeholder="类型" clearable style="width:120px">
        <el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width:120px">
        <el-option label="启用" :value="1" />
        <el-option label="停用" :value="0" />
      </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">
          <span class="font-medium text-gray-700">收支分类列表</span>
        </div>
        <el-button type="primary" @click="handleAdd">新增分类</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" row-key="id" default-expand-all style="width:100%">
          <el-table-column prop="name" label="分类名称" min-width="180" />
          <el-table-column label="类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.type === 1 ? 'success' : 'danger'" size="small">{{ typeMap[row.type] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="level" label="层级" width="80" align="center" />
          <el-table-column prop="sort" label="排序" width="80" align="center" />
          <el-table-column label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status ? 'success' : 'danger'" size="small">{{ row.status ? '启用' : '停用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
          <el-table-column label="操作" width="160" 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="[20,50,100]" layout="total,sizes,prev,pager,next,jumper" background @current-change="handlePageChange" @size-change="handleSizeChange" />
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑分类' : '新增分类'" width="450px" 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="请输入分类名称" /></el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" style="width:100%">
            <el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" />
          </el-select>
        </el-form-item>
        <el-form-item label="上级分类">
          <el-input-number v-model="form.parent_id" :min="0" style="width:100%" />
          <div style="font-size:12px;color:var(--color-text-secondary)">0 表示顶级分类</div>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="0" :max="9999" style="width:100%" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </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>
