<template>
    <t-dialog :visible="visible" :header="t('发起单人会话')" :footer="false" :close-on-overlay-click="false" width="480px"
        placement="center" destroy-on-close dialog-class-name="create-session-dialog-wrapper"
        @update:visible="handleVisibleUpdate">
        <div class="create-session-dialog">
            <div class="dialog-form-item dialog-form-item--radio">
                <t-radio-group v-model="contactType" :options="contactTypeOptions" @change="handleContactTypeChange" />
            </div>

            <template v-if="contactType === 'inner'">
                <div class="dialog-form-item">
                    <t-select v-model="innerContactUserId" :placeholder="t('请选择联系人')" :empty="innerSelectEmptyText"
                        :loading="innerContactsLoading" clearable
                        :popup-props="{ overlayClassName: 'create-session-inner-contact-popup' }"
                        @clear="handleInnerContactClear" @popup-visible-change="handleInnerSelectPopupChange">
                        <template #panelTopContent>
                            <div class="inner-contact-search">
                                <div class="inner-contact-search-box">
                                    <svg class="inner-contact-search-icon" viewBox="0 0 20 20" fill="none"
                                        xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                        <path
                                            d="M8.75 3.75a5 5 0 1 0 0 10 5 5 0 0 0 0-10Zm0-1.5a6.5 6.5 0 1 1 0 13 6.5 6.5 0 0 1 0-13Zm5.209 11.148 3.02 3.02a.75.75 0 1 1-1.06 1.061l-3.02-3.02a.75.75 0 0 1 1.06-1.06Z"
                                            fill="#86909C" />
                                    </svg>
                                    <input v-model="innerKeyword" class="inner-contact-search-input" type="text"
                                        :placeholder="t('搜索成员ID或名称')" autocomplete="off" />
                                </div>
                            </div>
                        </template>
                        <t-option v-for="contact in filteredInnerContacts" :key="contact.userId" :value="contact.userId"
                            :label="contact.name">
                            <div class="inner-contact-option">
                                <div class="inner-contact-avatar">
                                    <img v-if="contact.avatar" class="inner-contact-avatar-image" :src="contact.avatar"
                                        alt="" />
                                    <span v-else>{{ contact.name.slice(0, 1) }}</span>
                                </div>
                                <div class="inner-contact-text">
                                    <span class="inner-contact-name">{{ contact.name }}</span>
                                    <span class="inner-contact-id">（{{ contact.userId }}）</span>
                                </div>
                            </div>
                        </t-option>
                    </t-select>
                </div>
            </template>

            <template v-else>
                <div class="dialog-form-item">
                    <div class="dialog-form-label">{{ t('我的身份') }}</div>
                    <t-select v-model="myIdentity" :options="identityOptions" :placeholder="t('请选择')" :empty="t('暂无数据')"
                        clearable />
                </div>
                <div class="dialog-form-item">
                    <div class="dialog-form-label">{{ t('联系人') }}</div>
                    <t-select v-model="externalContactUserId" :placeholder="t('输入 UserID')"
                        :empty="externalSelectEmptyText" :loading="externalLoading" filterable :filter="() => true"
                        clearable :popup-props="{ overlayClassName: 'create-session-inner-contact-popup' }"
                        @search="handleExternalSearch" @clear="handleExternalContactClear"
                        @popup-visible-change="handleExternalSelectPopupChange">
                        <t-option v-for="contact in externalContacts" :key="contact.userId" :value="contact.userId"
                            :label="contact.name">
                            <div class="inner-contact-option">
                                <div class="inner-contact-text">
                                    <span class="inner-contact-name">{{ contact.name }}</span>
                                    <span class="inner-contact-id">（{{ contact.userId }}）</span>
                                </div>
                            </div>
                        </t-option>
                    </t-select>
                </div>
            </template>

            <div class="dialog-footer">
                <button type="button" class="dialog-button dialog-button--confirm"
                    :class="{ 'is-disabled': !canSubmit }" :disabled="!canSubmit" @click="handleConfirm">
                    {{ t('发起会话') }}
                </button>
            </div>
        </div>
    </t-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import debounce from 'lodash/debounce';
