<template>
    <div class="mcp-server-list"
        v-show="show">
        <div class="top">
            <div style="margin-left: 16px;align-items: center;display: flex;">
                <div class="icon">
                    <SvgIcon icon="mcp-switch" style="width: 16px; height: 16px;fill: var(--uosai-mcpserver-list-title-icon-color);"/>
                </div>
                <span style="margin-left: 8px" class="instruction">{{ store.loadTranslations['MCP Server'] }}</span>
            </div>
            <div style="margin-right: 7px;align-items: center;display: flex;">
                <div class="icon" style="width: 16px; height: 16px; cursor: pointer;display: flex;justify-content: center;" @click="$emit('close')">
                    <SvgIcon icon="mcp-list-close"/>
                </div>
            </div>
        </div>
        <custom-scrollbar class="mcpServerListScrollbar" id="promptListScroll" :autoHideDelay="2000" :thumbWidth="6" 
            :wrapperStyle="{ width: '100%', height: '100%' ,padding: '0px' }" :style="{ height: '100%' }">
            <div class="list-content">
                <div v-for="(item, index) in serverList" :key="index" class="list-item"
                    :class="{ active: item.checked, 'has-removable': item.removable }"
                    @click="handleItemClick(item)">
                    <div class="item-content">
                        <el-tooltip popper-class="uos-tooltip mcp-server-list-tooltip" effect="light" :show-arrow="false" :enterable="false"
                            :show-after="1000" :offset="2" :content="item.name">
                            <span class="item-name">{{ item.name }}</span>
                        </el-tooltip>
                        <div class="delete-btn" @click.stop="handleRemoveMcpSeverItem(item)" v-show="item.removable">
                            <SvgIcon icon="trash" style="width: 16px; height: 16px;"/>
                        </div>
                        <div class="checkbox-icon" v-show="item.checked">
                            <SvgIcon icon="checked" style="width: 16px; height: 16px;"/>
                        </div>
                    </div>
                </div>
                <div class="add-mcp-server-btn" v-show="store.IsInstallUOSAiAgent" @click="handleAddMcpServer">+ {{ store.loadTranslations['Add Server'] }}</div>
                <div class="uos-ai-agent-lost" v-show="!store.IsInstallUOSAiAgent">
                    <el-tooltip popper-class="uos-tooltip" effect="light" :show-arrow="false" :enterable="false"
                    :show-after="1000" :offset="2" :content="store.loadTranslations['MCP environment missing. Please install 【UOS AI Agent】']">
                        <span class="tip">
                            {{ store.loadTranslations['MCP environment missing. Please install 【UOS AI Agent】'] }}
                        </span>
                    </el-tooltip>
                    <div class="go-install" @click="installUOSAiAgent">
                        <span>{{ toInstallBtnText }}</span>
                        <SvgIcon icon="arrow_down"/>
                    </div>
                </div>
            </div>
        </custom-scrollbar>
    </div>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue'
import { useGlobalStore } from '@/store/global'
import SvgIcon from '@/components/svgIcon/svgIcon.vue'
import CustomScrollbar from 'custom-vue-scrollbar'
import { Qrequest } from "@/utils";
const { chatQWeb, updateActivityColor, updateTheme, updateFont, updateMainContentBackgroundColor} = useGlobalStore()

const store = useGlobalStore()
const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    mcpServerList: {
        type: Array,
        default: () => []
    }
})

const emit = defineEmits(['close','showAddMcpServerDialog', 'removeMcpSeverItem', 'mcpCheckChange'])

// 改为响应式数据而不是计算属性
const serverList = ref([])
// 跟踪之前的勾选状态，用于检测从无到有的变化
const previousCheckedCount = ref(0)

// 监听 props.mcpServerList 变化，同步更新 serverList
watch(() => props.mcpServerList, (newList) => {
    // 保持现有的 checked 状态
    const currentCheckedMap = new Map()
    serverList.value.forEach(item => {
        currentCheckedMap.set(item.name, item.checked)
    })
    
    // 更新 serverList，保持已选中的状态，并保留removable字段
    serverList.value = newList.map(serverObj => ({
        name: serverObj.name,
        removable: serverObj.removable,
        checked: currentCheckedMap.get(serverObj.name) || false
    }))
    
    // 更新之前的勾选数量
    previousCheckedCount.value = serverList.value.filter(server => server.checked).length

    store.updateMcpServerList(serverList.value.filter(server => server.checked))
}, { immediate: true })

// 监听store中MCP列表的变化，当store中的列表被清空时，同步清空组件中的勾选状态
watch(() => store.McpServerList, (newStoreList) => {
    if (newStoreList.length === 0) {
        // 当store中的MCP列表被清空时，清空所有勾选状态
        serverList.value.forEach(item => {
            item.checked = false
        })
        // 重置之前的勾选数量
        previousCheckedCount.value = 0
    }
}, { immediate: true })

const handleItemClick = (item) => {
    item.checked = !item.checked
    handleCheckChange(item)
}

