<template>
  <a-drawer
    :open="open"
    title="对话配置"
    :width="360"
    @close="$emit('close')"
  >
    <a-form layout="vertical">
      <a-form-item label="对话目标">
        <a-textarea
          v-model:value="config.goal"
          placeholder="例如：分析政策要点和实施影响"
          :rows="3"
        />
      </a-form-item>

      <a-form-item label="风格 / 角色">
        <div class="style-presets">
          <a-tag
            v-for="preset in stylePresets"
            :key="preset.value"
            :color="config.style === preset.value ? 'blue' : 'default'"
            class="style-tag"
            @click="config.style = preset.value"
          >
            {{ preset.label }}
          </a-tag>
        </div>
        <a-input
          v-model:value="config.style"
          placeholder="或自定义角色/风格"
          style="margin-top: 8px"
        />
      </a-form-item>

      <a-form-item label="回答长度">
        <a-radio-group v-model:value="config.answer_length">
          <a-radio-button value="short">简短</a-radio-button>
          <a-radio-button value="medium">适中</a-radio-button>
          <a-radio-button value="long">详细</a-radio-button>
        </a-radio-group>
      </a-form-item>

      <a-button type="primary" @click="handleSave" :loading="saving">
        保存配置
      </a-button>
    </a-form>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useNotebookStore } from '@/stores/notebook'
import { updateChatConfig } from '@/api/notebook'
import type { NotebookConfig } from '@/types/notebook'

const props = defineProps<{
  open: boolean
  notebookId: string
}>()

const emit = defineEmits<{
  close: []
}>()

const store = useNotebookStore()
const saving = ref(false)

const stylePresets = [
  { label: '政策分析师', value: '政策分析师，专业严谨，注重数据和法规依据' },
  { label: '通俗讲解', value: '用通俗易懂的语言讲解，避免专业术语' },
  { label: '研究助手', value: '学术研究助手，注重逻辑推理和文献引用' },
  { label: '汇报撰写', value: '公文写作风格，结构清晰，用语规范' },
  { label: '批判思考', value: '批判性思维视角，分析优缺点和潜在风险' },
  { label: '简明扼要', value: '极简风格，只给核心结论和关键数据' },
]

const config = ref<NotebookConfig>({
  goal: '',
  style: '',
  answer_length: 'medium',
})

watch(
  () => store.currentNotebook?.config,
  (cfg) => {
    if (cfg) {
      config.value = { ...cfg }
    }
  },
  { immediate: true },
)

async function handleSave() {
  saving.value = true
  try {
    await updateChatConfig(props.notebookId, config.value)
    await store.updateNotebook(props.notebookId, { config: config.value })
    message.success('配置已保存')
    emit('close')
  } catch {
    message.error('保存失败')
  } finally {
    saving.value = false
  }
}
</script>

<style scoped lang="less">
.style-presets {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.style-tag {
  cursor: pointer;
  border-radius: 4px;
  font-size: 12px;

  &:hover {
    opacity: 0.8;
  }
}
</style>
