<template>
    <div class="dict-item-list">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-select
            v-model="selectedDictTypeId"
            placeholder="选择字典类型"
            clearable
            filterable
            style="width: 250px"
            @change="handleTypeChange"
          >
            <el-option
              v-for="type in dictTypes"
              :key="type.id"
              :label="`${type.dict_name} (${type.dict_code})`"
              :value="type.id"
            />
          </el-select>
          <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"
            :disabled="!selectedDictTypeId"
            @click="handleAdd"
          >
            <el-icon><Plus /></el-icon>
            添加字典项
          </el-button>
        </div>
      </div>
  
      <!-- 提示信息 -->
      <el-alert
        v-if="!selectedDictTypeId"
        title="请先选择字典类型"
        type="info"
        :closable="false"
        style="margin-bottom: 16px"
      />
  
      <!-- 错误状态 -->
      <div v-if="error" class="error-state">
        <el-alert title="加载失败" :message="error" type="error" show-icon />
        <el-button type="primary" @click="fetchDictItems">重试</el-button>
      </div>
  
      <!-- 字典项列表 -->
      <div v-else-if="selectedDictTypeId">
        <el-table
          :data="filteredDictItems"
          stripe
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="dict_label" label="字典标签" min-width="150" align="center" />
          <el-table-column prop="dict_value" label="字典值" min-width="150" align="center">
            <template #default="{ row }">
              <el-tag size="small">{{ row.dict_value }}</el-tag>
            </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="color" label="颜色" width="100" align="center">
            <template #default="{ row }">
              <div v-if="row.color" class="color-display">
                <span
                  class="color-dot"
                  :style="{ backgroundColor: row.color }"
                ></span>
                <span>{{ row.color }}</span>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="icon" label="图标" width="100" align="center">
            <template #default="{ row }">
              <span v-if="row.icon">{{ row.icon }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <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="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button size="small" type="danger" link @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
  
      <!-- 编辑对话框 -->
      <DictItemEditDialog
        v-model="editDialogVisible"
        :dict-item="currentDictItem"
        :dict-type-id="selectedDictTypeId"
        @success="handleEditSuccess"
      />
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onMounted, watch } from 'vue'
  import {
    ElMessage,
    ElMessageBox,
  } from 'element-plus'
  import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue'
  import {
    getDictTypes,
    getDictItems,
    deleteDictItem,
  } from '@/api/dict'
  import DictItemEditDialog from './DictItemEditDialog.vue'
  
  interface Props {
    selectedTypeId?: number | null
  }
  
  const props = withDefaults(defineProps<Props>(), {
    selectedTypeId: null,
  })
  
  const emit = defineEmits<{
    'refresh': []
  }>()
  
  const dictTypes = ref<any[]>([])
  const dictItems = ref<any[]>([])
  const loading = ref(false)
  const error = ref('')
  const searchKeyword = ref('')
  const statusFilter = ref<number | ''>('')
  const selectedDictTypeId = ref<number | null>(null)
  
  const editDialogVisible = ref(false)
  const currentDictItem = ref<any>(null)
  
  // 过滤后的字典项
  const filteredDictItems = computed(() => {
    let result = dictItems.value
  
    // 搜索过滤
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      result = result.filter(
        (item) =>
          (item.dict_label && item.dict_label.toLowerCase().includes(keyword)) ||
          (item.dict_value && item.dict_value.toLowerCase().includes(keyword)) ||
          (item.remark && item.remark.toLowerCase().includes(keyword))
      )
    }
  
    // 状态过滤
    if (statusFilter.value !== '') {
      result = result.filter((item) => item.status === statusFilter.value)
    }
  
    return result
  })
  
  // 监听外部传入的selectedTypeId
  watch(
    () => props.selectedTypeId,
    (newId) => {
      if (newId) {
        selectedDictTypeId.value = newId
        fetchDictItems()
      }
    },
    { immediate: true }
  )
  
  // 格式化日期
  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() {
    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 : []
      }
    } catch (err: any) {
      console.error('获取字典类型列表失败:', err)
    }
  }
  
  // 获取字典项列表
  async function fetchDictItems() {
    if (!selectedDictTypeId.value) {
      dictItems.value = []
      return
    }
  
    loading.value = true
    error.value = ''
    try {
      const res = await getDictItems({ dict_type_id: selectedDictTypeId.value })
      if (res.success === true && res.data) {
        dictItems.value = Array.isArray(res.data) ? res.data : []
      } else if (Array.isArray(res)) {
        dictItems.value = res
      } else if (res && res.data) {
        dictItems.value = Array.isArray(res.data) ? res.data : []
      } else {
        error.value = res.message || '获取字典项列表失败'
        dictItems.value = []
      }
    } catch (err: any) {
      error.value = err.message || '获取字典项列表失败'
      dictItems.value = []
    } finally {
      loading.value = false
    }
  }
  
  // 字典类型改变
  const handleTypeChange = () => {
    fetchDictItems()
  }
  
  // 搜索
  const handleSearch = () => {
    // 搜索逻辑在computed中处理
  }
  
  // 筛选
  const handleFilter = () => {
    // 筛选逻辑在computed中处理
  }
  
  // 设置字典类型ID（供外部调用）
  function setTypeId(typeId: number) {
    selectedDictTypeId.value = typeId
  }
  
  // 添加字典项
  function handleAdd() {
    if (!selectedDictTypeId.value) {
      ElMessage.warning('请先选择字典类型')
      return
    }
    currentDictItem.value = null
    editDialogVisible.value = true
  }
  
  // 编辑字典项
  function handleEdit(row: any) {
    currentDictItem.value = { ...row }
    editDialogVisible.value = true
  }
  
  // 删除字典项
  async function handleDelete(row: any) {
    try {
      await ElMessageBox.confirm(
        `确定要删除字典项「${row.dict_label}」吗？删除后不可恢复。`,
        '警告',
        { type: 'warning' }
      )
  
      loading.value = true
      try {
        const res = await deleteDictItem(row.id)
        if (res.success === true || res.code === 0) {
          ElMessage.success('删除成功')
          fetchDictItems()
          emit('refresh')
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (err: any) {
        ElMessage.error(err.message || '删除失败')
      } finally {
        loading.value = false
      }
    } catch {
      // 取消删除
    }
  }
  
  // 编辑成功回调
  function handleEditSuccess() {
    fetchDictItems()
    emit('refresh')
  }
  
  // 刷新
  function refresh() {
    fetchDictTypes()
    if (selectedDictTypeId.value) {
      fetchDictItems()
    }
  }
  
  defineExpose({
    refresh,
    setTypeId,
  })
  
  onMounted(() => {
    fetchDictTypes()
    if (selectedDictTypeId.value) {
      fetchDictItems()
    }
  })
  </script>
  
  <style scoped lang="less">
  .dict-item-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;
      }
    }
  
    .color-display {
      display: flex;
      align-items: center;
      gap: 6px;
      justify-content: center;
  
      .color-dot {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        border: 1px solid #ddd;
      }
    }
  }
  
  .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>
  
  