<template>
  <div class="system-config">
    <el-card>
      <!-- 分类Tab -->
      <el-tabs v-model="activeCategory" @tab-change="handleCategoryChange">
        <el-tab-pane
          v-for="category in configCategories"
          :key="category.value"
          :label="category.label"
          :name="category.value"
        />

        <!-- 配置列表 -->
        <div class="config-actions">
          <el-button type="primary" :icon="Plus" @click="handleCreate">
            新增配置
          </el-button>
          <el-button :icon="Refresh" @click="handleRefreshCache">
            刷新缓存
          </el-button>
        </div>

        <el-table
          :data="filteredConfigs"
          v-loading="loading"
          border
          stripe
          class="config-table"
        >
          <el-table-column prop="configKey" label="配置键" width="200" />
          <el-table-column prop="configValue" label="配置值" min-width="200" />
          <el-table-column prop="description" label="说明" min-width="200" />
          <el-table-column prop="category" label="分类" width="120">
            <template #default="{ row }">
              <el-tag size="small">{{ getCategoryName(row.category) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="updatedAt" label="更新时间" width="180" />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-popconfirm
                title="确定删除该配置吗？"
                @confirm="handleDelete(row.id)"
              >
                <template #reference>
                  <el-button link type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-tabs>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="配置分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择配置分类">
            <el-option
              v-for="cat in configCategories"
              :key="cat.value"
              :label="cat.label"
              :value="cat.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="配置键" prop="configKey">
          <el-input
            v-model="formData.configKey"
            placeholder="请输入配置键"
            :disabled="isEdit"
          />
        </el-form-item>

        <el-form-item label="配置值" prop="configValue">
          <el-input
            v-model="formData.configValue"
            type="textarea"
            :rows="4"
            placeholder="请输入配置值"
          />
        </el-form-item>

        <el-form-item label="说明" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入配置说明"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus, Refresh } from '@element-plus/icons-vue'
import { getConfigList, createConfig, updateConfig, deleteConfig, refreshConfigCache } from '@/api'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 配置分类
const configCategories = [
  { label: '全部', value: '' },
  { label: '系统设置', value: 'system' },
  { label: '资产配置', value: 'asset' },
  { label: '通知设置', value: 'notification' },
  { label: '安全设置', value: 'security' },
  { label: '业务规则', value: 'business' }
]

const activeCategory = ref('')
const loading = ref(false)
const configs = ref<any[]>([])
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()
const isEdit = ref(false)
const editingId = ref<number | null>(null)

const formData = reactive({
  category: '',
  configKey: '',
  configValue: '',
  description: ''
})

const formRules: FormRules = {
  category: [{ required: true, message: '请选择配置分类', trigger: 'change' }],
  configKey: [{ required: true, message: '请输入配置键', trigger: 'blur' }],
  configValue: [{ required: true, message: '请输入配置值', trigger: 'blur' }],
  description: [{ required: true, message: '请输入配置说明', trigger: 'blur' }]
}

const dialogTitle = computed(() => isEdit.value ? '编辑配置' : '新增配置')

const filteredConfigs = computed(() => {
  if (!activeCategory.value) return configs.value
  return configs.value.filter(config => config.category === activeCategory.value)
})

// 获取配置列表
const fetchConfigs = async () => {
  loading.value = true
  try {
    const data = await getConfigList()
    configs.value = data
  } catch (error) {
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 分类切换
const handleCategoryChange = () => {
  // 过滤逻辑在 computed 中处理
}

// 新增
const handleCreate = () => {
  isEdit.value = false
  editingId.value = null
  Object.assign(formData, {
    category: activeCategory.value,
    configKey: '',
    configValue: '',
    description: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  isEdit.value = true
  editingId.value = row.id
  Object.assign(formData, {
    category: row.category,
    configKey: row.configKey,
    configValue: row.configValue,
    description: row.description
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = async (id: number) => {
  try {
    await deleteConfig(id)
    ElMessage.success('删除成功')
    fetchConfigs()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (isEdit.value && editingId.value) {
          await updateConfig(editingId.value, formData)
          ElMessage.success('更新成功')
        } else {
          await createConfig(formData)
          ElMessage.success('创建成功')
        }
        dialogVisible.value = false
        fetchConfigs()
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 刷新缓存
const handleRefreshCache = async () => {
  try {
    await refreshConfigCache()
    ElMessage.success('缓存刷新成功')
  } catch (error) {
    ElMessage.error('缓存刷新失败')
  }
}

// 获取分类名称
const getCategoryName = (category: string) => {
  const item = configCategories.find(c => c.value === category)
  return item?.label || category
}

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

<style scoped lang="scss">
.system-config {
  .config-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  .config-table {
    :deep(.el-table__body-wrapper) {
      max-height: calc(100vh - 400px);
      overflow-y: auto;
    }
  }
}
</style>
