<template>
  <div class="ai-chat-page">
    <div class="chat-toolbar">
      <span class="request-status">{{ loading ? '正在请求后台接口...' : '' }}</span>
      <div class="header-actions">
        <el-button icon="Delete" plain @click="clearMessages">清空</el-button>
      </div>
    </div>

    <div ref="messageListRef" class="message-list">
      <div v-if="messages.length === 0" class="empty-state">
        <div class="empty-title">暂无对话</div>
        <div class="empty-text">在下方输入问题后，后台返回的数据会展示在这里。</div>
      </div>

      <div v-for="(message, index) in messages" :key="`${message.createdAt || ''}-${index}`" class="message-row" :class="message.role">
        <div class="avatar">{{ message.role === 'user' ? '我' : 'AI' }}</div>
        <div class="message-bubble">
          <div class="message-meta">
            <span>{{ message.role === 'user' ? '用户' : '后台返回' }}</span>
            <span>{{ message.createdAt }}</span>
          </div>
          <div v-if="message.role === 'assistant'" class="message-content ai-html-content" v-html="message.content"></div>
          <div v-else class="message-content">{{ message.content }}</div>
        </div>
      </div>
    </div>

    <div class="input-panel">
      <el-input
        v-model="inputText"
        type="textarea"
        resize="none"
        maxlength="4000"
        show-word-limit
        placeholder="请输入对话内容，Ctrl + Enter 发送"
        @keydown="handleInputKeydown"
      />
      <div class="input-actions">
        <span class="input-tip">Ctrl + Enter 发送</span>
        <el-button type="primary" icon="Promotion" :loading="loading" :disabled="!inputText.trim()" @click="handleSend"> 发送 </el-button>
      </div>
    </div>

    <el-dialog v-model="configDialog" title="AI 接口配置" width="560px" append-to-body>
      <el-form :model="configForm" label-width="110px">
        <el-form-item label="接口地址">
          <el-input v-model="configForm.endpoint" placeholder="预留，例如 /aiChat/chat 或第三方代理地址" />
        </el-form-item>
        <el-form-item label="模型">
          <el-input v-model="configForm.model" placeholder="预留模型名称" />
        </el-form-item>
        <el-form-item label="温度">
          <el-input-number v-model="configForm.temperature" :min="0" :max="2" :step="0.1" controls-position="right" />
        </el-form-item>
        <el-form-item label="系统提示词">
          <el-input v-model="configForm.systemPrompt" type="textarea" :rows="4" resize="none" placeholder="预留系统提示词" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="configDialog = false">取消</el-button>
        <el-button type="primary" @click="saveConfig">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AiChat" lang="ts">
import {  sendAiChatMessage } from '@/api/aiChat';
import { AiChatConfig, AiChatMessage, AiChatResponse } from '@/api/aiChat/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const loading = ref(false);
const inputText = ref('');
const messages = ref<AiChatMessage[]>([]);
const messageListRef = ref<HTMLDivElement>();

const configDialog = ref(false);

const configForm = ref<AiChatConfig>({
  endpoint: '/aiChat/chat',
  model: '',
  temperature: 0.7,
  systemPrompt: ''
});

function nowText() {
  return proxy?.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}') || '';
}

function normalizeResponse(res: AiChatResponse | any) {
  const data = res?.data ?? res;
  return typeof data?.content === 'string' ? data.content : '';
}

async function scrollToBottom() {
  await nextTick();
  const el = messageListRef.value;
  if (el) el.scrollTop = el.scrollHeight;
}

function handleInputKeydown(event: KeyboardEvent) {
  if (event.ctrlKey && event.key === 'Enter') {
    event.preventDefault();
    handleSend();
  }
}

function buildHistory() {
  return messages.value
    .filter((message) => message.role === 'user' || message.role === 'assistant')
    .map((message) => ({
      role: message.role,
      content: message.content
    }));
}

async function handleSend() {
  const text = inputText.value.trim();
  if (!text || loading.value) return;

  const history = buildHistory();
  const userMessage: AiChatMessage = {
    role: 'user',
    content: text,
    createdAt: nowText()
  };
  messages.value.push(userMessage);
  inputText.value = '';
  await scrollToBottom();

  loading.value = true;
  try {
    const res = await sendAiChatMessage({
      message: text,
      useFileKnowledge: true,
      useDatabaseKnowledge: true,
      history
    });
    const content = normalizeResponse(res);
    messages.value.push({
      role: 'assistant',
      content: content || '后台接口未返回可展示内容',
      createdAt: nowText()
    });
  } catch (error: any) {
    messages.value.push({
      role: 'assistant',
      content: error?.msg || error?.message || '后台接口调用失败',
      createdAt: nowText()
    });
  } finally {
    loading.value = false;
    await scrollToBottom();
  }
}

