<template>
  <view class="sandbox">
    <view class="model-selector">
      <text class="label">选择模型：</text>
      <picker :value="modelIndex" :range="models" range-key="name" @change="onModelChange">
        <text class="picker-value">{{ models[modelIndex]?.name || '选择模型' }}</text>
      </picker>
    </view>
    <scroll-view class="chat-area" scroll-y :scroll-into-view="scrollId">
      <view class="message" v-for="(msg, i) in messages" :key="i" :class="{ user: msg.role === 'user', ai: msg.role === 'assistant' }">
        <text class="role">{{ msg.role === 'user' ? '我' : 'AI' }}</text>
        <text class="content">{{ msg.content }}</text>
      </view>
      <view id="bottom"></view>
    </scroll-view>
    <view class="input-area">
      <input class="input" v-model="inputText" placeholder="输入消息..." @confirm="sendMessage" />
      <button class="btn-send" @tap="sendMessage" :loading="sending">发送</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { api } from '../../api/index'
import { useUserStore } from '../../store/user'

const userStore = useUserStore()
const models = ref<any[]>([])
const modelIndex = ref(0)
const messages = ref<{ role: string; content: string }[]>([])
const inputText = ref('')
const sending = ref(false)
const scrollId = ref('')

onMounted(async () => {
  try {
    models.value = (await api.models.list({ featured: true })) as any[] || []
  } catch (e) { /* ignore */ }
  loadHistory()
})

async function loadHistory() {
  try {
    const history: any = await api.sandbox.history({ pageSize: 50 })
    const sessions = history.items || []
    if (sessions.length > 0) {
      const last = sessions[sessions.length - 1]
      messages.value = (last.messages || [])
    }
  } catch (e) { /* ignore */ }
}

async function sendMessage() {
  if (!inputText.value || sending.value) return
  if (!userStore.isLoggedIn) { uni.navigateTo({ url: '/pages/login/index' }); return }

  const userMsg = inputText.value
  messages.value.push({ role: 'user', content: userMsg })
  inputText.value = ''
  sending.value = true
  nextTick(() => { scrollId.value = 'bottom' })

  try {
    const res: any = await api.sandbox.chat({
      model: models.value[modelIndex.value]?.name || 'meituan/longcat-flash-lite',
      message: userMsg,
    })
    messages.value.push({ role: 'assistant', content: res.reply || res.content || '无回复' })
    nextTick(() => { scrollId.value = 'bottom' })
  } catch (e: any) {
    messages.value.push({ role: 'assistant', content: '请求失败，请重试' })
  } finally {
    sending.value = false
  }
}

function onModelChange(e: any) {
  modelIndex.value = e.detail.value
}
</script>

<style scoped>
.sandbox { display: flex; flex-direction: column; height: 100vh; }
.model-selector {
  display: flex; align-items: center; padding: 16rpx 30rpx; background: var(--card);
  border-bottom: 1rpx solid var(--border);
}
.label { font-size: 26rpx; color: var(--muted-foreground); }
.picker-value { font-size: 26rpx; color: var(--brand); margin-left: 8rpx; }
.chat-area { flex: 1; padding: 20rpx 30rpx; overflow-y: auto; }
.message { margin-bottom: 20rpx; max-width: 80%; }
.message.user { align-self: flex-end; margin-left: auto; }
.message.ai { align-self: flex-start; }
.role { font-size: 22rpx; color: var(--muted-foreground); display: block; margin-bottom: 6rpx; }
.content {
  display: inline-block; padding: 16rpx 20rpx; border-radius: 12rpx; font-size: 28rpx; line-height: 1.6;
}
.message.user .content { background: var(--brand); color: var(--card); border-radius: 12rpx 0 12rpx 12rpx; }
.message.ai .content { background: var(--card); color: var(--foreground); border-radius: 0 12rpx 12rpx 12rpx; }
.input-area {
  display: flex; align-items: center; padding: 16rpx 30rpx; background: var(--card);
  border-top: 1rpx solid var(--border);
}
.input { flex: 1; background: var(--muted); border-radius: 12rpx; padding: 16rpx 24rpx; font-size: 28rpx; }
.btn-send {
  background: var(--brand); color: var(--card); border-radius: 10rpx; padding: 14rpx 28rpx;
  font-size: 26rpx; margin-left: 16rpx; border: none;
}
</style>
