<template>
    <div v-if="isInterveneMessage" class="intervene-message-container">
        <span v-if="interveneInfo.isFromSelf" class="text-span">{{ interveneText }}</span>
        <span v-else class="text-span">{{ interveneText }}</span>
        <span class="open-history" @click="openMessageList">{{ t('查看聊天记录') }}</span>
    </div>

    <div v-else class="message-merge-container" @click="openMessageList">
        <div class="message-merge-title">{{ titleText }}</div>
        <div class="message-merge-abstract-list">
            <div v-for="(item, index) in abstractItems" :key="`${item}-${index}`" class="message-merge-abstract-item">
                {{ item }}
            </div>
        </div>
        <div class="message-merge-footer">{{ t('聊天记录') }}</div>
    </div>

    <Teleport to="body">
        <div v-if="showMessageList" class="message-merge-dialog-mask" @click="closeMessageList">
            <div class="message-merge-dialog" @click.stop>
                <div class="message-merge-dialog-header">
                    <div class="message-merge-dialog-title">{{ dialogTitle }}</div>
                    <button class="message-merge-dialog-close" type="button" :aria-label="t('关闭聊天记录弹窗')"
                        @click="closeMessageList">
                        <img :src="closeMessageListIcon" alt="" class="message-merge-dialog-close-icon">
                    </button>
                </div>

                <div class="message-merge-dialog-content">
                    <SimpleMessageList :message-list="messageList" :current-user-id="currentUserId" />
                </div>
            </div>
        </div>
    </Teleport>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'

import closeMessageListIcon from './close.svg'
import SimpleMessageList from './SimpleMessageList.vue'
import { JSONToObject } from '@tencentcloud/ai-desk-core'

interface MergeMessageBodyItem {
    type?: unknown
    payload?: Record<string, unknown> | null
}

interface MergeMessageItem {
    avatar?: unknown
    ID?: unknown
    cloudCustomData?: unknown
    from?: unknown
    messageBody?: MergeMessageBodyItem[] | null
    nick?: unknown
    time?: unknown
}

interface NormalizedInterveneInfo {
    fromMemberUserID: string
    fromMemberNickName: string
    peerMemberUserID: string
    peerMemberNickName: string
    clientUserID: string
    clientUserNickName: string
    isFromSelf: boolean
}

interface Props {
    mergeContent: {
        title: string;
        abstractList: string[];
        messageList: Array<{
            avatar: string;
            ID: string;
            cloudCustomData: string;
            from: string;
            messageBody: Array<{
                type: string;
                payload: Record<string, any>;
            }>;
            nick: string;
            time: number;
        }>;
        cloudCustomData: string;
    };
    isInterveneMessage?: boolean
    currentUserId?: string
}

const props = withDefaults(defineProps<Props>(), {
    isInterveneMessage: false,
    currentUserId: '',
})

const { t } = useI18n()

const showMessageList = ref(false)

const safeToString = (input: unknown): string => {
    if (typeof input === 'string') {
        return input
    }

    if (typeof input === 'number' || typeof input === 'boolean') {
        return String(input)
    }

    return ''
}

const titleText = computed(() => {
    return safeToString(props.mergeContent?.title)
})

const abstractItems = computed<string[]>(() => {
    if (!Array.isArray(props.mergeContent?.abstractList)) {
        return []
    }

    return props.mergeContent.abstractList
        .map((item) => safeToString(item))
        .filter((item) => item !== '')
})

const messageList = computed<MergeMessageItem[]>(() => {
    if (!Array.isArray(props.mergeContent?.messageList)) {
        return []
    }

    return props.mergeContent.messageList
})

const interveneInfo = computed<NormalizedInterveneInfo>(() => {
    const parsedPayload = JSONToObject(props.mergeContent?.cloudCustomData)
    const relayUserInfo = parsedPayload?.relayUserInfo ?? {}
    const fromMemberUserID = safeToString(relayUserInfo.fromMemberUserID)

    return {
        fromMemberUserID,
        fromMemberNickName: safeToString(relayUserInfo.fromMemberNickName),
        peerMemberUserID: safeToString(relayUserInfo.peerMemberUserID),
        peerMemberNickName: safeToString(relayUserInfo.peerMemberNickName),
        clientUserID: safeToString(relayUserInfo.clientUserID),
        clientUserNickName: safeToString(relayUserInfo.clientUserNickName),
        isFromSelf: fromMemberUserID !== '' && fromMemberUserID === props.currentUserId,
    }
})