function clearMessages() {
  messages.value = [];
}

function saveConfig() {
  configDialog.visible = false;
  proxy?.$modal.msgSuccess('配置已保存到当前页面');
}

// async function loadConfig() {
//   try {
//     const res = await getAiChatConfig();
//     const data = (res as any).data || {};
//     configForm.value = {
//       ...configForm.value,
//       ...data
//     };
//   } catch {
//     // 后端配置接口暂未实现时，继续使用页面默认预留配置。
//   }
// }

onMounted(() => {
  // loadConfig();
});
</script>

<style scoped>
.ai-chat-page {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  overflow: hidden;
  background: #fff;
}

.chat-toolbar {
  display: flex;
  flex: 0 0 52px;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  border-bottom: 1px solid #e5e7eb;
  padding: 8px 16px;
  background: #fff;
}

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

.message-list {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  padding: 22px;
  background:
    linear-gradient(180deg, rgba(248, 250, 252, 0.96), rgba(255, 255, 255, 0.96)),
    repeating-linear-gradient(90deg, rgba(148, 163, 184, 0.12) 0, rgba(148, 163, 184, 0.12) 1px, transparent 1px, transparent 36px);
}

.empty-state {
  display: grid;
  min-height: 100%;
  place-content: center;
  text-align: center;
}

.empty-title {
  color: #111827;
  font-size: 20px;
  font-weight: 700;
}

.empty-text {
  margin-top: 10px;
  color: #64748b;
}

.message-row {
  display: flex;
  gap: 12px;
  margin-bottom: 18px;
}

.message-row.user {
  flex-direction: row-reverse;
}

.avatar {
  display: grid;
  flex: 0 0 36px;
  width: 36px;
  height: 36px;
  place-items: center;
  border-radius: 8px;
  background: #0f766e;
  color: #fff;
  font-size: 13px;
  font-weight: 700;
}

.message-row.user .avatar {
  background: #2563eb;
}

.message-bubble {
  max-width: min(760px, calc(100% - 54px));
  padding: 12px 14px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
}

.message-row.user .message-bubble {
  border-color: #bfdbfe;
  background: #eff6ff;
}

.message-meta {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 8px;
  color: #64748b;
  font-size: 12px;
}

.message-content {
  white-space: pre-wrap;
  word-break: break-word;
  color: #111827;
  font-size: 14px;
  line-height: 1.7;
}

.ai-html-content {
  white-space: normal;
}

.ai-html-content :deep(h1),
.ai-html-content :deep(h2),
.ai-html-content :deep(h3),
.ai-html-content :deep(h4) {
  margin: 12px 0 8px;
  color: #0f172a;
  font-weight: 700;
  line-height: 1.35;
}

.ai-html-content :deep(h2) {
  font-size: 18px;
}

.ai-html-content :deep(h3) {
  font-size: 16px;
}

.ai-html-content :deep(p) {
  margin: 8px 0;
}

.ai-html-content :deep(ul),
.ai-html-content :deep(ol) {
  margin: 8px 0;
  padding-left: 22px;
}

.ai-html-content :deep(table) {
  width: 100%;
  margin: 12px 0;
  border-collapse: collapse;
  font-size: 13px;
}

.ai-html-content :deep(th),
.ai-html-content :deep(td) {
  border: 1px solid #dbe3ef;
  padding: 8px 10px;
}

.ai-html-content :deep(th) {
  background: #f8fafc;
  color: #334155;
  font-weight: 700;
}

.ai-html-content :deep(code) {
  border-radius: 4px;
  background: #f1f5f9;
  padding: 2px 5px;
  color: #0f766e;
}

.ai-html-content :deep(blockquote) {
  margin: 12px 0;
  border-left: 4px solid #f59e0b;
  padding: 8px 12px;
  background: #fffbeb;
  color: #713f12;
}

.input-panel {
  flex: 0 0 154px;
  height: 154px;
  border-top: 1px solid #e5e7eb;
  padding: 14px 16px 16px;
  background: #fff;
}

.input-panel :deep(.el-textarea),
.input-panel :deep(.el-textarea__inner) {
  height: 88px;
}

.input-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-top: 10px;
}

.request-status {
  color: #64748b;
  font-size: 13px;
}

.input-tip {
  color: #94a3b8;
  font-size: 13px;
}

@media (max-width: 768px) {
  .chat-toolbar,
  .input-actions {
    align-items: stretch;
    flex-direction: column;
  }

  .chat-toolbar {
    flex-basis: 92px;
  }

  .header-actions {
    justify-content: flex-start;
  }

  .message-list {
    padding: 16px 12px;
  }
}
</style>
