@@ -403,6 +403,9 @@ class SiteService {
403403 const sites = await configService . getSites ( forceRefresh )
404404
405405 if ( sites && sites . length > 0 ) {
406+ // 保存当前站点信息用于智能切换
407+ const previousCurrentSite = this . currentSite
408+
406409 // 清空现有站点(保留本地添加的站点)
407410 const localSites = Array . from ( this . sites . values ( ) ) . filter ( site => site . isLocal )
408411 this . sites . clear ( )
@@ -419,6 +422,9 @@ class SiteService {
419422 this . sites . set ( siteInfo . key , siteInfo )
420423 } )
421424
425+ // 智能源切换逻辑
426+ this . handleSmartSiteSwitch ( previousCurrentSite )
427+
422428 this . saveSitesToStorage ( )
423429 console . log ( `从配置加载了 ${ sites . length } 个站点` )
424430
@@ -496,6 +502,70 @@ class SiteService {
496502 } ) )
497503 }
498504 }
505+
506+ /**
507+ * 智能站点切换处理
508+ * @param {object } previousCurrentSite - 之前的当前站点
509+ */
510+ handleSmartSiteSwitch ( previousCurrentSite ) {
511+ let needReload = false
512+
513+ if ( previousCurrentSite && previousCurrentSite . key ) {
514+ // 检查之前的当前站点是否还在新的站点列表中
515+ const siteStillExists = this . sites . has ( previousCurrentSite . key )
516+
517+ if ( siteStillExists ) {
518+ // 如果站点仍然存在,保持当前选择
519+ this . currentSite = this . sites . get ( previousCurrentSite . key )
520+ console . log ( '保持当前源:' , this . currentSite . name )
521+ } else {
522+ // 如果站点不存在,切换到第一个可用站点
523+ const availableSites = this . getAllSites ( )
524+ if ( availableSites . length > 0 ) {
525+ // 优先选择type为4的站点,如果没有则选择第一个
526+ const firstSite = availableSites . find ( site => site . type === 4 ) || availableSites [ 0 ]
527+ this . currentSite = firstSite
528+ needReload = true
529+ console . log ( '自动切换到新源:' , this . currentSite . name )
530+
531+ // 触发站点切换事件
532+ this . emitSiteChange ( this . currentSite )
533+ }
534+ }
535+ } else {
536+ // 如果之前没有当前站点,设置第一个可用站点
537+ const availableSites = this . getAllSites ( )
538+ if ( availableSites . length > 0 ) {
539+ const firstSite = availableSites . find ( site => site . type === 4 ) || availableSites [ 0 ]
540+ this . currentSite = firstSite
541+ needReload = true
542+ console . log ( '设置默认源:' , this . currentSite . name )
543+
544+ // 触发站点切换事件
545+ this . emitSiteChange ( this . currentSite )
546+ }
547+ }
548+
549+ // 如果需要重载,触发重载源事件
550+ if ( needReload ) {
551+ this . emitReloadSource ( )
552+ }
553+ }
554+
555+ /**
556+ * 触发重载源事件
557+ */
558+ emitReloadSource ( ) {
559+ if ( typeof window !== 'undefined' ) {
560+ window . dispatchEvent ( new CustomEvent ( 'reloadSource' , {
561+ detail : {
562+ site : this . currentSite ,
563+ timestamp : Date . now ( )
564+ }
565+ } ) )
566+ console . log ( '触发重载源事件' )
567+ }
568+ }
499569}
500570
501571// 创建单例实例
0 commit comments