<!-- AI生成内容展示的抽屉组件 -->

<script setup lang="ts">
import { message } from 'ant-design-vue';
import { ref } from 'vue';
import { useClipboard } from "@/libs/clipboard.lib";

const props = defineProps({
  content: {
    type: String,
    required: true
  }
})

const clipboard = useClipboard()

// 组件可见状态
const visible = ref<boolean>(false);

const emits = defineEmits<{
  (e: "insert", text: string): void;
  (e: "close"): void;
}>();

function getSelectedText() {
  if (window.getSelection) {
    const range = window.getSelection()
    return range?.toString()
  } else {
    message.warning("暂不支持此版本浏览器选择复制")
  }
  return null
}

/**
 * 清理文本当中的em标签
 * @param {string} text 文本
 * @returns {string} 清理后的文本
 */
function purnText(text: string): string {
  if (!text) {
    return text
  }
  const re = new RegExp("</?em>", "gi");
  return text.replace(re, '')
}

function onCopy() {
  const selectedText = getSelectedText()
  const text = purnText(selectedText || '')
  const msg = selectedText && "复制所选内容成功" || "复制内容成功"
  clipboard.copy(text).then(() => {
    message.success(msg)
  })
}

function onInsertion() {
  const text = purnText(getSelectedText() || props.content)
  emits("insert", text)
}

const onClose = () => {
  visible.value = false;
  emits("close")
};

const show = () => {
  visible.value = true;
};

defineExpose({
  show
});
</script>

<template>
  <a-drawer
    :width="'60%'"
    title="检索参考文献"
    placement="right"
    :visible="visible"
    @close="onClose"
    class="reference-drawer"
  >
    <h1>AI生成的参考内容</h1>
    <p>{{ content }}</p>
    <div class="btn-group">
      <a-radio-group>
        <a-radio-button value="default" @mousedown="onCopy">复制</a-radio-button>
        <a-radio-button value="small" @mousedown="onInsertion">插入</a-radio-button>
      </a-radio-group>
    </div>
  </a-drawer>
</template>

<style scoped lang="scss">
</style>
