<template>
  <div>
    <el-card class="box-card">
<!--      <template #header>-->
<!--        <div class="card-header">-->
<!--          <span>AI问答编排设置</span>-->
<!--        </div>-->
<!--      </template>-->

      <el-form
        ref="settingsFormRef"
        :model="settingsForm"
        :rules="rules"
        label-width="120px"
        class="settings-form"
      >
        <!-- 欢迎语图标设置 -->
        <el-form-item label="欢迎语图标" prop="welcomeIcon">
          <div class="welcome-icon-container">
            <div class="icon-preview">
              <img
                v-if="settingsForm.welcomeIcon"
                :src="settingsForm.welcomeIcon"
                alt="欢迎语图标"
                class="welcome-icon-preview"
              />
              <div v-else class="icon-placeholder">
                <el-icon><Picture /></el-icon>
                <span>暂无图标</span>
              </div>
            </div>
            <div class="icon-actions">
              <el-upload
                ref="iconUploadRef"
                :show-file-list="false"
                :before-upload="beforeIconUpload"
                :on-success="handleIconSuccess"
                :on-error="handleIconError"
                accept="image/*"
                action="/api/upload"
                class="icon-upload"
              >
                <el-button type="primary" size="small">
                  <el-icon><Upload /></el-icon>
                  上传图标
                </el-button>
              </el-upload>
              <el-button
                v-if="settingsForm.welcomeIcon"
                type="danger"
                size="small"
                @click="removeIcon"
              >
                <el-icon><Delete /></el-icon>
                删除图标
              </el-button>
            </div>
          </div>
        </el-form-item>

        <!-- 欢迎语标题设置 -->
        <el-form-item label="欢迎语标题" prop="welcomeTitle">
          <el-input
            v-model="settingsForm.welcomeTitle"
            placeholder="请输入欢迎语标题..."
            class="welcome-title-input"
            maxlength="50"
            show-word-limit
            type="text"
          />
        </el-form-item>

        <!-- 欢迎语设置 -->
        <el-form-item label="欢迎语" prop="welcomeMessage">
          <el-input
            v-model="settingsForm.welcomeMessage"
            type="text"
            placeholder="请输入欢迎语内容..."
            class="welcome-text-input"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <!-- 预设问题设置 -->
        <el-form-item label="预设问题" prop="presetQuestions">
          <div class="preset-questions">
            <div
              v-for="(question, index) in settingsForm.presetQuestions"
              :key="index"
              class="question-item"
            >
              <el-input
                v-model="settingsForm.presetQuestions[index]"
                placeholder="请输入预设问题内容..."
                class="question-input"
              >
                <template #append>
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeQuestion(index)"
                    :disabled="settingsForm.presetQuestions.length <= 1"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </div>

            <el-button
              type="primary"
              plain
              size="small"
              @click="addQuestion"
              class="add-question-btn"
            >
              <el-icon><Plus /></el-icon>
              添加预设问题
            </el-button>
          </div>
        </el-form-item>

        <!-- 历史聊天记录数量设置 -->
        <el-form-item label="历史记录数量" prop="historyCount">
          <el-input-number
            v-model="settingsForm.historyCount"
            :min="1"
            :max="100"
            :precision="0"
            placeholder="请输入历史聊天记录数量"
            class="history-count-input"
          />
          <span class="input-tip">条（1-100之间的正整数）</span>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="saveSettings" :loading="loading">
            保存设置
          </el-button>
          <el-button @click="resetSettings">重置</el-button>
          <el-button @click="previewSettings">预览效果</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="设置预览"
      width="800px"
      :before-close="handlePreviewClose"
    >
      <div class="preview-content">
        <div class="preview-section">
          <h4>欢迎语图标预览：</h4>
          <div class="icon-preview-section">
            <img
              v-if="settingsForm.welcomeIcon"
              :src="settingsForm.welcomeIcon"
              alt="欢迎语图标"
              class="preview-icon"
            />
            <div v-else class="no-icon">暂无图标</div>
          </div>
        </div>

        <div class="preview-section">
          <h4>欢迎语标题预览：</h4>
          <div class="welcome-title-preview">{{ settingsForm.welcomeTitle }}</div>
        </div>

        <div class="preview-section">
          <h4>欢迎语预览：</h4>
          <div class="welcome-preview">{{ settingsForm.welcomeMessage }}</div>
        </div>

        <div class="preview-section">
          <h4>预设问题预览：</h4>
          <div class="questions-preview">
            <el-tag
              v-for="(question, index) in settingsForm.presetQuestions"
              :key="index"
              class="question-tag"
              type="info"
            >
              {{ question }}
            </el-tag>
          </div>
        </div>

        <div class="preview-section">
          <h4>历史记录数量：</h4>
          <span>{{ settingsForm.historyCount }} 条</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAiChatSettings, saveAiChatSettings } from '@/api/ai/base/aiApp/index'
import {
  Delete,
  Plus,
  Picture,
  Upload
} from '@element-plus/icons-vue'

// 表单引用
const settingsFormRef = ref()
const iconUploadRef = ref()

// 加载状态
const loading = ref(false)

// 预览对话框
const previewVisible = ref(false)

