<template>
  <div class="dictionaries-container">
    <div class="page-header">
      <h1>字典管理</h1>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增字典
      </el-button>
    </div>
    
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="字典名称">
          <el-input
            v-model="searchForm.dictname"
            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-select v-model="searchForm.dicttype" placeholder="请选择字典类型" clearable>
            <el-option label="系统字典" value="1" />
            <el-option label="业务字典" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="table-actions">
          <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
        <div class="table-info">
          共 {{ total }} 条记录
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="dictname" label="字典名称" min-width="150" />
        <el-table-column prop="dictcode" label="字典编码" width="150" />
        <el-table-column prop="dicttype" label="字典类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.dicttype === '1' ? 'primary' : 'success'">
              {{ row.dicttype === '1' ? '系统字典' : '业务字典' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderno" label="排序" width="80" />
        <el-table-column prop="dictdesc" label="字典描述" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="success" size="small" @click="handleViewData(row)">
              字典数据
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 字典表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑字典' : '新增字典'"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="字典名称" prop="dictname">
          <el-input v-model="form.dictname" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典编码" prop="dictcode">
          <el-input v-model="form.dictcode" placeholder="请输入字典编码" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dicttype">
          <el-select v-model="form.dicttype" placeholder="请选择字典类型">
            <el-option label="系统字典" value="1" />
            <el-option label="业务字典" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="orderno">
          <el-input-number v-model="form.orderno" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="字典描述" prop="dictdesc">
          <el-input
            v-model="form.dictdesc"
            type="textarea"
            :rows="3"
            placeholder="请输入字典描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 字典数据对话框 -->
    <el-dialog
      v-model="dataDialogVisible"
      :title="`字典数据 - ${currentDict?.dictname}`"
      width="800px"
      @close="handleDataDialogClose"
    >
      <div class="data-header">
        <el-button type="primary" size="small" @click="handleAddData">
          <el-icon><Plus /></el-icon>
          新增数据
        </el-button>
      </div>
      
      <el-table
        v-loading="dataLoading"
        :data="dictDataList"
        stripe
        border
        size="small"
      >
        <el-table-column prop="dataname" label="数据名称" width="150" />
        <el-table-column prop="datavalue" label="数据值" width="120" />
        <el-table-column prop="orderno" label="排序" width="80" />
        <el-table-column prop="datadesc" label="数据描述" min-width="150" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEditData(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteData(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    
    <!-- 字典数据表单对话框 -->
    <el-dialog
      v-model="dataFormDialogVisible"
      :title="isEditData ? '编辑字典数据' : '新增字典数据'"
      width="500px"
      @close="handleDataFormDialogClose"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataFormRules"
        label-width="80px"
      >
        <el-form-item label="数据名称" prop="dataname">
          <el-input v-model="dataForm.dataname" placeholder="请输入数据名称" />
        </el-form-item>
        <el-form-item label="数据值" prop="datavalue">
          <el-input v-model="dataForm.datavalue" placeholder="请输入数据值" />
        </el-form-item>
        <el-form-item label="排序" prop="orderno">
          <el-input-number v-model="dataForm.orderno" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="数据描述" prop="datadesc">
          <el-input
            v-model="dataForm.datadesc"
            type="textarea"
            :rows="2"
            placeholder="请输入数据描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dataFormDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="dataSubmitLoading" @click="handleDataSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Delete } from '@element-plus/icons-vue'
import {
  getDictionaryList,
  createDictionary,
  updateDictionary,
  deleteDictionary,
  batchDeleteDictionaries,
  getDictionaryData
} from '@/api/dictionary'

// 响应式数据
const loading = ref(false)
const dataLoading = ref(false)
const submitLoading = ref(false)
const dataSubmitLoading = ref(false)
const dialogVisible = ref(false)
const dataDialogVisible = ref(false)
const dataFormDialogVisible = ref(false)
const isEdit = ref(false)
const isEditData = ref(false)
const tableData = ref([])
const dictDataList = ref([])
const selectedIds = ref([])
const total = ref(0)
const formRef = ref()
const dataFormRef = ref()
const currentDict = ref(null)

// 分页
const pagination = reactive({
  page: 1,
  size: 10
})

// 搜索表单
const searchForm = reactive({
  dictname: '',
  dictcode: '',
  dicttype: ''
})

// 表单数据
const form = reactive({
  id: '',
  dictname: '',
  dictcode: '',
  dicttype: '2',
  orderno: 0,
  dictdesc: ''
})

// 字典数据表单
const dataForm = reactive({
  id: '',
  dictid: '',
  dataname: '',
  datavalue: '',
  orderno: 0,
  datadesc: ''
})

// 表单验证规则
const formRules = {
  dictname: [
    { required: true, message: '请输入字典名称', trigger: 'blur' },
    { min: 2, max: 50, message: '字典名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  dictcode: [
    { required: true, message: '请输入字典编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '字典编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  dicttype: [
    { required: true, message: '请选择字典类型', trigger: 'change' }
  ],
  orderno: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 字典数据表单验证规则
const dataFormRules = {
  dataname: [
    { required: true, message: '请输入数据名称', trigger: 'blur' },
    { min: 1, max: 50, message: '数据名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  datavalue: [
    { required: true, message: '请输入数据值', trigger: 'blur' }
  ],
  orderno: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 加载字典列表
const loadDictionaries = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    
    const response = await getDictionaryList(params)
    if (response.success) {
      tableData.value = response.data.records || []
      total.value = response.data.total || 0
    }
  } catch (error) {
    console.error('加载字典列表失败:', error)
    ElMessage.error('加载字典列表失败')
  } finally {
    loading.value = false
  }
}

// 加载字典数据
const loadDictionaryData = async (dictId) => {
  dataLoading.value = true
  try {
    const response = await getDictionaryData(dictId)
    if (response.success) {
      dictDataList.value = response.data || []
    }
  } catch (error) {
    console.error('加载字典数据失败:', error)
    ElMessage.error('加载字典数据失败')
  } finally {
    dataLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadDictionaries()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    dictname: '',
    dictcode: '',
    dicttype: ''
  })
  pagination.page = 1
  loadDictionaries()
}

// 新增字典
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 编辑字典
const handleEdit = (row) => {
  isEdit.value = true
  dialogVisible.value = true
  Object.assign(form, row)
}

// 删除字典
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除字典 "${row.dictname}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteDictionary(row.id)
    if (response.success) {
      ElMessage.success('删除成功')
      loadDictionaries()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除字典失败:', error)
      ElMessage.error('删除字典失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 个字典吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await batchDeleteDictionaries(selectedIds.value)
    if (response.success) {
      ElMessage.success('删除成功')
      selectedIds.value = []
      loadDictionaries()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 查看字典数据
const handleViewData = (row) => {
  currentDict.value = row
  dataDialogVisible.value = true
  loadDictionaryData(row.id)
}

// 新增字典数据
const handleAddData = () => {
  isEditData.value = false
  dataFormDialogVisible.value = true
  resetDataForm()
  dataForm.dictid = currentDict.value.id
}

// 编辑字典数据
const handleEditData = (row) => {
  isEditData.value = true
  dataFormDialogVisible.value = true
  Object.assign(dataForm, row)
}

// 删除字典数据
const handleDeleteData = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据 "${row.dataname}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用删除字典数据的API
    ElMessage.success('删除成功')
    loadDictionaryData(currentDict.value.id)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除字典数据失败:', error)
      ElMessage.error('删除字典数据失败')
    }
  }
}

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

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadDictionaries()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page
  loadDictionaries()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    submitLoading.value = true
    
    let response
    if (isEdit.value) {
      response = await updateDictionary(form.id, form)
    } else {
      response = await createDictionary(form)
    }
    
    if (response.success) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadDictionaries()
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 提交字典数据表单
const handleDataSubmit = async () => {
  if (!dataFormRef.value) return
  
  try {
    const valid = await dataFormRef.value.validate()
    if (!valid) return
    
    dataSubmitLoading.value = true
    
    // 这里应该调用创建/更新字典数据的API
    ElMessage.success(isEditData.value ? '更新成功' : '创建成功')
    dataFormDialogVisible.value = false
    loadDictionaryData(currentDict.value.id)
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    dataSubmitLoading.value = false
  }
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
}

const handleDataDialogClose = () => {
  currentDict.value = null
  dictDataList.value = []
}

const handleDataFormDialogClose = () => {
  resetDataForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: '',
    dictname: '',
    dictcode: '',
    dicttype: '2',
    orderno: 0,
    dictdesc: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 重置字典数据表单
const resetDataForm = () => {
  Object.assign(dataForm, {
    id: '',
    dictid: '',
    dataname: '',
    datavalue: '',
    orderno: 0,
    datadesc: ''
  })
  if (dataFormRef.value) {
    dataFormRef.value.clearValidate()
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadDictionaries()
})
</script>

<style lang="scss" scoped>
.dictionaries-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h1 {
    color: #333;
    font-size: 24px;
    font-weight: 600;
  }
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .table-actions {
      display: flex;
      gap: 8px;
    }
    
    .table-info {
      color: #666;
      font-size: 14px;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.data-header {
  margin-bottom: 16px;
}
</style>