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

import { defaultHomeAnnouncements, mergeHomeConfig } from '@/features/listings/api/homeConfig'
import { updateSystemConfig, type SystemConfig } from '@/features/admin/api/systemConfigs'
import { safeParseJSON } from '@/utils/json'

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

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

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

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

function parseHomeAnnouncements(raw: string) {
  const parsed = safeParseJSON(raw, defaultHomeAnnouncements)
  return mergeHomeConfig({ announcements: Array.isArray(parsed) ? parsed : [] }).announcements
}

function linesToItems(value: string) {
  return value
    .split('\n')
    .map((item) => item.trim())
    .filter(Boolean)
}

function itemsToLines(items: string[]) {
  return items.join('\n')
}

function resetHomeAnnouncements() {
  homeAnnouncementLines.value = itemsToLines(defaultHomeAnnouncements)
}

async function handleSave() {
  submitting.value = true
  try {
    const value = JSON.stringify(linesToItems(homeAnnouncementLines.value), null, 2)
    await updateSystemConfig(props.config.key, {
      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="680px"
    @update:model-value="emit('update:modelValue', $event)"
  >
    <div class="dialog-body">
      <p class="config-key-label"><strong>{{ config.key }}</strong></p>

      <div class="home-config-editor">
        <div class="editor-toolbar">
          <span>首页公告</span>
          <el-button size="small" @click="resetHomeAnnouncements">恢复默认公告</el-button>
        </div>
        <el-form-item label="公告内容" class="full-control">
          <el-input
            v-model="homeAnnouncementLines"
            type="textarea"
            :rows="8"
            placeholder="一行一条公告，移动端会自动轮播展示"
          />
        </el-form-item>
      </div>

      <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;
}

.home-config-editor {
  display: grid;
  gap: 14px;
}

.editor-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.editor-toolbar span {
  color: #30343a;
  font-weight: 700;
}

.full-control {
  width: 100%;
}

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