<script setup lang="ts">
import Message from './Message.vue'
import { copy } from '@/utils/copy'
import { storeToRefs } from 'pinia'
import { useChatStore } from '@/stores/chat'
import { elScrollToBottom } from '@/utils/scroll'
import Sender from './Sender.vue'

const chatStore = useChatStore()
const { currentSession, sending } = storeToRefs(chatStore)
const { sendMessage, stopMessage } = chatStore

watch(
  () => currentSession.value,
  () => {
    elScrollToBottom('.message-list .box')
  },
  // 一定要深入监听
  { deep: true },
)

const title = computed(() => {
  // 限制标题的长度
  const oldTitle = currentSession.value.title
  const maxSize = 20
  if (oldTitle?.length > maxSize) {
    return oldTitle.slice(0, maxSize) + '...'
  }
  return oldTitle
})
</script>

<template>
  <div class="message-list">
    <div v-if="currentSession.id" class="header">
      <!-- <div class="title g-one-line">
                {{ currentSession.title }}
            </div> -->
      <BigTitle class="title" :title="currentSession.title" :text="title" size="36" />
    </div>
    <ElScrollbar
      class="box g-main-bg"
      :class="{
        radius: !currentSession.id,
      }"
    >
      <div v-if="currentSession.messages?.length" class="list">
        <Message
          v-for="message in currentSession.messages"
          :key="message.id"
          :loading="sending"
          v-bind="message as any"
          @copy="copy"
        />
      </div>
      <div v-else class="empty">
        <Empty content="暂无数据" type="learn"></Empty>
      </div>
    </ElScrollbar>
    <Sender v-if="currentSession.id" :loading="sending" @submit="sendMessage" @stop="stopMessage" />
  </div>
</template>

<style scoped lang="scss">
@use '../index.scss' as *;

.message-list {
  flex: 1;
  display: flex;
  flex-direction: column;

  .header {
    height: $header_h;
    display: flex;
    text-align: center;
    align-items: center;
    padding: 0 16px;
    background-color: $bg1;
    border-top-left-radius: $border_radius;
    border-top-right-radius: $border_radius;
    position: relative;

    .title {
      color: $font-color;
      font-size: 3vh;
      text-shadow: 0 0.25vh 0.25vh rgba(255, 255, 255, 1);
      font-family: $font-special;
      padding: 0 150px;
      width: 100%;
    }
  }

  .box {
    flex: 1;
    overflow: hidden;
    background-color: #ebfdff;

    // 公共
    :deep(.el-scrollbar__wrap) {
      overflow-y: auto;
    }

    :deep(.el-scrollbar__view) {
      padding: 1.67vh;
      min-height: 100%;
    }

    // 当前会话没有选中时
    &.radius {
      border-radius: $border_radius;
    }

    .empty {
      margin-top: 16.67vh;
    }

    .list {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
  }
}
</style>
