<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchAutoWelcomeMessage, updateAutoWelcomeMessage } from '@/features/chats'

const loading = ref(false)
const saving = ref(false)
const message = ref('')
const editing = ref(false)

onMounted(async () => {
  await loadMessage()
})

async function loadMessage() {
  loading.value = true
  try {
    message.value = await fetchAutoWelcomeMessage()
  } catch {
    ElMessage.error('加载自动话术失败')
  } finally {
    loading.value = false
  }
}

async function handleSave() {
  if (!message.value.trim()) {
    ElMessage.warning('话术内容不能为空')
    return
  }
  saving.value = true
  try {
    await updateAutoWelcomeMessage(message.value.trim())
    ElMessage.success('保存成功')
    editing.value = false
  } catch {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

function startEdit() {
  editing.value = true
}

function cancelEdit() {
  editing.value = false
  loadMessage()
}
</script>

<template>
  <div class="auto-welcome-config" v-loading="loading">
    <div class="config-header">
      <h3>建群自动话术</h3>
      <p>订单群聊创建后自动发送的欢迎消息</p>
    </div>
    <div class="config-content">
      <template v-if="editing">
        <el-input
          v-model="message"
          type="textarea"
          :rows="4"
          maxlength="500"
          show-word-limit
          placeholder="输入建群后自动发送的话术"
        />
        <div class="config-actions">
          <el-button size="small" @click="cancelEdit">取消</el-button>
          <el-button size="small" type="primary" :loading="saving" @click="handleSave">
            保存
          </el-button>
        </div>
      </template>
      <template v-else>
        <div class="preview-box">
          <p>{{ message || '未设置' }}</p>
        </div>
        <el-button size="small" @click="startEdit">编辑</el-button>
      </template>
    </div>
  </div>
</template>

<style scoped>
.auto-welcome-config {
  padding: 20px;
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.config-header {
  margin-bottom: 16px;
}

.config-header h3 {
  margin: 0 0 4px;
  font-size: 16px;
  color: #111827;
}

.config-header p {
  margin: 0;
  color: #6b7280;
  font-size: 13px;
}

.config-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.config-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.preview-box {
  padding: 12px;
  background: #f8fafc;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  min-height: 60px;
}

.preview-box p {
  margin: 0;
  color: #374151;
  line-height: 1.5;
  white-space: pre-wrap;
}
</style>
