<template>
    <aside class="pc-user-info-panel">
        <div class="pc-user-info-panel__list">
            <div v-for="item in infoItems" :key="item.label" class="pc-user-info-panel__row">
                <div class="pc-user-info-panel__label">{{ item.label }}</div>
                <div class="pc-user-info-panel__value" :class="item.className">{{ item.value }}</div>
            </div>

            <div class="pc-user-info-panel__row pc-user-info-panel__row--remark">
                <div class="pc-user-info-panel__label">{{ t('用户备注') }}</div>
                <div class="pc-user-info-panel__remark-wrapper">
                    <input v-model="profileRemark" type="text" maxlength="200" class="pc-user-info-panel__remark-input"
                        :placeholder="t('暂无备注')" @blur="handleRemarkBlur" />
                    <span class="pc-user-info-panel__remark-count">{{ profileRemark.length }}/200</span>
                </div>
            </div>
        </div>
    </aside>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import AIDeskCoreInstance, {
    SESSION_TYPE,
    StoreName,
    type SessionTypeMap,
} from '@tencentcloud/ai-desk-core';
import { getLocalizedCountry, getLocalizedTimezone, getLocalizedUserLanguage } from '../../../../utils';

const { t } = useI18n();

const currentSession = ref<SessionTypeMap[SESSION_TYPE] | null>(null);
const profileRemark = ref('');
const chatWorkBenchShowUserIP = ref(0);
const userIPLocation = ref('-');

type CurrentSessionData = {
    sessionId: string;
    sessionType: '';
    sessionData: null;
} | {
    [T in SESSION_TYPE]: {
        sessionId: string;
        sessionType: T;
        sessionData: SessionTypeMap[T];
    }
}[SESSION_TYPE];

const formatUserIPLocation = (location?: { country?: string; province?: string }) => {
    return [location?.country, location?.province].filter(Boolean).join('') || '-';
};

const loadUserIPLocation = async () => {
    const sessionInfo = currentSession.value;

    if (chatWorkBenchShowUserIP.value !== 1 || !sessionInfo?.sessionId || !sessionInfo?.userClientIP) {
        userIPLocation.value = '-';
        return;
    }

    try {
        const location = sessionInfo.userClientIP
            ? await AIDeskCoreInstance.sessionService.getUserIPLocation({
                userClientIP: sessionInfo.userClientIP,
            })
            : await AIDeskCoreInstance.sessionService.getUserIPLocation({
                sessionId: sessionInfo.sessionId,
            });

        userIPLocation.value = formatUserIPLocation(location);
    } catch (error) {
        console.error(error);
        userIPLocation.value = '-';
    }
};

const onCurrentSessionUpdated = (session: CurrentSessionData) => {
    const sessionInfo = session.sessionData;
    currentSession.value = sessionInfo;

    if (sessionInfo?.type !== SESSION_TYPE.IM) {
        profileRemark.value = sessionInfo?.userMark || '';
        return;
    }

    profileRemark.value = sessionInfo.remark || '';
};

const handleRemarkBlur = () => {
    const sessionInfo = currentSession.value;

    if (!sessionInfo || sessionInfo.type !== SESSION_TYPE.IM || sessionInfo.sessionState !== 'inProgress') {
        return;
    }

    if (profileRemark.value === (sessionInfo.remark || '')) {
        return;
    }

    AIDeskCoreInstance.sessionService.setUserRemark({
        sessionId: sessionInfo.sessionId,
        remark: profileRemark.value,
    });
};

const onChatWorkBenchShowUserIPUpdated = (showUserIP: number) => {
    chatWorkBenchShowUserIP.value = showUserIP;

    if (showUserIP === 1) {
        loadUserIPLocation();
        return;
    }

    userIPLocation.value = '-';
};

const infoItems = computed(() => {
    const currentIMSession = currentSession.value?.type === SESSION_TYPE.IM
        ? currentSession.value
        : null;
    const baseItems: Array<{ label: string; value: string; className?: string }> = [
        {
            label: t('用户ID'),
            value: currentSession.value?.userId || '-',
        },
        {
            label: t('用户昵称'),
            value: currentSession.value?.nickname || '-',
        },
        {
            label: t('来源'),
            value: currentSession.value?.channelName || '-',
        },
        {
            label: t('用户语言'),
            value: currentSession.value?.language ? getLocalizedUserLanguage(currentSession.value.language) : '-',
        },
        {
            label: t('用户地区'),
            value: currentIMSession?.country ? getLocalizedCountry(currentIMSession.country) : '-',
        },
        {
            label: t('用户时区'),
            value: currentIMSession?.timezone ? getLocalizedTimezone(currentIMSession.timezone) : '-',
        },
        ...(chatWorkBenchShowUserIP.value === 1
            ? [{
                label: t('用户IP'),
                value: userIPLocation.value,
            }]
            : []),
    ];

    return baseItems;
});

onMounted(() => {
    AIDeskCoreInstance.coreStore.watch(StoreName.SESSION, {
        currentSession: onCurrentSessionUpdated,
    });
    AIDeskCoreInstance.coreStore.watch(StoreName.APP_SETTING, {
        chatWorkBenchShowUserIP: onChatWorkBenchShowUserIPUpdated,
    });
});

onUnmounted(() => {
    AIDeskCoreInstance.coreStore.unwatch(StoreName.SESSION, {
        currentSession: onCurrentSessionUpdated,
    });
    AIDeskCoreInstance.coreStore.unwatch(StoreName.APP_SETTING, {
        chatWorkBenchShowUserIP: onChatWorkBenchShowUserIPUpdated,
    });
});
</script>

<style scoped>
.pc-user-info-panel {
    width: 360px;
    flex-shrink: 0;
    padding: 8px 4px;
    background: #ffffff;
    border-left: 1px solid #f2f3f5;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    box-sizing: border-box;
}

.pc-user-info-panel__list {
    display: flex;
    flex-direction: column;
}

.pc-user-info-panel__row {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 10px 20px;
    min-height: 24px;
}

.pc-user-info-panel__label {
    width: 72px;
    flex-shrink: 0;
    font-size: 13px;
    color: rgb(153, 162, 178);
    line-height: 20px;
}

.pc-user-info-panel__value {
    flex: 1;
    min-width: 0;
    font-size: 13px;
    color: #1d2129;
    line-height: 20px;
    text-align: left;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.pc-user-info-panel__row--remark {
    align-items: center;
}

.pc-user-info-panel__remark-wrapper {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 0;
}

.pc-user-info-panel__remark-input {
    flex: 1;
    min-width: 0;
    border: none;
    outline: none;
    background: transparent;
    font-size: 13px;
    line-height: 20px;
    color: #1d2129;
    padding: 0;
}

.pc-user-info-panel__remark-input::placeholder {
    color: #c9cdd4;
}

.pc-user-info-panel__remark-count {
    font-size: 13px;
    color: #c9cdd4;
    flex-shrink: 0;
}
</style>
