<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
      <el-form-item label="字典名称" prop="dictName">
        <el-input v-model="queryParams.dictName" placeholder="请输入字典名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="字典类型" prop="dictType">
        <el-input v-model="queryParams.dictType" placeholder="请输入字典类型" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="字典状态" clearable>
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" plain @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain :disabled="!selectedIds.length" @click="handleDelete">删除</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="dictList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="字典编号" prop="dict_id" width="100" />
      <el-table-column label="字典名称" prop="dict_name" width="200" show-overflow-tooltip />
      <el-table-column label="字典类型" prop="dict_type" width="200">
        <template #default="{ row }">
          <el-link type="primary" @click="handleViewData(row)">{{ row.dict_type }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === '0' ? 'success' : 'danger'">
            {{ row.status === '0' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" show-overflow-tooltip />
      <el-table-column label="创建时间" prop="create_time" width="160" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="primary" @click="handleViewData(row)">字典数据</el-button>
          <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="getList"
      @current-change="getList"
      style="margin-top: 15px; justify-content: flex-end"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="form.dictType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="0">正常</el-radio>
            <el-radio value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 字典数据对话框 -->
    <el-dialog :title="`字典数据 - ${currentDictType}`" v-model="dataDialogVisible" width="800px" append-to-body>
      <!-- 操作栏 -->
      <el-row :gutter="10" class="mb10">
        <el-col :span="1.5">
          <el-button type="primary" plain size="small" @click="handleAddData">新增</el-button>
        </el-col>
      </el-row>
      
      <!-- 字典数据表格 -->
      <el-table v-loading="dataLoading" :data="dictDataList" max-height="400">
        <el-table-column label="字典编码" prop="dict_code" width="100" />
        <el-table-column label="字典标签" prop="dict_label" width="150" />
        <el-table-column label="字典键值" prop="dict_value" width="100" />
        <el-table-column label="字典排序" prop="dict_sort" width="100" />
        <el-table-column label="状态" prop="status" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === '0' ? 'success' : 'danger'" size="small">
              {{ row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" show-overflow-tooltip />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleEditData(row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDeleteData(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 字典数据编辑对话框 -->
    <el-dialog :title="dataDialogTitle" v-model="dataFormVisible" width="500px" append-to-body>
      <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="80px">
        <el-form-item label="字典标签" prop="dictLabel">
          <el-input v-model="dataForm.dictLabel" placeholder="请输入字典标签" />
        </el-form-item>
        <el-form-item label="字典键值" prop="dictValue">
          <el-input v-model="dataForm.dictValue" placeholder="请输入字典键值" />
        </el-form-item>
        <el-form-item label="显示排序" prop="dictSort">
          <el-input-number v-model="dataForm.dictSort" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dataForm.status">
            <el-radio value="0">正常</el-radio>
            <el-radio value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dataForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dataFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDataForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/**
 * 字典管理页面
 * @author 湖北新华业务中台研发团队
 */
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

// 字典类型查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  dictName: '',
  dictType: '',
  status: ''
})

// 字典类型列表
const loading = ref(false)
const dictList = ref([])
const total = ref(0)
const selectedIds = ref([])

// 字典类型对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = ref({})

const rules = {
  dictName: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
  dictType: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }]
}

// 字典数据
const dataDialogVisible = ref(false)
const dataLoading = ref(false)
const currentDictType = ref('')
const dictDataList = ref([])

// 字典数据编辑
const dataFormVisible = ref(false)
const dataDialogTitle = ref('')
const dataFormRef = ref()
const dataForm = ref({})

const dataRules = {
  dictLabel: [{ required: true, message: '字典标签不能为空', trigger: 'blur' }],
  dictValue: [{ required: true, message: '字典键值不能为空', trigger: 'blur' }]
}

// 获取字典类型列表
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/api/system/dict/type/list', { params: queryParams })
    dictList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取字典类型列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.dictName = ''
  queryParams.dictType = ''
  queryParams.status = ''
  handleQuery()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.dict_id)
}

// 新增字典类型
const handleAdd = () => {
  form.value = { status: '0' }
  dialogTitle.value = '新增字典类型'
  dialogVisible.value = true
}

// 编辑字典类型
const handleEdit = async (row) => {
  try {
    const res = await request.get(`/api/system/dict/type/${row.dict_id}`)
    const data = res.data
    form.value = {
      dictId: data.dict_id,
      dictName: data.dict_name,
      dictType: data.dict_type,
      status: data.status,
      remark: data.remark
    }
    dialogTitle.value = '编辑字典类型'
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取字典类型信息失败')
  }
}

// 提交字典类型表单
const submitForm = async () => {
  await formRef.value?.validate()
  try {
    if (form.value.dictId) {
      await request.put('/api/system/dict/type', form.value)
      ElMessage.success('修改成功')
    } else {
      await request.post('/api/system/dict/type', form.value)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 删除字典类型
const handleDelete = async (row) => {
  const ids = row?.dict_id ? [row.dict_id] : selectedIds.value
  if (!ids.length) return
  
  await ElMessageBox.confirm('确认删除选中的字典类型?', '提示', { type: 'warning' })
  try {
    await request.delete(`/api/system/dict/type/${ids.join(',')}`)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    ElMessage.error(error.message || '删除失败')
  }
}

// 查看字典数据
const handleViewData = async (row) => {
  currentDictType.value = row.dict_type
  dataDialogVisible.value = true
  await getDictDataList()
}

// 获取字典数据列表
const getDictDataList = async () => {
  dataLoading.value = true
  try {
    const res = await request.get('/api/system/dict/data/list', { 
      params: { dictType: currentDictType.value } 
    })
    dictDataList.value = res.rows || []
  } catch (error) {
    console.error('获取字典数据失败:', error)
  } finally {
    dataLoading.value = false
  }
}

// 新增字典数据
const handleAddData = () => {
  dataForm.value = { dictType: currentDictType.value, status: '0', dictSort: 0 }
  dataDialogTitle.value = '新增字典数据'
  dataFormVisible.value = true
}

// 编辑字典数据
const handleEditData = async (row) => {
  try {
    const res = await request.get(`/api/system/dict/data/${row.dict_code}`)
    const data = res.data
    dataForm.value = {
      dictCode: data.dict_code,
      dictType: data.dict_type,
      dictLabel: data.dict_label,
      dictValue: data.dict_value,
      dictSort: data.dict_sort,
      status: data.status,
      remark: data.remark
    }
    dataDialogTitle.value = '编辑字典数据'
    dataFormVisible.value = true
  } catch (error) {
    ElMessage.error('获取字典数据信息失败')
  }
}

// 提交字典数据表单
const submitDataForm = async () => {
  await dataFormRef.value?.validate()
  try {
    if (dataForm.value.dictCode) {
      await request.put('/api/system/dict/data', dataForm.value)
      ElMessage.success('修改成功')
    } else {
      await request.post('/api/system/dict/data', dataForm.value)
      ElMessage.success('新增成功')
    }
    dataFormVisible.value = false
    getDictDataList()
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 删除字典数据
const handleDeleteData = async (row) => {
  await ElMessageBox.confirm('确认删除该字典数据?', '提示', { type: 'warning' })
  try {
    await request.delete(`/api/system/dict/data/${row.dict_code}`)
    ElMessage.success('删除成功')
    getDictDataList()
  } catch (error) {
    ElMessage.error(error.message || '删除失败')
  }
}

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

<style scoped>
.search-form {
  margin-bottom: 15px;
}
.mb10 {
  margin-bottom: 10px;
}
</style>