const peerDisplayName = computed(() => {
    return interveneInfo.value.peerMemberNickName || interveneInfo.value.peerMemberUserID || t('未知用户')
})

const clientDisplayName = computed(() => {
    return interveneInfo.value.clientUserNickName || interveneInfo.value.clientUserID || t('未知用户')
})

const fromDisplayName = computed(() => {
    return interveneInfo.value.fromMemberNickName || interveneInfo.value.fromMemberUserID || t('未知用户')
})

const interveneText = computed(() => {
    if (interveneInfo.value.isFromSelf) {
        return t('你查看了"{peer}"与"{client}"的会话，并发起了私聊', { peer: peerDisplayName.value, client: clientDisplayName.value })
    }

    return t('"{from}"查看了你与"{client}"的会话，并发起了私聊', { from: fromDisplayName.value, client: clientDisplayName.value })
})

const dialogTitle = computed(() => {
    if (props.isInterveneMessage) {
        return t('{peer}与{client}的聊天记录', { peer: peerDisplayName.value, client: clientDisplayName.value })
    }

    return titleText.value
})

const openMessageList = () => {
    showMessageList.value = true
}

const closeMessageList = () => {
    showMessageList.value = false
}
</script>

<style scoped>
.message-merge-container {
    display: block;
    cursor: pointer;
    word-break: break-all;
    overflow-wrap: break-word;
}

.message-merge-title {
    font-size: 14px;
    line-height: 20px;
    color: #1f2329;
    font-weight: 500;
}

.message-merge-abstract-list {
    margin-top: 4px;
}

.message-merge-abstract-item {
    font-size: 14px;
    line-height: 20px;
    color: #4f566b;
}

.message-merge-footer {
    margin-top: 6px;
    font-size: 13px;
    line-height: 20px;
    color: #7a7f8c;
}

.intervene-message-container {
    display: flex;
    justify-content: center;
    color: #999;
    width: 100%;
    font-size: 12px;
    margin-bottom: 10px;
    word-break: break-all;
    padding: 0 20px;
    position: relative;
}

.text-span {
    position: relative;
    padding: 0 10px;
    z-index: 1;
}

.open-history {
    position: relative;
    padding-right: 10px;
    z-index: 1;
    color: #1c66e5;
    cursor: pointer;
}

.message-merge-dialog-mask {
    position: fixed;
    inset: 0;
    z-index: 1300;
    background: rgba(0, 0, 0, 0.45);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 24px;
    box-sizing: border-box;
}

.message-merge-dialog {
    width: min(960px, 100%);
    height: min(80vh, 900px);
    max-height: min(80vh, 900px);
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 16px 48px rgba(0, 0, 0, 0.18);
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.message-merge-dialog-header {
    position: relative;
    padding: 18px 56px 18px 24px;
    border-bottom: 1px solid #f0f0f0;
    flex-shrink: 0;
}

.message-merge-dialog-title {
    font-size: 18px;
    line-height: 26px;
    font-weight: 600;
    color: #1f2329;
    word-break: break-all;
}

.message-merge-dialog-close {
    position: absolute;
    right: 8px;
    top: 8px;
    border: none;
    background: transparent;
    padding: 8px;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
}

.message-merge-dialog-close:hover {
    background: #f5f7fa;
}

.message-merge-dialog-close-icon {
    width: 16px;
    height: 16px;
    display: block;
}

.message-merge-dialog-content {
    flex: 1 1 auto;
    min-height: 0;
    min-width: 0;
    padding: 0;
    background: #f5f7fa;
    display: flex;
}

@media (max-width: 768px) {
    .message-merge-dialog-mask {
        padding: 12px;
    }

    .message-merge-dialog {
        width: 100%;
        height: 88vh;
        max-height: 88vh;
    }

    .message-merge-dialog-header {
        padding-left: 16px;
        padding-right: 48px;
    }

    .message-merge-dialog-title {
        font-size: 16px;
        line-height: 24px;
    }
}
</style>