// 表单数据
const settingsForm = reactive({
  welcomeIcon: '',
  welcomeTitle: 'AI智能问答',
  welcomeMessage: '欢迎使用AI智能问答系统！\n\n我可以帮助您解答各种问题，请随时向我提问。',
  presetQuestions: [
    '什么是人工智能？',
    '如何提高工作效率？',
    '推荐一些学习资源'
  ],
  historyCount: 20
})

// 表单验证规则
const rules = {
  welcomeMessage: [
    { required: true, message: '请输入欢迎语内容', trigger: 'blur' }
  ],
  historyCount: [
    { required: true, message: '请输入历史记录数量', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '历史记录数量必须在1-100之间', trigger: 'blur' }
  ]
}

// 图标上传前验证
const beforeIconUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 图标上传成功
const handleIconSuccess = (response) => {
  if (response.code === 200) {
    settingsForm.welcomeIcon = response.data
    ElMessage.success('图标上传成功')
  } else {
    ElMessage.error('图标上传失败')
  }
}

// 图标上传失败
const handleIconError = () => {
  ElMessage.error('图标上传失败')
}

// 删除图标
const removeIcon = () => {
  settingsForm.welcomeIcon = ''
  ElMessage.success('图标已删除')
}

// 添加预设问题
const addQuestion = () => {
  settingsForm.presetQuestions.push('')
}

// 删除预设问题
const removeQuestion = (index) => {
  if (settingsForm.presetQuestions.length > 1) {
    settingsForm.presetQuestions.splice(index, 1)
  }
}

// 保存设置
const saveSettings = async () => {
  try {
    await settingsFormRef.value.validate()

    loading.value = true

    // 验证预设问题不能为空
    const emptyQuestions = settingsForm.presetQuestions.filter(q => !q.trim())
    if (emptyQuestions.length > 0) {
      ElMessage.error('预设问题不能为空，请填写完整')
      return
    }

    // 调用API保存设置
    await saveAiChatSettings(settingsForm)

    ElMessage.success('设置保存成功')
    loading.value = false
  } catch (error) {
    loading.value = false
    console.error('保存设置失败:', error)
    ElMessage.error('保存设置失败，请重试')
  }
}

// 重置设置
const resetSettings = async () => {
  try {
    await ElMessageBox.confirm('确定要重置所有设置吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 重置为默认值
    settingsForm.welcomeIcon = ''
    settingsForm.welcomeTitle = 'AI智能问答'
    settingsForm.welcomeMessage = '欢迎使用AI智能问答系统！\n\n我可以帮助您解答各种问题，请随时向我提问。'
    settingsForm.presetQuestions = [
      '什么是人工智能？',
      '如何提高工作效率？',
      '推荐一些学习资源'
    ]
    settingsForm.historyCount = 20

    ElMessage.success('设置已重置')
  } catch (error) {
    // 用户取消操作
  }
}

// 预览设置
const previewSettings = () => {
  previewVisible.value = true
}

// 关闭预览对话框
const handlePreviewClose = () => {
  previewVisible.value = false
}

// 简单的Markdown渲染
const renderMarkdown = (text) => {
  if (!text) return ''

  return text
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank">$1</a>')
    .replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
    .replace(/\n/g, '<br>')
}

// 组件挂载时加载设置
onMounted(async () => {
  try {
    // 调用API加载现有设置
    const response = await getAiChatSettings()
    Object.assign(settingsForm, response.data)
  } catch (error) {
    console.error('加载设置失败:', error)
    ElMessage.error('加载设置失败')
  }
})
</script>

<style scoped>
.app-container {
  padding: 1px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.settings-form {
  max-width: 800px;
}

.welcome-editor {
  position: relative;
}

.welcome-textarea {
  margin-bottom: 10px;
}

.editor-toolbar {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.preset-questions {
  width: 100%;
}

.question-item {
  margin-bottom: 10px;
}

.question-input {
  width: 100%;
}

.add-question-btn {
  margin-top: 10px;
}

.history-count-input {
  width: 200px;
}

.input-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 14px;
}

.preview-content {
  padding: 20px 0;
}

.preview-section {
  margin-bottom: 30px;
}

.preview-section h4 {
  margin-bottom: 10px;
  color: #303133;
  font-weight: 600;
}

.welcome-preview {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
  line-height: 1.6;
}

.welcome-preview :deep(strong) {
  font-weight: bold;
}

.welcome-preview :deep(em) {
  font-style: italic;
}

.welcome-preview :deep(a) {
  color: #409eff;
  text-decoration: none;
}

.welcome-preview :deep(a:hover) {
  text-decoration: underline;
}

.welcome-preview :deep(pre) {
  background-color: #f6f8fa;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  margin: 10px 0;
}

.welcome-preview :deep(code) {
  font-family: 'Courier New', monospace;
  background-color: #f6f8fa;
  padding: 2px 4px;
  border-radius: 2px;
}

.questions-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.question-tag {
  margin-bottom: 5px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .settings-form {
    max-width: 100%;
  }

  .history-count-input {
    width: 100%;
  }

  .input-tip {
    display: block;
    margin-left: 0;
    margin-top: 5px;
  }
}
</style>
