<template>
  <div class="container">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="资产分类管理"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <template #toolbar-left>
        <a-button type="primary" @click="handleCreate">
          <template #icon>
            <icon-plus />
          </template>
          新建分类
        </a-button>
      </template>

      <!-- 序号 -->
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
      </template>

      <!-- 层级 -->
      <template #level="{ record }">
        <a-tag :color="getLevelColor(record.level)">第{{ record.level }}级</a-tag>
      </template>

      <!-- 父级分类 -->
      <template #parent="{ record }">
        {{ record.parent?.name || '-' }}
      </template>

      <!-- 资产数量 -->
      <template #asset_count="{ record }">
        <a-badge :count="record.asset_count" :max-count="999" />
      </template>

      <!-- 状态 -->
      <template #enabled="{ record }">
        <a-tag :color="record.enabled ? 'green' : 'red'">
          {{ record.enabled ? '启用' : '禁用' }}
        </a-tag>
      </template>

      <!-- 创建时间 -->
      <template #created_at="{ record }">
        {{ formatDateTime(record.created_at) }}
      </template>

      <!-- 操作 -->
      <template #actions="{ record }">
        <a-button type="text" size="small" @click="handleDetail(record)">详情</a-button>
        <a-button type="text" size="small" @click="handleEdit(record)">编辑</a-button>
        <a-button type="text" size="small" @click="handleAddChild(record)">添加子分类</a-button>
        <a-button type="text" size="small" status="danger" @click="handleDelete(record)">删除</a-button>
      </template>
    </search-table>

    <!-- 分类表单对话框 -->
    <category-form-dialog v-model:visible="formVisible" :category="editingCategory" @success="handleFormSuccess" />

    <!-- 分类详情对话框 -->
    <category-detail-dialog v-model:visible="detailVisible" :category-id="currentCategoryId" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import type { FormItem } from '@/components/search-form/types'
import SearchTable from '@/components/search-table/index.vue'
import { searchFormConfig } from './config/search-form'
import { columns as columnsConfig } from './config/columns'
import { fetchCategoryList, deleteCategory } from '@/api/ops/assetCategory'
import type { AssetCategory } from '@/api/ops/assetCategory'
import CategoryFormDialog from './components/CategoryFormDialog.vue'
import CategoryDetailDialog from './components/CategoryDetailDialog.vue'

// 状态管理
const loading = ref(false)
const tableData = ref<AssetCategory[]>([])
const formModel = ref({
  keyword: '',
})

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

// 表单项配置
const formItems = computed<FormItem[]>(() => searchFormConfig)

// 表格列配置
const columns = computed(() => columnsConfig)

// 当前选中的分类
const currentCategoryId = ref<number | undefined>(undefined)
const editingCategory = ref<AssetCategory | null>(null)

// 对话框可见性
const formVisible = ref(false)
const detailVisible = ref(false)

// 获取层级颜色
const getLevelColor = (level: number) => {
  const colors: Record<number, string> = {
    1: 'blue',
    2: 'green',
    3: 'orange',
    4: 'purple',
    5: 'cyan',
  }
  return colors[level] || 'gray'
}

// 格式化日期时间
const formatDateTime = (dateStr?: string) => {
  if (!dateStr) return '-'
  try {
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    })
  } catch {
    return dateStr
  }
}

// 获取分类列表
const fetchCategories = async () => {
  loading.value = true

  try {
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: formModel.value.keyword || undefined,
    }

    const res = await fetchCategoryList(params)

    tableData.value = res.details?.data || []
    pagination.total = res.details?.total || 0
  } catch (error) {
    console.error('获取分类列表失败:', error)
    Message.error('获取分类列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchCategories()
}

// 处理表单模型更新
const handleFormModelUpdate = (value: any) => {
  formModel.value = value
}

// 重置
const handleReset = () => {
  formModel.value = {
    keyword: '',
  }
  pagination.current = 1
  fetchCategories()
}

// 分页变化
const handlePageChange = (current: number) => {
  pagination.current = current
  fetchCategories()
}

// 刷新
const handleRefresh = () => {
  fetchCategories()
  Message.success('数据已刷新')
}

// 新建分类
const handleCreate = () => {
  editingCategory.value = null
  formVisible.value = true
}

// 编辑分类
const handleEdit = (record: AssetCategory) => {
  editingCategory.value = record
  formVisible.value = true
}

// 添加子分类
const handleAddChild = (record: AssetCategory) => {
  editingCategory.value = {
    parent_id: record.id,
  } as AssetCategory
  formVisible.value = true
}

// 详情
const handleDetail = (record: AssetCategory) => {
  currentCategoryId.value = record.id
  detailVisible.value = true
}

// 删除分类
const handleDelete = async (record: AssetCategory) => {
  try {
    Modal.confirm({
      title: '确认删除',
      content: `确认删除分类「${record.name}」吗？如果该分类下存在子分类或资产，将无法删除。`,
      onOk: async () => {
        const res = await deleteCategory(record.id)
        if (res.code === 0) {
          Message.success('删除成功')
          fetchCategories()
        } else {
          Message.error(res.message || '删除失败')
        }
      },
    })
  } catch (error) {
    console.error('删除分类失败:', error)
  }
}

// 表单成功回调
const handleFormSuccess = () => {
  fetchCategories()
}

// 初始化加载数据
onMounted(() => {
  fetchCategories()
})
</script>

<script lang="ts">
export default {
  name: 'AssetCategory',
}
</script>

<style scoped lang="less">
.container {
  margin-top: 20px;
}
</style>
