<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">
          新增分类
        </a-button>
      </template>

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

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

      <!-- 颜色标识 -->
      <template #color="{ record }">
        <div class="color-cell">
          <div
            class="color-block"
            :style="{ backgroundColor: record.color || '#ccc' }"
          ></div>
          <span>{{ record.color || '-' }}</span>
        </div>
      </template>

      <!-- 是否启用 -->
      <template #enabled="{ record }">
        <a-tag :color="record.enabled ? 'green' : 'red'">
          {{ record.enabled ? '是' : '否' }}
        </a-tag>
      </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" status="danger" @click="handleDelete(record)">
          删除
        </a-button>
        <a-button type="text" size="small" status="success" @click="handleAddChild(record)">
          新增
        </a-button>
      </template>
    </search-table>

    <!-- 分类表单对话框（新增/编辑） -->
    <category-form-dialog
      v-model:visible="formVisible"
      :category="editingCategory"
      :parent-categories="parentCategories"
      :fixed-parent-id="fixedParentId"
      :show-parent-selector="showParentSelector"
      @success="handleFormSuccess"
    />

    <!-- 分类详情对话框 -->
    <category-detail-dialog
      v-model:visible="detailVisible"
      :category="currentCategory"
    />
  </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 {
  fetchCategoryList,
  deleteCategory,
  fetchAllCategories,
  fetchCategoryDetail,
} from '@/api/ops/assetCategory'
import CategoryFormDialog from './components/CategoryFormDialog.vue'
import CategoryDetailDialog from './components/CategoryDetailDialog.vue'

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

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

// 父级分类列表（用于下拉选择）
const parentCategories = ref<any[]>([])

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    field: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '请输入分类名称或编码',
  },
  {
    field: 'parent_id',
    label: '父级分类',
    type: 'select',
    placeholder: '请选择父级分类',
    options: parentCategories.value.map((item) => ({
      label: item.name,
      value: item.id,
    })),
    allowClear: true,
    allowSearch: true,
  },
])

// 表格列配置
const columns = computed(() => [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    width: 80,
    align: 'center' as const,
  },
  {
    title: '分类名称',
    dataIndex: 'name',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '分类编码',
    dataIndex: 'code',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '父级分类',
    dataIndex: 'parent',
    slotName: 'parent',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '层级',
    dataIndex: 'level',
    width: 80,
    align: 'center' as const,
  },
  {
    title: '排序',
    dataIndex: 'sort',
    width: 80,
    align: 'center' as const,
  },
  {
    title: '颜色标识',
    dataIndex: 'color',
    slotName: 'color',
    width: 120,
    align: 'center' as const,
  },
  {
    title: '是否启用',
    dataIndex: 'enabled',
    slotName: 'enabled',
    width: 100,
    align: 'center' as const,
  },
  {
    title: '操作',
    slotName: 'actions',
    width: 300,
    fixed: 'right' as const,
  },
])

// 当前选中的分类
const currentCategory = ref<any>(null)
const editingCategory = ref<any>(null)

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

// 固定的父级分类ID（用于新增子分类时）
const fixedParentId = ref<number | undefined>(undefined)

// 是否显示父级分类选择器
const showParentSelector = ref(true)

// 获取父级分类列表（用于下拉选择）
const fetchParentCategories = async () => {
  try {
    const res = await fetchAllCategories()
    parentCategories.value = res.details || []
  } catch (error) {
    console.error('获取父级分类列表失败:', error)
  }
}

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

  try {
    const params: any = {
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: formModel.value.keyword || undefined,
      parent_id: formModel.value.parent_id || 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: '',
    parent_id: '',
  }
  pagination.current = 1
  fetchCategories()
}

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

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

// 新增分类
const handleCreate = () => {
  editingCategory.value = null
  fixedParentId.value = undefined
  showParentSelector.value = false
  formVisible.value = true
}

// 新增子分类
const handleAddChild = (record: any) => {
  editingCategory.value = null
  fixedParentId.value = record.id
  showParentSelector.value = true
  formVisible.value = true
}

// 编辑分类
const handleEdit = (record: any) => {
  console.log('编辑分类:', record)
  editingCategory.value = record
  formVisible.value = true
}

// 详情
const handleDetail = async (record: any) => {
  console.log('查看详情:', record)
  try {
    const res = await fetchCategoryDetail(record.id)
    if (res.code === 0) {
      currentCategory.value = res.details
      detailVisible.value = true
    } else {
      Message.error(res.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取分类详情失败:', error)
    Message.error('获取详情失败')
  }
}

// 删除分类
const handleDelete = async (record: any) => {
  console.log('删除分类:', record)
  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 = () => {
  formVisible.value = false
  fetchCategories()
  fetchParentCategories()
}

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

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

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

.color-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;

  .color-block {
    width: 20px;
    height: 20px;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
  }
}
</style>
