<template>
  <div class="ai-chat">
    <div class="ai-chat-header">
      <div class="ai-chat-header-info">
        <div class="logo">
          <img src="@/assets/webapp/12.svg" alt="" />
        </div>
        <div class="info">
          <div class="info-title">内容创作大师</div>
          <div class="info-sub-title">减少人工编写时间、提高效率</div>
        </div>
      </div>
    </div>
    <div class="ai-chat-content" ref="chatContentRef">
      <div class="ai-chat-header-tips">
        <div class="title pointer">您可以尝试提问：</div>
        <div class="tag pointer" v-for="item in tagList" :key="item" @click="questionText = item">
          {{ item }}
        </div>
      </div>
      <ul>
        <li v-for="(item, index) in questionList" :key="index">
          <!--问-->
          <div class="question">
            <div class="content-wrapper" style="margin-right: 8px">
              <div class="content">{{ item.question.content }}</div>
            </div>
            <div class="avatar">
              <img src="@/assets/user-icon.svg" alt="" />
            </div>
          </div>
          <!--答-->
          <div class="answer">
            <div class="avatar"><img src="@/assets/webapp/12.svg" alt="" /></div>
            <div class="content-wrapper" style="margin-left: 8px">
              <div class="content-loading" v-if="item.answer.status === 'init'">
                <RotateLoading />AI正在生成回答
              </div>
              <div class="content-loading" v-if="item.answer.status === 'error'">
                Ai对话异常,请稍后再试!
              </div>
              <MdPreview
                v-else
                ref="editorRef"
                editorId="preview-only"
                :modelValue="item.answer.content"
                :key="index"
                class="maxkb-md"
              />
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div class="ai-chat-footer">
      <el-input
        type="textarea"
        v-model="questionText"
        :rows="3"
        placeholder="请使用文字描述您的需求"
        resize="none"
        @keyup.enter="handleSendMsg"
      />
      <div :class="['button', loading ? 'btn-loading' : '']" @click="handleSendMsg">
        <img src="@/assets/webapp/13.svg" alt="" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { MsgWarning } from '@/utils/message'
import { aiChat } from '@/api/writing'
import { responseToText } from '@/request/fetchWithAbort'
import RotateLoading from './RotateLoading.vue'
import { guuid } from '@/utils/uuid'
import useStore from '@/stores'
const { dada } = useStore()

type AnswerStatus = 'init' | 'pending' | 'done' | 'error'

interface ChatMessage {
  question: {
    content: string
  }
  answer: {
    content: string
    status?: AnswerStatus
  }
}

const questionList = ref<ChatMessage[]>([])
const questionText = ref('')
const loading = ref(false)
const chatContentRef = ref<HTMLElement | null>(null)
const tagList = ref<any[]>(['帮我写10个金句', '帮我写一个投标文件的目录', '帮我写一份年终总结'])

let ticking = false

const scrollChatToBottom = () => {
  const container = chatContentRef.value
  if (!container || ticking) return

  requestAnimationFrame(() => {
    container.scrollTop = container.scrollHeight + 50
    ticking = false
  })
  ticking = true
}

const handleSendMsg = () => {
  if (loading.value || !questionText.value.trim()) return

  loading.value = true

  questionList.value.push({
    question: {
      content: questionText.value
    },
    answer: {
      content: '',
      status: 'init'
    }
  })

  sendMsg(questionText.value)

  nextTick(() => {
    questionText.value = ''
    scrollChatToBottom()
  })
}

const sendMsg = (content: string) => {
  const session_id = guuid(`${dada?.id}`)
  aiChat({ session_id, content })
    .then((response) => {
      setItemStatus('pending')
      responseToText(response, (status, data: any) => {
        if (status) {
          scrollChatToBottom()
          if (data.type === 'done') {
            setItemStatus('done')
            loading.value = false
            data.content && insertItemContent(data.content)
          } else if (data.type === 'error') {
            MsgWarning(data.error)
            setItemStatus('error')
            loading.value = false
          } else {
            insertItemContent(data.content)
          }
        }
      })
    })
    .catch((e) => {
      console.log(e)
      MsgWarning('Ai对话异常,请稍后再试!')
      loading.value = false
      setItemStatus('error')
    })
}

const insertItemContent = (content: string) => {
  const lastIndex = questionList.value.length - 1
  if (lastIndex >= 0) {
    questionList.value[lastIndex].answer.content = questionList.value[lastIndex].answer.content +=
      content
  }
}

const setItemStatus = (status: AnswerStatus) => {
  const lastIndex = questionList.value.length - 1
  if (lastIndex >= 0) {
    questionList.value[lastIndex].answer.status = status
  }
}
</script>

<style scoped lang="scss">
.ai-chat {
  padding: 0 20px;
  display: flex;
  flex-direction: column;
  height: 100%;

  &-header {
    &-info {
      padding: 9px 12px;
      display: flex;
      border-radius: 8px 8px 8px 8px;
      background: linear-gradient(90deg, #e7eeff 0%, #daeaff 48%, #daf4ff 100%);
      margin-bottom: 20px;
      &-title {
        font-weight: 500;
        font-size: 16px;
        color: #191919;
        margin-top: 7px;
        margin-bottom: 4px;
      }
      &-sub-title {
        font-weight: 400;
        font-size: 12px;
        color: #333333;
      }
    }

    &-tips {
      .title {
        font-weight: 500;
        font-size: 14px;
        color: #3067ef;
        line-height: 17px;
        margin-bottom: 10px;
      }

      .tag {
        padding: 11px 10px;
        background: #e8efff;
        border-radius: 4px 4px 4px 4px;
        font-weight: 400;
        font-size: 12px;
        color: #3067ef;
        line-height: 14px;
        margin-bottom: 5px;
      }
    }
  }

  &-content {
    flex: 1;
    overflow-y: scroll;
    margin-bottom: 20px;

    .question,
    .answer {
      display: flex;
      margin-bottom: 16px; // 增加一些间距

      .avatar {
        margin-top: 8px;
        margin-bottom: 4px;
        img {
          width: 28px;
          height: 28px;
        }
      }

      .content-wrapper {
        flex: 1;
        padding: 12px; // 添加填充
        border-radius: 8px; // 圆角
        background-color: #f0f0f0; // 背景色
        margin-top: 4px; // 与头像的垂直间距

        .content {
          // 内容文本的样式，可以根据需要调整
          font-size: 14px;
          color: #333;
          white-space: pre-wrap;
        }
        .content-loading {
          display: flex;
          align-items: center;
        }
      }
    }

    .question {
      align-items: flex-end; // 问题左对齐
      .content-wrapper {
        width: 60%;
        margin-left: 10%;
      }
    }

    .answer {
      align-items: flex-start; // 答案右对齐
      justify-content: flex-end;

      .content-wrapper {
        margin-right: 8px; // 与头像的水平间距
        background-color: #fff// 答案使用不同的背景色以示区分;
      }
    }
  }
  &-footer {
    position: relative;

    .button {
      width: 28px;
      height: 28px;
      position: absolute;
      right: 12px;
      bottom: 8px;
      background: #3067ef;
      border-radius: 32px 32px 32px 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;

      img {
        margin: 0 auto;
      }
    }
    .btn-loading {
      background-color: #999;
    }
  }
}
</style>