import AIDeskCoreInstance, { SESSION_TYPE, StoreName } from '@tencentcloud/ai-desk-core';
import toast from '../../../../utils/toast';
import { parseUnknownError } from '../../../../utils/parseUnknownError';

type ContactType = 'inner' | 'outer';

interface InnerContactItem {
    userId: string;
    name: string;
    avatar: string;
}

interface Props {
    visible: boolean;
}

const props = defineProps<Props>();
const emit = defineEmits<{
    (e: 'update:visible', value: boolean): void;
    (e: 'success', payload: { contactType: ContactType; userId: string }): void;
}>();

const skillGroupTypeMap = {
    IM: 1,
};

const { t } = useI18n();

const contactType = ref<ContactType>('inner');
const myIdentity = ref('');
const identityOptions = ref<{ label: string; value: string }[]>([]);
const imContactUserEnable = ref(false);

const innerContactUserId = ref('');
const innerContacts = ref<InnerContactItem[]>([]);
const innerContactsLoading = ref(false);
const innerContactsLoadError = ref('');
const innerKeyword = ref('');

const externalKeyword = ref('');
const externalContactUserId = ref('');
const externalContactName = ref('');
const externalContacts = ref<InnerContactItem[]>([]);
const externalLoading = ref(false);
const externalLoadError = ref('');

const contactTypeOptions = computed(() => [
    { value: 'inner', label: t('内部联系人') },
    { value: 'outer', label: t('外部联系人') },
]);

const normalizedInnerKeyword = computed(() => innerKeyword.value.trim().toLowerCase());

const filteredInnerContacts = computed(() => {
    if (!normalizedInnerKeyword.value) {
        return innerContacts.value;
    }
    return innerContacts.value.filter((item) => {
        return (
            item.name.toLowerCase().includes(normalizedInnerKeyword.value) ||
            item.userId.toLowerCase().includes(normalizedInnerKeyword.value)
        );
    });
});

const innerSelectEmptyText = computed(() => {
    if (innerContactsLoading.value) {
        return t('加载中...');
    }
    if (innerContactsLoadError.value) {
        return innerContactsLoadError.value;
    }
    return t('未找到匹配的客服信息');
});

const canSubmit = computed(() => {
    if (contactType.value === 'inner') {
        return innerContactUserId.value.trim().length > 0;
    }
    return externalContactUserId.value.trim().length > 0 && myIdentity.value.length > 0;
});

const normalizedExternalKeyword = computed(() => externalKeyword.value.trim());

const externalSelectEmptyText = computed(() => {
    if (!normalizedExternalKeyword.value) {
        return t('请输入 UserID 后搜索');
    }
    if (externalLoading.value) {
        return t('加载中...');
    }
    if (externalLoadError.value) {
        return externalLoadError.value;
    }
    return t('未找到匹配的联系人');
});

const onIMContactUserEnableUpdated = (value: boolean) => {
    imContactUserEnable.value = value;
};

const loadIdentityOptions = async () => {
    try {
        const result = await AIDeskCoreInstance.sessionService.getIMAgentList();
        identityOptions.value = result.map((item) => ({
            label: item.nickName || item.userId,
            value: item.userId,
        }));
    } catch (error) {
        console.error('getIMAgentList error', error);
        identityOptions.value = [];
    }
};

const loadInnerContacts = async () => {
    innerContactsLoading.value = true;
    innerContactsLoadError.value = '';

    try {
        const result = await AIDeskCoreInstance.sessionService.getStaffList({
            pageNum: 0,
            pageSize: 2000,
            isNeedStatus: true,
            skillGroupType: skillGroupTypeMap.IM,
        });

        innerContacts.value = result.staffList.map((staff) => ({
            userId: staff.userId,
            name: staff.nickName || staff.staffName || staff.userId,
            avatar: staff.avatar || '',
        }));
    } catch (error) {
        console.error('getStaffList error', error);
        innerContacts.value = [];
        innerContactsLoadError.value = t('获取客服列表失败');
    } finally {
        innerContactsLoading.value = false;
    }
};

