<template>
  <div class="flex gap-2">
    <div class="h-11 w-11">
      <img class="h-full w-full" src="@/assets/images/chat/default-logo.png" />
    </div>
    <div
      class="flex flex-1 flex-col overflow-hidden"
      :class="
        (item.slot ? '' : 'max-w-fit') +
        ' ' +
        (item.workflows?.length > 0 ? 'w-full max-w-full' : '')
      "
    >
      <template v-if="item.prologue">
        <div
          class="answer-markdown w-fit overflow-hidden rounded-lg rounded-tl-none bg-[#EAF1FF] p-2.75 text-[#303133]"
          v-html="item.prologue"
        />
        <template v-if="item.prologueQuestions?.length > 0">
          <template v-if="item.prologueNum == 0">
            <div class="mt-2 ml-2.5 flex flex-col gap-2">
              <template v-for="pq in item.prologueQuestions">
                <div
                  class="__hover w-fit text-sm text-[var(--czr-main-color)]"
                  @click="$emit('setText', { text: pq, send: true })"
                >
                  {{ pq }}
                </div>
              </template>
            </div>
          </template>
          <template v-else>
            <div class="mt-2 flex flex-wrap gap-x-6 gap-y-1.5">
              <template
                v-for="pq in item.prologueQuestions.filter(
                  (v, i) => i < item.prologueNum,
                )"
              >
                <div
                  class="__hover w-fit rounded-sm bg-[#F6F6F6] px-2.5 py-1 text-sm text-[var(--czr-main-color)]"
                  @click="$emit('setText', { text: pq, send: true })"
                >
                  {{ pq }}
                </div>
              </template>
            </div>
          </template>
        </template>
      </template>
      <template v-else-if="item.loading">
        <div class="answer-loading">
          <span></span>
          <span></span>
          <span></span>
        </div>
      </template>
      <template v-else>
        <div
          class="max-w-full rounded-lg rounded-tl-none bg-[#EAF1FF] p-2.75 text-[#303133]"
          :class="item.workflows?.length > 0 ? 'w-full' : 'w-fit'"
        >
          <template v-if="item.workflows?.length > 0">
            <div
              class="flex flex-col rounded-sm p-2 text-xs"
              :class="
                item.workflowStatus === 'succeeded'
                  ? 'bg-[var(--czr-success-color)]/15'
                  : item.workflowStatus === 'failed'
                    ? 'bg-[var(--czr-error-color)]/15'
                    : 'bg-[#ffffff]/50'
              "
            >
              <div
                class="__hover flex items-center"
                @click="state.workflowExpend = !state.workflowExpend"
              >
                <template v-if="item.workflowStatus === 'succeeded'">
                  <SvgIcon
                    name="success"
                    size="14"
                    color="var(--czr-success-color)"
                  />
                </template>
                <template v-else-if="item.workflowStatus === 'failed'">
                  <SvgIcon
                    name="failed"
                    size="14"
                    color="var(--czr-error-color)"
                  />
                </template>
                <template v-else>
                  <SvgIcon name="wait" size="14" />
                </template>
                <div class="ml-0.5">工作流</div>
                <template v-if="state.workflowExpend">
                  <SvgIcon
                    name="czr_arrow"
                    size="8"
                    rotate="90"
                    class="ml-auto"
                  />
                </template>
                <template v-else>
                  <SvgIcon name="czr_arrow" size="8" class="ml-1" />
                </template>
              </div>
              <div class="mt-2 flex flex-col gap-1">
                <template v-for="wf in item.workflows">
                  <div class="rounded-sm bg-[#ffffff] p-1">
                    <div
                      class="flex items-center"
                      :class="wf.status ? '__hover' : 'cursor-no-drop'"
                      @click="
                        wf.status ? (wf.__expend = !wf.__expend) : undefined
                      "
                    >
                      <template v-if="wf.__expend">
                        <SvgIcon name="czr_arrow" size="8" rotate="90" />
                      </template>
                      <template v-else>
                        <SvgIcon name="czr_arrow" size="8" />
                      </template>
                      <img
                        :src="nodeSources[wf.nodeType].icon"
                        class="ml-1 size-4"
                      />
                      <div class="ml-0.5 flex-1 font-bold" v-title>
                        {{ wf.title }}
                      </div>
                      <div class="ml-auto flex items-center gap-1">
                        <div class="text-[10px]">
                          <template v-if="wf.tokens">
                            {{ wf.tokens }} Tokens ·
                          </template>
                          {{ formatTimeDuration(wf.elapsedTime) }}
                        </div>
                        <template v-if="wf.status === 'succeeded'">
                          <SvgIcon
                            name="success"
                            size="12"
                            color="var(--czr-success-color)"
                          />
                        </template>
                        <template v-else-if="wf.status === 'failed'">
                          <SvgIcon
                            name="failed"
                            size="12"
                            color="var(--czr-error-color)"
                          />
                        </template>
                        <template v-else>
                          <div class="text-[var(--czr-main-color)]/70">
                            Running
                          </div>
                          <SvgIcon name="wait" size="12" />
                        </template>
                      </div>
                    </div>
                    <div v-if="wf.__expend" class="mt-1 flex flex-col gap-1">
                      <div
                        v-if="wf.error"
                        class="rounded-sm border-1 border-[var(--czr-error-color)]/10 shadow"
                      >
                        <div
                          class="flex items-center justify-between rounded-t-sm bg-[#000000]/10 p-1 text-xs"
                        >
                          错误信息
                          <el-tooltip content="复制" placement="top">
                            <SvgIcon
                              class="__hover"
                              name="copy"
                              size="14"
                              @click="onCopy(wf.error)"
                            />
                          </el-tooltip>
                        </div>
                        <div
                          class="bg-[var(--czr-error-color)]/10 p-1 pt-1 break-words"
                        >
                          {{ wf.error }}
                        </div>
                      </div>
                      <div
                        v-if="wf.inputData"
                        class="rounded-sm border-1 border-[#000000]/5 shadow"
                      >
                        <div
                          class="flex items-center justify-between rounded-t-sm bg-[#000000]/10 p-1 text-xs"
                        >
                          输入
                          <el-tooltip content="复制" placement="top">
                            <SvgIcon
                              class="__hover"
                              name="copy"
                              size="14"
                              @click="onCopy(JSON.stringify(wf.inputData))"
                            />
                          </el-tooltip>
                        </div>
                        <pre
                          class="mt-1 p-1 break-words"
                          style="margin-bottom: 0"
                          >{{ wf.inputData }}</pre
                        >
                      </div>
                      <div
                        v-if="wf.outputData"
                        class="rounded-sm border-1 border-[#000000]/5 shadow"
                      >
                        <div
                          class="flex items-center justify-between rounded-t-sm bg-[#000000]/10 p-1 text-xs"
                        >
                          输出
                          <el-tooltip content="复制" placement="top">
                            <SvgIcon
                              class="__hover"
                              name="copy"
                              size="14"
                              @click="onCopy(JSON.stringify(wf.outputData))"
                            />
                          </el-tooltip>
                        </div>
                        <pre
                          class="mt-1 p-1 break-words"
                          style="margin-bottom: 0"
                          >{{ wf.outputData }}</pre
                        >
                      </div>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </template>
          <template v-for="part in textCpt">
            <template v-if="part.type === 'think'">
              <thinkCom :text="part.text" />
            </template>
            <template v-else>
              <div
                class="answer-markdown"
                :class="{ error: item.error }"
                v-html="md.render(part.text.replace(/^<think>/, ''))"
              />
            </template>
          </template>
        </div>
        <div
          class="mt-2 flex items-center gap-2.5 px-2.5 text-[0.63rem] text-[#909399]"
          v-if="item.finished && !item.mock"
        >
          <div v-if="item.time">{{ formatTimeDuration(item.time) }}</div>
          <div v-if="item.tokens">{{ item.tokens }} Tokens</div>
          <div class="mx-auto" v-if="item.time || item.tokens" />
          <template v-if="!item.error && item.messageId">
            <template v-if="item.feedback == 1">
              <el-tooltip content="取消喜欢" placement="top">
                <SvgIcon
                  class="__hover"
                  name="good"
                  size="20"
                  :active="true"
                  @click="$emit('onFeedback', item, 0)"
                />
              </el-tooltip>
            </template>
            <template v-else-if="item.feedback == 2">
              <el-tooltip content="取消不喜欢" placement="top">
                <SvgIcon
                  class="__hover"
                  name="good"
                  size="20"
                  rotate="180"
                  color="var(--czr-error-color)"
                  @click="$emit('onFeedback', item, 0)"
                />
              </el-tooltip>
            </template>
            <template v-else>
              <el-tooltip content="喜欢" placement="top">
                <SvgIcon
                  class="__hover"
                  name="good"
                  size="20"
                  @click="$emit('onFeedback', item, 1)"
                />
              </el-tooltip>
              <el-tooltip content="不喜欢" placement="top">
                <SvgIcon
                  class="__hover"
                  name="good"
                  size="20"
                  rotate="180"
                  @click="$emit('onFeedback', item, 2)"
                />
              </el-tooltip>
            </template>
          </template>
          <template
            v-if="textCpt.filter((v) => v.type === 'response')[0]?.text"
          >
            <el-tooltip content="复制" placement="top">
              <SvgIcon
                class="__hover"
                name="copy"
                size="24"
                @click="
                  onCopy(textCpt.filter((v) => v.type === 'response')[0]?.text)
                "
              />
            </el-tooltip>
          </template>
          <el-tooltip content="重新生成" placement="top">
            <SvgIcon
              class="__hover"
              name="refresh"
              size="20"
              @click="$emit('onReBuild', item)"
            />
          </el-tooltip>
        </div>
        <template v-if="item.slot">
          <slot :name="item.slot" :props="item.slotProps" />
        </template>
        <template v-if="item.adviseLoading">
          <div class="mt-2 ml-2.5 text-sm text-[var(--czr-main-color)]">
            问题建议生成中……
          </div>
        </template>
        <template v-else-if="item.advise?.length > 0">
          <div class="mt-2 ml-2.5 flex flex-col gap-2">
            <template v-for="ad in item.advise">
              <div
                class="__hover w-fit text-sm text-[var(--czr-main-color)]"
                @click="$emit('setText', { text: ad, send: true })"
              >
                {{ ad }}
              </div>
            </template>
          </div>
        </template>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, onMounted, reactive, watch } from 'vue'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import { marked } from 'marked'