const handleCheckChange = (item) => {
    store.updateMcpServerList(serverList.value.filter(server => server.checked))
    
    // 计算当前勾选的数量
    const currentCheckedCount = serverList.value.filter(server => server.checked).length
    
    // 只有当勾选状态从无到有时才发出信号
    if (previousCheckedCount.value === 0 && currentCheckedCount > 0) {
        emit('mcpCheckChange', true)
    }
    
    // 更新之前的勾选数量
    previousCheckedCount.value = currentCheckedCount
}

const handleAddMcpServer = () => {
    emit('showAddMcpServerDialog')
}

const handleRemoveMcpSeverItem = async (item) => {
    emit('removeMcpSeverItem', item)
}

const installUOSAiAgent = () => {
    Qrequest(chatQWeb.installUosAiAgent)
}

const toInstallBtnText = ref("")

// 监听翻译数据的变化
watch(() => store.loadTranslations, (newTranslations) => {
    if (newTranslations && Object.keys(newTranslations).length > 0) {
        toInstallBtnText.value = store.loadTranslations['Install Now >'].replace(' >', '')
    }
}, { immediate: true, deep: true })

</script>

<style lang="scss" scoped>
.mcp-server-list {
    border-radius: 8px 8px 0px 0px;
    font-family: var(--font-family);
    color: var(--uosai-color-prompt-item);
    background-color: var(--uosai-color-normal-bg);
    font-size: 1rem;
    font-weight: 500;
    overflow: hidden;
    padding-bottom: 10px;

    .top {
        display: flex;
        align-items: center;
        height: 30px;
        justify-content: space-between;

        .instruction {
            color: var(--uosai-color-assistantmenu-name);
        }

        .icon {
            display: flex;
            align-items: center;
            &:not(.disabled):hover {
                svg {
                    fill: var(--uosai-color-prompt-icon-hover);
                }
            }

            svg {
                fill: var(--uosai-color-prompt-icon);
                width: 16px;
                height: 16px;
            }
        }
    }

    .mcpServerListScrollbar {
        overflow-y: overlay;
        overflow-x: hidden;
        height: 100%;
        padding-right: 0px;
        
        .list-content {
            max-height: 140px;
            margin: 0 6px;

            .list-item {
                height: 30px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 0 10px;
                cursor: pointer;
                border-radius: 8px;
                transition: background-color 0.2s ease;

                &:hover {
                    background-color: var(--uosai-color-activeItem-bg);
                    
                    .item-content .delete-btn {
                        display: flex;
                    }

                    .item-content .checkbox-icon {
                        margin-left: 10px;
                    }
                }

                &:hover:not(.has-removable) {
                    .item-content .checkbox-icon {
                        margin-left: auto;
                    }
                }

                &.active {
                    // background-color: var(--uosai-color-activeItem-bg);
                }

                .item-content {
                    display: flex;
                    align-items: center;
                    flex: 1;
                    gap: 8px;
                    max-width: 100%;

                    .item-name {
                        color: var(--uosai-color-prompt-item);
                        flex: 1;
                        max-width: 70%;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }

                    .delete-btn {
                        display: none;
                        width: 16px;
                        height: 16px;
                        align-items: center;
                        justify-content: center;
                        cursor: pointer;
                        flex-shrink: 0;
                        z-index: 10;
                        margin-left: auto;

                        svg {
                            fill: var(--uosai-color-prompt-icon);
                            width: 16px;
                            height: 16px;
                        }

                        &:hover {
                            svg {
                                fill: var(--uosai-color-prompt-icon-hover);
                            }
                        }

                        &:active {
                            svg {
                                fill: var(--activityColor);
                            }
                        }
                    }

                    .checkbox-icon {
                        width: 16px;
                        height: 16px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        margin-left: auto;
                        flex-shrink: 0;

                        svg {
                            fill: var(--uosai-color-prompt-icon);
                        }
                    }
                }
            }

            .add-mcp-server-btn {
                height: 30px;
                display: flex;
                align-items: center;
                justify-content: left;
                padding: 0 10px;
                cursor: pointer;
                border-radius: 8px;
                transition: background-color 0.2s ease;

                &:hover {
                    background-color: var(--uosai-color-activeItem-bg);
                }
            }

            .uos-ai-agent-lost {
                height: 30px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 0 10px;
                cursor: pointer;
                border-radius: 8px;
                transition: background-color 0.2s ease;

                .tip {
                    width: 70%;
                    // 超出部分显示省略号
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }

                .go-install {
                    font-size: 1rem;
                    color: var(--activityColor);
                    display: flex;
                    align-items: center;
                    justify-content: left;
                    cursor: pointer;
                    
                    svg {
                        width: 9px;
                        height: 10px;
                        margin-left: 5px;
                        margin-top: 1px;
                        fill: var(--activityColor);
                        transform: rotate(-90deg);
                    }
                }
            }
        }
    }
}
</style> 