const resetExternalContactState = () => {
    externalKeyword.value = '';
    externalContactUserId.value = '';
    externalContactName.value = '';
    externalContacts.value = [];
    externalLoading.value = false;
    externalLoadError.value = '';
    debouncedFetchExternalContacts.cancel();
};

const resetState = () => {
    contactType.value = 'inner';
    myIdentity.value = '';
    innerContactUserId.value = '';
    innerKeyword.value = '';
    resetExternalContactState();
};

const fetchExternalContacts = async () => {
    const userId = normalizedExternalKeyword.value;
    if (!userId) {
        externalContacts.value = [];
        externalLoading.value = false;
        externalLoadError.value = '';
        return;
    }

    externalLoading.value = true;
    externalLoadError.value = '';

    try {
        const result = await AIDeskCoreInstance.sessionService.getIMUserProfile([userId]);
        externalContacts.value = result.map((item) => ({
            userId: item.userId,
            name: item.nickName || item.userId,
            avatar: '',
        }));
    } catch (error) {
        console.error('getIMUserProfile error', error);
        externalContacts.value = [];
        externalLoadError.value = t('获取联系人失败');
    } finally {
        externalLoading.value = false;
    }
};

const debouncedFetchExternalContacts = debounce(fetchExternalContacts, 500);

const handleExternalSearch = (value: string) => {
    externalKeyword.value = value;

    if (!value.trim()) {
        debouncedFetchExternalContacts.cancel();
        externalContacts.value = [];
        externalLoading.value = false;
        externalLoadError.value = '';
        return;
    }

    debouncedFetchExternalContacts();
};

const handleExternalSelectPopupChange = (visible: boolean) => {
    if (!visible) {
        // 弹层关闭时不再重置输入内容，保留已选中联系人的展示
    }
};

const handleExternalContactClear = () => {
    externalContactUserId.value = '';
    externalContactName.value = '';
    externalKeyword.value = '';
    externalContacts.value = [];
    externalLoadError.value = '';
};

onMounted(() => {
    AIDeskCoreInstance.coreStore.watch(StoreName.APP_SETTING, {
        imContactUserEnable: onIMContactUserEnableUpdated,
    });
});

onUnmounted(() => {
    AIDeskCoreInstance.coreStore.unwatch(StoreName.APP_SETTING, {
        imContactUserEnable: onIMContactUserEnableUpdated,
    });
    debouncedFetchExternalContacts.cancel();
});

watch(
    () => props.visible,
    (val) => {
        if (val) {
            resetState();
        }
    },
);

const handleVisibleUpdate = (val: boolean) => {
    emit('update:visible', val);
};

const closeDialog = () => {
    emit('update:visible', false);
};

const handleContactTypeChange = (val: ContactType) => {
    if (val === 'outer') {
        if (!imContactUserEnable.value) {
            contactType.value = 'inner';
            console.warn(t('当前未开启外部联系人会话'));
            return;
        }
        loadIdentityOptions();
    }
    myIdentity.value = '';
    innerContactUserId.value = '';
    innerKeyword.value = '';
    resetExternalContactState();
};

const handleInnerSelectPopupChange = (visible: boolean) => {
    if (visible) {
        loadInnerContacts();
    } else {
        innerKeyword.value = '';
    }
};

const handleInnerContactClear = () => {
    innerContactUserId.value = '';
    innerKeyword.value = '';
};

const handleConfirm = () => {
    if (!canSubmit.value) {
        return;
    }

    if (contactType.value === 'inner') {
        const userId = innerContactUserId.value.trim();
        const contact = innerContacts.value.find((item) => item.userId === userId);
        const sessionName = contact?.name || userId;
        try {
            AIDeskCoreInstance.sessionService.startInnerSession(userId, sessionName);
            AIDeskCoreInstance.sessionService.switchSession({
                sessionId: `C2C${userId}`,
                sessionType: SESSION_TYPE.IM,
            });
            emit('success', { contactType: 'inner', userId });
            closeDialog();
        } catch (error) {
            console.error('startInnerSession error', error);
        }
        return;
    }

    const userId = externalContactUserId.value.trim();
    try {
        AIDeskCoreInstance.sessionService.followUpSession(userId, myIdentity.value);
        emit('success', { contactType: 'outer', userId });
        closeDialog();
    } catch (error) {
        console.error('followUpSession error', error);
        toast.error(parseUnknownError(error))
    }
};
</script>