import DOMPurify from 'dompurify'
import thinkCom from './think.vue'
import { copy } from '@/utils/czr-util'
import { ElMessage } from 'element-plus'
import useTextToSpeech from '../audio/useTextToSpeech'
import { nodeSources } from '@/views/workflow/config'

const { speak, stop } = useTextToSpeech()
const md = new MarkdownIt({
  html: false, // 在源码中启用 HTML 标签
  highlight: (str, lang) => {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return `<pre class="hljs" style="padding: 10px"><code>${hljs.highlight(str, { language: lang }).value}</code></pre>`
      } catch (__) {}
    }
    return `<pre class="hljs" style="padding: 10px"><code>${md.utils.escapeHtml(str)}</code></pre>`
  },
})
const emit = defineEmits(['setText', 'onReBuild', 'onFeedback'])
const props = defineProps({
  item: {} as any,
  goodMap: {} as any,
  badMap: {} as any,
})
const state: any = reactive({
  workflowExpend: false,
})
const textCpt = computed(() => {
  const segments: any = []
  const rawContent = props.item.text

  // 正则表达式匹配<think>标签及其内容
  const thinkRegex = /<think>([\s\S]*?)<\/think>/g

  let match
  let lastIndex = 0

  while ((match = thinkRegex.exec(rawContent)) !== null) {
    // 添加think标签前的普通内容
    if (match.index > lastIndex) {
      segments.push({
        type: 'response',
        text: rawContent.substring(lastIndex, match.index),
      })
    }

    // 添加think内容
    segments.push({
      type: 'think',
      text: match[1].trim(),
    })

    lastIndex = thinkRegex.lastIndex
  }

  // 添加剩余内容
  if (lastIndex < rawContent.length) {
    segments.push({
      type: 'response',
      text: rawContent.substring(lastIndex).trim(),
    })
  }
  return segments
})
const onCopy = (text) => {
  copy(text)
  ElMessage.success('复制成功！')
}
const formatTimeDuration = (timestamp) => {
  if (timestamp < 1000) {
    return `${Math.round(timestamp)} ms`
  } else if (timestamp < 60000) {
    const seconds = timestamp / 1000
    return `${seconds.toFixed(1)} s` // 一位小数
  } else {
    const minutes = Math.floor(timestamp / 60000)
    const remainingSeconds = Math.floor((timestamp % 60000) / 1000)
    return `${minutes} m ${remainingSeconds} s`
  }
}
</script>

<style lang="scss" scoped>
.answer-loading {
  width: 50px;
  height: 100%;
  display: inline-flex;
  gap: 6px;
  align-items: center;
  justify-content: center;

  span {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #6c9eff;
    animation: ellipsis-bounce 1.4s infinite ease-in-out;
  }

  span:nth-child(1) {
    animation-delay: -0.32s;
  }

  span:nth-child(2) {
    animation-delay: -0.16s;
  }

  @keyframes ellipsis-bounce {
    0%,
    80%,
    100% {
      transform: translateY(4px);
    }
    40% {
      transform: translateY(-6px);
    }
  }
}
.answer-markdown {
  line-height: 1.5;
  &.error {
    color: red;
  }
  > * {
    word-break: break-all;
    text-align: justify;
    line-height: inherit;
    margin-bottom: 12px;
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
