<template>
  <div class="dictionary-list">
    <h2 class="page-title">字典管理</h2>
    
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="字典类型">
          <el-input v-model="searchForm.dictType" placeholder="请输入字典类型" clearable />
        </el-form-item>
        <el-form-item label="字典编码">
          <el-input v-model="searchForm.dictCode" placeholder="请输入字典编码" clearable />
        </el-form-item>
        <el-form-item label="字典名称">
          <el-input v-model="searchForm.dictName" placeholder="请输入字典名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="handleCreate">新增字典</el-button>
    </el-card>
    
    <el-card class="table-card">
      <template #header>
        <span>字典列表</span>
      </template>
      
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="dictType" label="字典类型" />
        <el-table-column prop="dictCode" label="字典编码" />
        <el-table-column prop="dictName" label="字典名称" />
        <el-table-column prop="dictValue" label="字典值" />
        <el-table-column prop="sortOrder" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="updateTime" label="更新时间" width="160" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button 
              :type="row.status === 1 ? 'warning' : 'success'" 
              link 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchData"
        @current-change="fetchData"
        class="pagination"
      />
    </el-card>
    
    <!-- 字典详情对话框 -->
    <el-dialog v-model="detailVisible" title="字典详情" width="600px">
      <el-descriptions :column="2" border v-if="currentDictionary">
        <el-descriptions-item label="字典类型">{{ currentDictionary.dictType }}</el-descriptions-item>
        <el-descriptions-item label="字典编码">{{ currentDictionary.dictCode }}</el-descriptions-item>
        <el-descriptions-item label="字典名称">{{ currentDictionary.dictName }}</el-descriptions-item>
        <el-descriptions-item label="字典值">{{ currentDictionary.dictValue || '-' }}</el-descriptions-item>
        <el-descriptions-item label="排序">{{ currentDictionary.sortOrder }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentDictionary.status === 1 ? 'success' : 'danger'">
            {{ currentDictionary.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentDictionary.remarks || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ currentDictionary.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">{{ currentDictionary.updateTime }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getDictionaryPage, deleteDictionary, updateDictionary } from '@/api/dictionary'
import type { Dictionary, DictionaryPageRequest } from '@/types/dictionary'

/**
 * 字典列表页
 * - 负责查询/展示/跳转新增与编辑
 * - 注意：项目使用 history 路由模式，禁止使用 window.location.hash 跳转
 */
const router = useRouter()

const loading = ref(false)
const detailVisible = ref(false)
const currentDictionary = ref<Dictionary | null>(null)

const searchForm = reactive<DictionaryPageRequest>({
  current: 1,
  size: 10
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const tableData = ref<Dictionary[]>([])

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      current: pagination.current,
      size: pagination.size
    }
    const res = await getDictionaryPage(params)
    const pageData = res.data as any
    tableData.value = pageData.records
    pagination.total = pageData.total
  } catch (error) {
    console.error('获取字典列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    current: 1,
    size: 10,
    dictType: '',
    dictCode: '',
    dictName: '',
    status: undefined
  })
  fetchData()
}

const handleCreate = () => {
  /**
   * 跳转到创建页面（history 模式）
   */
  router.push('/dictionary/create')
}

const handleEdit = (row: Dictionary) => {
  /**
   * 跳转到编辑页面（history 模式）
   */
  router.push(`/dictionary/edit/${row.id}`)
}

const handleView = (row: Dictionary) => {
  currentDictionary.value = row
  detailVisible.value = true
}

const handleDelete = (row: Dictionary) => {
  ElMessageBox.confirm('确定要删除该字典吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDictionary(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

const handleToggleStatus = (row: Dictionary) => {
  const action = row.status === 1 ? '禁用' : '启用'
  ElMessageBox.confirm(`确定要${action}该字典吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateDictionary({
        id: row.id,
        dictType: row.dictType,
        dictCode: row.dictCode,
        dictName: row.dictName,
        dictValue: row.dictValue,
        sortOrder: row.sortOrder,
        status: row.status === 1 ? 0 : 1,
        remarks: row.remarks
      })
      ElMessage.success(`${action}成功`)
      fetchData()
    } catch (error) {
      console.error(`${action}失败:`, error)
    }
  })
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.dictionary-list {
  .page-title {
    margin-bottom: 20px;
    font-size: 24px;
    color: var(--ls-text);
  }
  
  .search-card {
    margin-bottom: 20px;
    
    .el-form {
      margin-bottom: 20px;
    }
  }
  
  .table-card {
    .pagination {
      margin-top: 20px;
      justify-content: flex-end;
    }
  }
}
</style>