<style scoped>
.create-session-dialog {
    padding: 4px 0 0;
}

.dialog-form-item {
    margin-bottom: 16px;
}

.dialog-form-item--radio {
    text-align: left;
}

.dialog-form-item--radio :deep(.t-radio-group) {
    justify-content: flex-start;
}

/* 压缩 tdesign 输入框与下拉框内部 padding，让控件变矮 */
.create-session-dialog :deep(.t-input) {
    padding-top: 6px;
    padding-bottom: 6px;
}

.create-session-dialog :deep(.t-input__inner) {
    padding-top: 0;
    padding-bottom: 0;
}

.dialog-form-label {
    margin-bottom: 8px;
    font-size: 14px;
    line-height: 20px;
    color: #1D2129;
    text-align: left;
}

.create-session-dialog :deep(.t-dialog__header),
.create-session-dialog :deep(.t-dialog__header-content) {
    text-align: left;
    justify-content: flex-start;
}

:global(.create-session-dialog-wrapper .t-dialog__header),
:global(.create-session-dialog-wrapper .t-dialog__header-content) {
    text-align: left;
    justify-content: flex-start;
}

.dialog-footer {
    display: flex;
    justify-content: center;
    margin-top: 24px;
}

.dialog-button {
    min-width: 200px;
    height: 40px;
    padding: 0 32px;
    border-radius: 999px;
    font-size: 14px;
    line-height: 20px;
    cursor: pointer;
    border: 1px solid transparent;
    transition: background 0.15s, color 0.15s, border-color 0.15s;
}

.dialog-button--confirm {
    background: #316EF5;
    color: #fff;
    border-color: #316EF5;
}

.dialog-button--confirm:hover {
    background: #2A5FDB;
    border-color: #2A5FDB;
}

.dialog-button--confirm.is-disabled {
    background: #A5A9B0;
    border-color: #A5A9B0;
    color: #fff;
    cursor: not-allowed;
}

.inner-contact-search {
    padding: 8px 8px 4px;
}

.inner-contact-search-box {
    display: flex;
    align-items: center;
    gap: 8px;
    height: 36px;
    padding: 0 14px;
    border-radius: 22px;
    background: #f2f3f5;
}

.inner-contact-search-icon {
    width: 16px;
    height: 16px;
    flex-shrink: 0;
}

.inner-contact-search-input {
    flex: 1;
    min-width: 0;
    border: none;
    outline: none;
    background: transparent;
    font-size: 14px;
    color: #1d2129;
}

.inner-contact-search-input::placeholder {
    color: #86909c;
}

.inner-contact-option {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 100%;
    min-width: 0;
}

/* 穿透 tdesign 下拉项容器：让每个客服选项之间有更充足的呼吸感 */
:global(.create-session-inner-contact-popup .t-select-option) {
    min-height: 44px;
    padding-top: 6px;
    padding-bottom: 6px;
    line-height: 1.4;
}

:global(.create-session-inner-contact-popup .t-select-option + .t-select-option) {
    margin-top: 2px;
}

.inner-contact-avatar {
    width: 28px;
    height: 28px;
    border-radius: 999px;
    background: #f0f2f7;
    color: #165dff;
    font-size: 14px;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    overflow: hidden;
}

.inner-contact-avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.inner-contact-text {
    flex: 1;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.inner-contact-name {
    font-size: 14px;
    line-height: 22px;
    color: #1d2129;
}

.inner-contact-id {
    margin-left: 2px;
    font-size: 12px;
    line-height: 20px;
    color: #86909c;
}
</style>
