<template>
    <div class="dict-type-list">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索字典类型名称或编码"
            clearable
            style="width: 300px"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select
            v-model="statusFilter"
            placeholder="状态筛选"
            clearable
            style="width: 120px"
            @change="handleFilter"
          >
            <el-option label="全部" value="" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </div>
        <div class="toolbar-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加字典类型
          </el-button>
        </div>
      </div>
  
      <!-- 错误状态 -->
      <div v-if="error" class="error-state">
        <el-alert title="加载失败" :message="error" type="error" show-icon />
        <el-button type="primary" @click="fetchDictTypes">重试</el-button>
      </div>
  
      <!-- 字典类型列表 -->
      <div v-else>
        <el-table
          :data="filteredDictTypes"
          stripe
          style="width: 100%"
          v-loading="loading"
          @row-click="handleRowClick"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="dict_name" label="字典名称" min-width="150" align="center" />
          <el-table-column prop="dict_code" label="字典编码" min-width="150" align="center">
            <template #default="{ row }">
              <el-tag size="small">{{ row.dict_code }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="tid" label="租户ID" width="100" align="center">
            <template #default="{ row }">
              <span>{{ row.tid || 0 }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="parent_id" label="父级ID" width="100" align="center">
            <template #default="{ row }">
              <span>{{ row.parent_id || '-' }}</span>
            </template>
          </el-table-column> -->
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" width="80" align="center" />
          <el-table-column prop="remark" label="备注" min-width="200" align="center" show-overflow-tooltip />
          <el-table-column label="创建时间" width="180" align="center">
            <template #default="{ row }">
              {{ formatDate(row.create_time) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click.stop="handleViewItems(row)">
                <el-icon><Menu /></el-icon>
                查看字典项
              </el-button>
              <el-button size="small" type="primary" link @click.stop="handleEdit(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button size="small" type="danger" link @click.stop="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
  
      <!-- 编辑对话框 -->
      <DictTypeEdit
        v-model="editDialogVisible"
        :dict-type="currentDictType"
        @success="handleEditSuccess"
      />
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onMounted } from 'vue'
  import {
    ElMessage,
    ElMessageBox,
  } from 'element-plus'
  import { Plus, Search, Edit, Delete, Menu } from '@element-plus/icons-vue'
  import {
    getDictTypes,
    deleteDictType,
  } from '@/api/dict'
  import DictTypeEdit from './DictTypeEdit.vue'
  
  const emit = defineEmits<{
    'select-type': [typeId: number]
    'refresh': []
  }>()
  
  const dictTypes = ref<any[]>([])
  const loading = ref(false)
  const error = ref('')
  const searchKeyword = ref('')
  const statusFilter = ref<number | ''>('')
  
  const editDialogVisible = ref(false)
  const currentDictType = ref<any>(null)
  
  // 过滤后的字典类型
  const filteredDictTypes = computed(() => {
    let result = dictTypes.value
  
    // 搜索过滤
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      result = result.filter(
        (type) =>
          (type.dict_name && type.dict_name.toLowerCase().includes(keyword)) ||
          (type.dict_code && type.dict_code.toLowerCase().includes(keyword))
      )
    }
  
    // 状态过滤
    if (statusFilter.value !== '') {
      result = result.filter((type) => type.status === statusFilter.value)
    }
  
    return result
  })
  
  // 格式化日期
  function formatDate(dateStr: string | null | undefined): 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 as string
    }
  }
  
  // 获取字典类型列表
  async function fetchDictTypes() {
    loading.value = true
    error.value = ''
    try {
      const res = await getDictTypes()
      if (res.success === true && res.data) {
        dictTypes.value = Array.isArray(res.data) ? res.data : []
      } else if (Array.isArray(res)) {
        dictTypes.value = res
      } else if (res && res.data) {
        dictTypes.value = Array.isArray(res.data) ? res.data : []
      } else {
        error.value = res.message || '获取字典类型列表失败'
        dictTypes.value = []
      }
    } catch (err: any) {
      error.value = err.message || '获取字典类型列表失败'
      dictTypes.value = []
    } finally {
      loading.value = false
    }
  }
  
  // 搜索
  const handleSearch = () => {
    // 搜索逻辑在computed中处理
  }
  
  // 筛选
  const handleFilter = () => {
    // 筛选逻辑在computed中处理
  }
  
  // 添加字典类型
  function handleAdd() {
    currentDictType.value = null
    editDialogVisible.value = true
  }
  
  // 编辑字典类型
  function handleEdit(row: any) {
    currentDictType.value = { ...row }
    editDialogVisible.value = true
  }
  
  // 查看字典项
  function handleViewItems(row: any) {
    emit('select-type', row.id)
  }
  
  // 行点击
  function handleRowClick(row: any) {
    // 可以在这里处理行点击事件
  }
  
  // 删除字典类型
  async function handleDelete(row: any) {
    try {
      await ElMessageBox.confirm(
        `确定要删除字典类型「${row.dict_name}」吗？删除后不可恢复。`,
        '警告',
        { type: 'warning' }
      )
  
      loading.value = true
      try {
        const res = await deleteDictType(row.id)
        if (res.success === true || res.code === 0) {
          ElMessage.success('删除成功')
          fetchDictTypes()
          emit('refresh')
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (err: any) {
        ElMessage.error(err.message || '删除失败')
      } finally {
        loading.value = false
      }
    } catch {
      // 取消删除
    }
  }
  
  // 编辑成功回调
  function handleEditSuccess() {
    fetchDictTypes()
    emit('refresh')
  }
  
  // 刷新
  function refresh() {
    fetchDictTypes()
  }
  
  defineExpose({
    refresh,
  })
  
  onMounted(() => {
    fetchDictTypes()
  })
  </script>
  
  <style scoped lang="less">
  .dict-type-list {
    .toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      gap: 12px;
  
      .toolbar-left {
        display: flex;
        gap: 12px;
        align-items: center;
      }
  
      .toolbar-right {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .error-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 220px;
    padding: 32px 0 16px 0;
    background: var(--el-bg-color-page);
    border-radius: 5px;
    gap: 16px;
  }
  </style>
  
  