<script setup lang="ts">
import type { IExecuteRawResponse } from '@/api'
import { computed } from 'vue'
import MarkdownIt from 'markdown-it'
import DOMPurify from 'dompurify'
import Iod from './Iod.vue'

const props = defineProps<{
  executePlans: IExecuteRawResponse[]
  nodeId?: string
  actionId?: string
}>()

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

function sanitize(str?: string) {
  if (!str) {
    return ''
  }
  const cleanStr = str.replace(/\\n/g, '\n').replace(/\n\s*\d+\./g, '\n$&')
  const html = md.render(cleanStr)
  return html
  // return DOMPurify.sanitize(html)
}

interface Data {
  Description: string
  Content: string
  LogNodeType: string
}
const data = computed<Data | null>(() => {
  for (const result of props.executePlans) {
    if (result.NodeId === props.nodeId) {
      //  LogNodeType 为 object直接渲染Content
      if (result.LogNodeType === 'object') {
        const data = {
          Description: props.nodeId,
          Content: sanitize(result.content),
          LogNodeType: result.LogNodeType
        }
        return data
      }

      if (!result.ActionHistory) {
        return null
      }

      for (const action of result.ActionHistory) {
        if (action.ID === props.actionId) {
          return {
            Description: action.Description,
            Content: sanitize(action.Action_Result),
            LogNodeType: result.LogNodeType
          }
        }
      }
    }
  }
  return null
})
</script>

<template>
  <div v-if="data" class="card-item w-full pl-[56px] pr-[41px]">
    <!-- 分割线 -->
    <div v-if="data.LogNodeType !== 'object'" class="h-[1px] w-full bg-[#494B51] my-[8px]"></div>
    <div
      v-if="data.Description"
      class="text-[16px] flex items-center gap-1 text-[var(--color-text-secondary)] mb-1"
    >
      {{ data.Description }}
      <Iod v-if="data.LogNodeType !== 'object'" />
    </div>
    <div
      class="rounded-[8px] p-[15px] text-[14px] bg-[var(--color-bg-result-detail)] text-[var(--color-text-detail)]"
    >
      <div
        class="markdown-content max-h-[240px] overflow-y-auto max-w-full"
        v-html="data.Content"
      ></div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.card-item + .card-item {
  margin-top: 10px;
}
.markdown-content {
  :deep(code) {
    display: block;
    width: 100px;
    max-width: 100%;
  }

  :deep(pre) {
    overflow-x: auto;
    max-width: 100%;
  }
}
</style>
