<template>
  <div class="page-wrapper">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <template #header>
        <div class="card-header-title">
          <el-icon><Search /></el-icon>
          <span>搜索条件</span>
        </div>
      </template>
      <el-form :model="query" inline>
        <el-form-item label="字典类型">
          <el-select v-model="query.dictType" placeholder="全部" clearable style="width: 200px" @change="handleSearch">
            <el-option
              v-for="t in dictTypeList"
              :key="t.dictType"
              :label="t.dictType"
              :value="t.dictType"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="query.dictLabel" placeholder="请输入标签" clearable @clear="handleSearch" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增字典
      </el-button>
      <el-button @click="handleAddType">
        <el-icon><FolderAdd /></el-icon>
        新增字典类型
      </el-button>
    </div>

    <!-- 表格 -->
    <el-card shadow="never">
      <el-table :data="tableData" border stripe v-loading="loading" style="width: 100%">
        <el-table-column prop="dictType" label="字典类型" width="160" />
        <el-table-column prop="dictLabel" label="标签" width="150" />
        <el-table-column prop="dictValue" label="值" width="150" />
        <el-table-column prop="sortOrder" label="排序" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="dark" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" class-name="ops-col">
          <template #default="{ row }">
            <div class="actions">
              <el-button type="primary" size="small" plain @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" size="small" plain @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据，请选择字典类型或新增" :image-size="100" />
        </template>
      </el-table>
    </el-card>

    <!-- 新增字典类型弹窗 -->
    <el-dialog
      v-model="typeDialogVisible"
      title="新增字典类型"
      width="450px"
      :close-on-click-modal="false"
    >
      <el-form ref="typeFormRef" :model="typeForm" :rules="typeRules" label-width="100px">
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="typeForm.dictType" placeholder="请输入字典类型编码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="typeDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="typeSubmitLoading" @click="submitAddType">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, FolderAdd } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import request from '@/utils/request'

/** 字典项类型 */
interface DictItem {
  id?: string
  dictType: string
  dictLabel: string
  dictValue: string
  sortOrder: number
  status: number
}

interface DictTypeItem {
  dictType: string
}

// --- 查询 ---
const query = reactive({
  dictType: '',
  dictLabel: '',
})

const tableData = ref<DictItem[]>([])
const dictTypeList = ref<DictTypeItem[]>([])
const loading = ref(false)

/** 获取字典类型列表 */
async function fetchDictTypeList() {
  try {
    const res = await request.get('/zgapi/v1/admin/dict/type/list')
    dictTypeList.value = res.data ?? []
  } catch {
    dictTypeList.value = []
  }
}

/** 根据字典类型获取数据 */
async function fetchData() {
  if (!query.dictType) {
    tableData.value = []
    return
  }
  loading.value = true
  try {
    const res = await request.get(`/zgapi/v1/admin/dict/type/${query.dictType}`)
    let dataList = res.data ?? []
    // 如果有 dictLabel 筛选，前端过滤
    if (query.dictLabel) {
      dataList = dataList.filter((item: DictItem) =>
        item.dictLabel.includes(query.dictLabel)
      )
    }
    tableData.value = dataList
  } catch {
    tableData.value = []
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  fetchData()
}

function handleReset() {
  query.dictType = ''
  query.dictLabel = ''
  tableData.value = []
}

// --- 新增/编辑（路由跳转到独立表单页）---
const router = useRouter()

function handleAdd() {
  let url = '/admin/dict/form'
  if (query.dictType) {
    url += '?dictType=' + query.dictType
  }
  router.push(url)
}

function handleEdit(row: DictItem) {
  router.push('/admin/dict/form/' + row.id)
}

// --- 删除 ---
function handleDelete(row: DictItem) {
  ElMessageBox.confirm(`确认删除字典"${row.dictLabel}"吗？`, '删除确认', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    try {
      await request.delete(`/zgapi/v1/admin/dict/${row.id}`)
      ElMessage.success('删除成功')
      fetchDictTypeList()
      fetchData()
    } catch {
      // ignore
    }
  }).catch(() => {})
}

// --- 新增字典类型 ---
const typeDialogVisible = ref(false)
const typeSubmitLoading = ref(false)
const typeFormRef = ref<FormInstance>()

const typeForm = reactive({
  dictType: '',
})

const typeRules: FormRules = {
  dictType: [{ required: true, message: '请输入字典类型编码', trigger: 'blur' }],
}

function handleAddType() {
  typeForm.dictType = ''
  setTimeout(() => typeFormRef.value?.clearValidate(), 0)
  typeDialogVisible.value = true
}

async function submitAddType() {
  const valid = await typeFormRef.value?.validate().catch(() => false)
  if (!valid) return

  typeSubmitLoading.value = true
  try {
    await request.post('/zgapi/v1/admin/dict', {
      dictType: typeForm.dictType,
      dictLabel: '',
      dictValue: '',
      sortOrder: 0,
      status: 1,
    })
    ElMessage.success('新增字典类型成功')
    typeDialogVisible.value = false
    fetchDictTypeList()
  } catch {
    // ignore
  } finally {
    typeSubmitLoading.value = false
  }
}

// 初始化
fetchDictTypeList()
</script>

<style scoped>
.page-wrapper {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.card-header-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
  color: #303133;
}

.toolbar {
  display: flex;
  justify-content: flex-start;
  gap: 8px;
}

.actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
}

@media (max-width: 768px) {
  .page-wrapper { gap: 10px; }
  .page-toolbar { flex-direction: column; gap: 10px; }
  .page-toolbar .el-select,
  .page-toolbar .el-input { width: 100% !important; }
}
</style>
