<template>
    <div class="pc-top-bar">
        <div class="top-bar-left"></div>

        <t-popup v-model="visible" placement="bottom-right" trigger="click" overlay-class-name="pc-user-menu-popup"
            :overlay-inner-style="popupOverlayStyle" :on-visible-change="handleVisibleChange">
            <div class="top-bar-right">
                <div class="avatar">
                    <img v-if="staffAvatar" class="avatar-image" :src="staffAvatar" alt="" />
                    <svg v-else class="avatar-icon" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"
                        aria-hidden="true">
                        <path fill="#fff"
                            d="M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm0 2c-3.3 0-8 1.7-8 5v1a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-1c0-3.3-4.7-5-8-5Z" />
                    </svg>
                    <span class="avatar-status-dot" :style="{ background: currentStatusColor }"></span>
                </div>
                <span class="user-name">{{ displayName }}</span>
                <svg class="user-arrow" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg"
                    aria-hidden="true">
                    <path d="M2.5 4.5 6 8l3.5-3.5" stroke="#fff" stroke-width="1.4" stroke-linecap="round"
                        stroke-linejoin="round" />
                </svg>
            </div>

            <template #content>
                <div class="user-menu">
                    <div class="user-menu__profile">
                        <div class="user-menu__profile-name">{{ userId || '--' }}</div>
                        <div class="user-menu__profile-nick">{{ t('昵称') }}：{{ staffName || '--' }}</div>
                    </div>

                    <div class="user-menu__section">
                        <button v-for="option in statusOptions" :key="option.key" type="button"
                            class="user-menu__status-item" :class="{ 'is-selected': option.selected }"
                            @click="handleStatusSelect(option)">
                            <span class="status-dot" :style="{ background: option.color }"></span>
                            <span class="status-label" :style="{ color: option.selected ? option.color : '#1D2129' }">
                                {{ option.label }}
                            </span>
                            <svg v-if="option.showArrow" class="status-arrow" viewBox="0 0 12 12" fill="none"
                                xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                <path d="M2.5 4.5 6 8l3.5-3.5" stroke="#86909C" stroke-width="1.4"
                                    stroke-linecap="round" stroke-linejoin="round" />
                            </svg>
                        </button>
                    </div>

                    <div v-if="isConnected && restReasonOptions.length > 0"
                        class="user-menu__section user-menu__section--reasons">
                        <button v-for="reasonItem in restReasonOptions" :key="reasonItem.name" type="button"
                            class="user-menu__reason-item"
                            :class="{ 'is-selected': isRestReasonSelected(reasonItem.name) }"
                            @click="handleRestReasonSelect(reasonItem.name)">
                            <span class="reason-label">{{ reasonItem.name }}</span>
                        </button>
                    </div>

                    <div v-if="isConnected" class="user-menu__section user-menu__section--offline">
                        <button type="button" class="user-menu__status-item"
                            :class="{ 'is-selected': status === 'offline' }" @click="handleOfflineClick">
                            <span class="status-dot" style="background:#A5A9B0"></span>
                            <span class="status-label"
                                :style="{ color: status === 'offline' ? '#A5A9B0' : '#1D2129' }">{{ t('下线') }}</span>
                        </button>
                    </div>

                    <div class="user-menu__section user-menu__section--logout">
                        <button type="button" class="user-menu__logout" @click="handleLogoutClick">
                            {{ t('退出登录') }}
                        </button>
                    </div>
                </div>
            </template>
        </t-popup>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import AIDeskCoreInstance, { StoreName } from '@tencentcloud/ai-desk-core';

type StatusOption = {
    key: string;
    value: 'free' | 'notReady' | 'rest' | 'offline';
    label: string;
    color: string;
    selected: boolean;
    showArrow?: boolean;
};

type RestReasonItem = {
    name: string;
    state: string;
};

type ConnectionState = 'disconnected' | 'connected' | 'connecting' | 'reconnecting';
type UserStatus = 'offline' | 'free' | 'busy' | 'rest' | 'countdown' | 'arrange' | 'notReady';
type LogicStatus = 'ready' | 'notReady' | 'rest' | 'afterCallWork' | 'offline' | '';

const router = useRouter();
const { t } = useI18n();

const visible = ref(false);
const status = ref<UserStatus>('offline');
const logicStatus = ref<LogicStatus>('');
const reason = ref<string>('');
const staffAvatar = ref<string>('');
const staffName = ref<string>('');
const userId = ref<string>('');
const connectionState = ref<ConnectionState>('disconnected');
const restReasonList = ref<RestReasonItem[]>([]);

