<script setup>
const props = defineProps({
  messageContent: String | Number, // 消息内容
  viewType: Number, // 0发送 1接收
});


let linkInfo = ref(null) // hostname、mainParts、isInStation、url
const IN_STATION_LINK = []// 站内链接
const findHyperlinks = (text) => {
  try {
    const urlPattern = /https?:\/\/[^\s]+/g;
    if (!text.match(urlPattern)) return null
    const maybeUrl = text.match(urlPattern)[0];
    const url = new URL(maybeUrl);
    let hostname = url.hostname;
    const mainParts = hostname.split('.').slice(-2).join('.');
    return {
      mainParts,
      hostname: hostname,
      isInStation: IN_STATION_LINK.includes(hostname),
      url: maybeUrl
    }
  } catch (e) {
    return null
  }
}
const initMessage = () => {
  try {
    linkInfo.value = findHyperlinks(props.messageContent) ?? null;
  } catch (e) {
    console.error(e, 'initMessage')
  }
}
onMounted(() => {
  initMessage()
})
</script>

<template>
  <div class="link-message" :class="viewType ? 'link-message--accept' : 'link-message--send'">
    <div class="link-message__content">
      <div>
        {{ messageContent }}
      </div>
      <template v-if="linkInfo">
        <NuxtLink :to="linkInfo.url" target="_blank" class="bg-[#FFF] p-12 rounded-[4px] mt-12 flex flex-row">
          <div class="flex-1 min-w-0 mr-10">
            <div class="text-black-3 text-base text-ellipsis text-nowrap overflow-hidden ...">
              {{linkInfo.mainParts}}
            </div>
            <div class="text-black-9 text-sm text-ellipsis text-nowrap overflow-hidden ...">
              {{linkInfo.hostname}}
            </div>
          </div>
          <div class="ml-auto w-40 h-40 rounded-2 bg-[#F1F1F1] grid place-items-center">
            <img src="../../../../assets/img/chat/link-icon.png" height="24" width="25" alt=""/>
          </div>
        </NuxtLink>
      </template>
    </div>
    <div class="bg-[#F3F3F3] rounded-[25px] px-12 py-4 text-black-9 mt-4 text-sm w-max grid place-items-center">转自 第三方链接</div>
  </div>
</template>

<style scoped lang="scss">
.link-message {
  .link-message__content {
    max-width: 250px;
    padding: 12px;
    box-sizing: border-box;
    background: #F3F3F3;
    color: #000000;
    color: rgba(0, 0, 0, 0.9);
    font-size: 14px;
    word-wrap: break-word;
    word-break: break-all;
  }

  &.link-message--accept {
    .link-message__content {
      background: #F3F3F3;
      border-radius: 0 12px 12px 12px;
    }
  }

  &.link-message--send {
    .link-message__content {
      background: #FEF4E6;
      border-radius: 12px 0 12px 12px;
    }
  }


}
</style>