<template>
  <div class="config-page">
    <a-card class="mb-4">
      <template #title>系统配置</template>
      <template #extra>
        <a-button v-permission="'config:create'" type="primary" @click="handleAdd">新增配置</a-button>
      </template>
    </a-card>
    <a-table :columns="columns" :data-source="dataSource" :loading="loading" :pagination="pagination"
      @change="handleTableChange">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'value'">
          <a-typography-paragraph :ellipsis="{ rows: 1, expandable: true }" style="margin: 0; max-width: 300px">
            {{ record.value || '-' }}
          </a-typography-paragraph>
        </template>
        <template v-if="column.key === 'description'">
          <span>{{ record.description || '-' }}</span>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button v-permission="'config:update'" type="link" size="small" @click="handleEdit(record)">
              编辑
            </a-button>
            <a-button v-permission.hide="'config:delete'" type="link" size="small" danger @click="handleDelete(record)">
              删除
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增/编辑配置弹窗 -->
    <a-modal v-model:open="modalVisible" :title="modalTitle" :confirm-loading="submitLoading" @ok="handleSubmit"
      @cancel="handleCancel" width="600px" :loading="detailLoading">
      <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="配置键" name="key">
          <a-input v-model:value="form.key" placeholder="请输入配置键（英文，如：site_name）" :maxlength="100"
            :disabled="!!editingId" />
        </a-form-item>
        <a-form-item label="配置值" name="value">
          <a-textarea v-model:value="form.value" placeholder="请输入配置值" :rows="4" :maxlength="500" show-count />
        </a-form-item>
        <a-form-item label="配置描述" name="description">
          <a-textarea v-model:value="form.description" placeholder="请输入配置描述" :rows="3" :maxlength="200" show-count />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { TableColumnsType, FormInstance } from 'ant-design-vue'
import { configApi, type Config, type CreateConfigForm, type UpdateConfigForm } from '@/api/config'
import { useListRequest } from '@/composables/useListRequest'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

const submitLoading = ref(false)
const detailLoading = ref(false)
const modalVisible = ref(false)
const modalTitle = ref('新增配置')
const formRef = ref<FormInstance>()
const editingId = ref<number | null>(null)

// 使用列表请求组合函数
const {
  loading,
  dataSource,
  pagination,
  handleTableChange,
  refresh: refreshList,
} = useListRequest<Config>({
  requestFn: configApi.getList,
  errorMessage: '获取配置列表失败',
})

const form = reactive<CreateConfigForm>({
  key: '',
  value: '',
  description: '',
})

const rules = {
  key: [
    { required: true, message: '请输入配置键', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
      message: '配置键只能包含字母、数字和下划线，且必须以字母开头',
      trigger: 'blur',
    },
    { max: 100, message: '配置键不能超过100个字符', trigger: 'blur' },
  ],
  value: [
    { required: true, message: '请输入配置值', trigger: 'blur' },
    { max: 500, message: '配置值不能超过500个字符', trigger: 'blur' },
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' },
  ],
}

const columns: TableColumnsType = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '配置键', dataIndex: 'key', key: 'key' },
  { title: '配置值', dataIndex: 'value', key: 'value' },
  { title: '描述', dataIndex: 'description', key: 'description' },
  { title: '操作', key: 'action', width: 150, fixed: 'right' },
]

// 新增配置
const handleAdd = () => {
  // 权限检查
  if (!authStore.hasPermission('config:create')) {
    message.error('您没有创建配置的权限')
    return
  }

  modalTitle.value = '新增配置'
  editingId.value = null
  modalVisible.value = true
  nextTick(() => {
    formRef.value?.resetFields()
    form.key = ''
    form.value = ''
    form.description = ''
  })
}

// 编辑配置
const handleEdit = async (record: Config) => {
  modalTitle.value = '编辑配置'
  editingId.value = record.id
  modalVisible.value = true
  detailLoading.value = true

  try {
    const detail = await configApi.getDetail(record.id)
    form.key = detail.key
    form.value = detail.value
    form.description = detail.description || ''
  } catch (error) {
    message.error('获取配置详情失败')
    modalVisible.value = false
  } finally {
    detailLoading.value = false
  }
}

// 删除配置
const handleDelete = (record: Config) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除配置 "${record.key}" 吗？删除后无法恢复。`,
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        await configApi.delete(record.id)
        message.success('删除成功')
        refreshList()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || '删除失败'
        message.error(errorMessage)
      }
    },
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    if (editingId.value) {
      // 编辑
      await configApi.update(editingId.value, form)
      message.success('编辑成功')
    } else {
      // 新增
      await configApi.create(form)
      message.success('新增成功')
    }

    modalVisible.value = false
    refreshList()
  } catch (error: any) {
    if (error?.errorFields) {
      // 表单验证错误
      return
    }
    const errorMessage =
      error?.response?.data?.message ||
      (editingId.value ? '编辑失败' : '新增失败')
    message.error(errorMessage)
  } finally {
    submitLoading.value = false
  }
}

// 取消表单
const handleCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}
</script>

<style scoped lang="scss">
.config-page {
  // 系统配置页面样式
}
</style>