const popupOverlayStyle = {
    padding: 0,
    background: '#fff',
    borderRadius: '10px',
    border: 'none',
    boxShadow: '0 6px 24px rgba(0, 0, 0, 0.12)',
    overflow: 'hidden',
};

onMounted(() => {
    AIDeskCoreInstance.coreStore.watch(StoreName.USERINFO, {
        status: onStatusUpdated,
        logicStatus: onLogicStatusUpdated,
        reason: onReasonUpdated,
        staffAvatar: onStaffAvatarUpdated,
        nickname: onStaffNameUpdated,
        userId: onUserIdUpdated,
        connectionState: onConnectionStateUpdated,
    });
    AIDeskCoreInstance.coreStore.watch(StoreName.APP_SETTING, {
        restReasonList: onRestReasonListUpdated,
    });
});

onUnmounted(() => {
    AIDeskCoreInstance.coreStore.unwatch(StoreName.USERINFO, {
        status: onStatusUpdated,
        logicStatus: onLogicStatusUpdated,
        reason: onReasonUpdated,
        staffAvatar: onStaffAvatarUpdated,
        nickname: onStaffNameUpdated,
        userId: onUserIdUpdated,
        connectionState: onConnectionStateUpdated,
    });
    AIDeskCoreInstance.coreStore.unwatch(StoreName.APP_SETTING, {
        restReasonList: onRestReasonListUpdated,
    });
});

const onStatusUpdated = (newStatus: UserStatus) => {
    status.value = newStatus ?? 'offline';
};

const onLogicStatusUpdated = (newLogicStatus: LogicStatus) => {
    logicStatus.value = newLogicStatus ?? '';
};

const onReasonUpdated = (newReason: string) => {
    reason.value = newReason ?? '';
};

const onStaffAvatarUpdated = (newAvatar: string) => {
    staffAvatar.value = newAvatar ?? '';
};

const onStaffNameUpdated = (newName: string) => {
    staffName.value = newName ?? '';
};

const onUserIdUpdated = (newUserId: string) => {
    userId.value = newUserId ?? '';
};

const onConnectionStateUpdated = (newConnectionState: ConnectionState) => {
    connectionState.value = newConnectionState ?? 'disconnected';
};

const onRestReasonListUpdated = (newList: RestReasonItem[]) => {
    restReasonList.value = Array.isArray(newList) ? newList : [];
};

const enabledRestReasonList = computed(() => {
    return restReasonList.value.filter((item) => item.state === '1');
});

const isConnected = computed(() => connectionState.value === 'connected');

const isFreeSelected = computed(() => {
    return status.value === 'free' && logicStatus.value === 'ready';
});

const isNotReadySelected = computed(() => {
    return status.value === 'busy'
        ? logicStatus.value === 'notReady'
        : status.value === 'notReady';
});

const isRestSelected = computed(() => {
    return status.value === 'busy'
        ? logicStatus.value === 'rest'
        : status.value === 'rest';
});

const hasMatchedRestReason = computed(() => {
    if (!isRestSelected.value) {
        return false;
    }
    if (!reason.value) {
        return false;
    }
    return enabledRestReasonList.value.some((item) => item.name === reason.value);
});

const statusOptions = computed<StatusOption[]>(() => {
    if (connectionState.value === 'connected') {
        return [
            {
                key: 'free',
                value: 'free',
                label: t('示闲'),
                color: '#00B42A',
                selected: isFreeSelected.value,
            },
            {
                key: 'notReady',
                value: 'notReady',
                label: t('示忙'),
                color: '#E54545',
                selected: isNotReadySelected.value,
            },
            {
                key: 'rest',
                value: 'rest',
                label: t('小休'),
                color: '#FF7D00',
                selected: isRestSelected.value && !hasMatchedRestReason.value,
                showArrow: enabledRestReasonList.value.length > 0,
            },
        ];
    }

    if (connectionState.value === 'disconnected') {
        return [
            {
                key: 'online',
                value: 'free',
                label: t('上线'),
                color: '#00B42A',
                selected: false,
            },
        ];
    }

    return [];
});

const restReasonOptions = computed(() => {
    return enabledRestReasonList.value;
});

const displayName = computed(() => {
    return staffName.value || userId.value || '--';
});

