<template>
  <div class="ai-analysis">
    <div class="ai-analysis-empty" v-if="loading">
      <Empty :autoFinish="autoFinish" :fail="fail"></Empty>
    </div>
    <div class="ai-analysis-text" v-html="renderedMarkdown" v-else></div>
  </div>
</template>

<script lang="ts" setup>
import DOMPurify from 'dompurify';
import MarkdownIt from 'markdown-it';
import { checkLimit, incrementCount } from '@/utils/limit';


import { ref, computed } from 'vue';
import { useMainStore } from '@/store';
import Empty from '@/components/CommonEmpty.vue';

const mainStore = useMainStore();
const loading = ref<boolean>(true);
const autoFinish = ref<boolean>(false);
const fail = ref<boolean>(false);

const rawText = ref<string>('');

const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true
});

// 去掉最外层 ```，渲染内部 Markdown
const renderedMarkdown = computed(() => {
  let content = rawText.value.trim();
  content = content.replace(/^```[\s\S]*?\n?/, '').replace(/```$/, '');
  return DOMPurify.sanitize(md.render(content));
});

const getQualitativeInfo = () => {
  return mainStore
    .getQualitative()
    .then((res) => {
      rawText.value = res.msg;
      autoFinish.value = true;
      setTimeout(() => {
        loading.value = false;
      }, 300);
    })
    .catch((err) => {
      fail.value = true;
    }).finally(async () => {
      mainStore.setIsLoadOver(true);
      await incrementCount();
    })
};

getQualitativeInfo();
</script>

<style lang="scss" scoped>
.ai-analysis {
  width: 100%;
  height: auto;
  padding: 40px;
  box-sizing: border-box;
  background-color: #ffffff;

  &-empty {
    width: 100%;
    height: 376px;
  }

  &-text {
    width: 100%;
    word-break: break-all;
    white-space: pre-wrap;
    overflow: hidden;
    font-weight: 400;
    font-size: 20px;
    color: #282e30;
  }
}
</style>
