<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { computed, ref, watch } from 'vue'

import { updateSystemConfig, type SystemConfig } from '@/features/admin/api/systemConfigs'
import { getSystemConfigSelectOptions, type SystemConfigOption } from '@/utils/systemConfigOptions'

const props = defineProps<{
  modelValue: boolean
  config: SystemConfig
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', val: boolean): void
  (e: 'saved'): void
}>()

const submitting = ref(false)
const value = ref('')
const description = ref('')

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      value.value = props.config.value || ''
      description.value = props.config.description || ''
    }
  },
  { immediate: true }
)

const isStructuredConfig = computed(() => {
  const trimmed = value.value.trim()
  return trimmed.startsWith('{') || trimmed.startsWith('[')
})

const selectOptions = computed<SystemConfigOption[] | null>(() => {
  const options = getSystemConfigSelectOptions(props.config.key)
  if (!options) return null
  if (!value.value || options.some((item) => item.value === value.value)) {
    return options
  }
  return [{ label: `当前值：${value.value}`, value: value.value }, ...options]
})

async function handleSave() {
  submitting.value = true
  try {
    await updateSystemConfig(props.config.key, {
      value: value.value,
      description: description.value,
    })
    ElMessage.success('配置已更新')
    emit('saved')
    emit('update:modelValue', false)
  } catch (error) {
    ElMessage.error(readError(error, '保存失败'))
  } finally {
    submitting.value = false
  }
}

function readError(error: unknown, fallback: string) {
  if (typeof error === 'object' && error && 'response' in error) {
    const response = (error as { response?: { data?: { message?: string } } }).response
    return response?.data?.message || fallback
  }
  return fallback
}
</script>

<template>
  <el-dialog
    :model-value="modelValue"
    title="编辑系统配置"
    width="560px"
    @update:model-value="emit('update:modelValue', $event)"
  >
    <div class="dialog-body">
      <p class="config-key-label"><strong>{{ config.key }}</strong></p>

      <el-form-item v-if="isStructuredConfig" label="配置值 (JSON)" class="full-control">
        <el-input v-model="value" type="textarea" :rows="12" placeholder="配置值 JSON" />
      </el-form-item>
      <el-form-item v-else-if="selectOptions" label="配置值" class="full-control">
        <el-select v-model="value" class="full-select" placeholder="请选择配置值">
          <el-option
            v-for="option in selectOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-else label="配置值" class="full-control">
        <el-input v-model="value" placeholder="配置值" />
      </el-form-item>

      <el-form-item label="配置说明" class="desc-item">
        <el-input v-model="description" type="textarea" :rows="3" placeholder="配置说明" />
      </el-form-item>
    </div>
    <template #footer>
      <el-button @click="emit('update:modelValue', false)">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-body {
  display: grid;
  gap: 16px;
}

.config-key-label {
  margin: 0;
  color: #374151;
}

.full-control {
  width: 100%;
}

.full-select {
  width: 100%;
}

.desc-item {
  margin-top: 14px;
  margin-bottom: 0;
}
</style>