const currentStatusColor = computed(() => {
    if (connectionState.value !== 'connected') {
        return '#A5A9B0';
    }
    if (isFreeSelected.value) {
        return '#00B42A';
    }
    if (isNotReadySelected.value) {
        return '#E54545';
    }
    if (isRestSelected.value) {
        return '#FF7D00';
    }
    if (status.value === 'offline') {
        return '#A5A9B0';
    }
    return '#A5A9B0';
});

const handleVisibleChange = (val: boolean) => {
    visible.value = val;
};

const handleSetStatus = (nextStatus: 'offline' | 'free' | 'rest' | 'notReady', restReason?: string) => {
    AIDeskCoreInstance.userInfoService.setStatus({
        status: nextStatus,
        restReason,
    });
};

const handleStatusSelect = (selectedStatus: StatusOption) => {
    if (selectedStatus.value === 'rest') {
        if (enabledRestReasonList.value.length > 0) {
            return;
        }
        handleSetStatus('rest');
        visible.value = false;
        return;
    }

    if (selectedStatus.key === 'online') {
        AIDeskCoreInstance.userInfoService.online();
        visible.value = false;
        return;
    }

    handleSetStatus(selectedStatus.value);
    visible.value = false;
};

const handleOfflineClick = () => {
    AIDeskCoreInstance.userInfoService.offline();
    visible.value = false;
};

const handleRestReasonSelect = (restReason: string) => {
    handleSetStatus('rest', restReason);
    visible.value = false;
};

const isRestReasonSelected = (restReasonName: string) => {
    return isRestSelected.value && reason.value === restReasonName;
};

const handleLogoutClick = () => {
    visible.value = false;
    router.replace('/login').then(() => {
        AIDeskCoreInstance.destroy();
    });
};
</script>

<style scoped>
.pc-top-bar {
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24px;
    background: #316EF5;
    color: #fff;
    flex-shrink: 0;
}

.top-bar-left {
    display: flex;
    align-items: center;
}

.top-bar-right {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    padding: 4px 8px;
    border-radius: 4px;
    transition: background 0.2s;
}

.top-bar-right:hover {
    background: rgba(255, 255, 255, 0.12);
}

.avatar {
    position: relative;
    width: 28px;
    height: 28px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: visible;
}

.avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 50%;
}

.avatar-status-dot {
    position: absolute;
    right: -4px;
    bottom: -4px;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    border: 1.5px solid #316EF5;
    box-sizing: content-box;
}

.avatar-icon {
    width: 20px;
    height: 20px;
}

.user-name {
    font-size: 14px;
    max-width: 160px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.user-arrow {
    width: 12px;
    height: 12px;
}

.user-menu {
    width: 240px;
    background: #fff;
    padding: 8px;
    border-radius: 10px;
    box-sizing: border-box;
}

.user-menu__profile {
    padding: 12px 12px 12px;
    border-bottom: 1px solid #f2f3f5;
}

.user-menu__profile-name {
    font-size: 15px;
    font-weight: 500;
    color: #1D2129;
    line-height: 22px;
}

.user-menu__profile-nick {
    margin-top: 6px;
    font-size: 12px;
    color: #86909C;
    line-height: 18px;
}

.user-menu__section {
    padding: 6px 0;
    border-bottom: 1px solid #f2f3f5;
}

.user-menu__section:last-child {
    border-bottom: none;
}

.user-menu__section--reasons {
    padding: 2px 0 8px;
}

.user-menu__status-item {
    width: 100%;
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 12px;
    background: transparent;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    text-align: left;
    transition: background 0.15s;
}

.user-menu__status-item:hover {
    background: #f7f8fa;
}

.user-menu__status-item.is-selected {
    background: #F2F6FF;
}

.status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    flex-shrink: 0;
}

.status-label {
    flex: 1;
    font-size: 14px;
    line-height: 20px;
}

.status-arrow {
    width: 12px;
    height: 12px;
}

.user-menu__reason-item {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px 8px 32px;
    background: transparent;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    text-align: left;
    transition: background 0.15s;
}

.user-menu__reason-item:hover {
    background: #f7f8fa;
}

.user-menu__reason-item.is-selected {
    background: #F2F6FF;
}

.user-menu__reason-item.is-selected .reason-label {
    color: #316EF5;
}

.reason-label {
    font-size: 13px;
    color: #4E5969;
    line-height: 20px;
}

.user-menu__logout {
    width: 100%;
    padding: 10px 12px;
    background: transparent;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    color: #1D2129;
    text-align: left;
    line-height: 20px;
    transition: background 0.15s;
}

.user-menu__logout:hover {
    background: #f7f8fa;
}
</style>
