import { CommonModule } from '@angular/common'; import { Component } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'; import { firstValueFrom } from 'rxjs'; import { MSQParse } from '../../app/parse'; import { SaasPlatformService } from '../../app/core/services/saas-platform.service'; import { AsinSkuMappingService } from '../shared/services/asin-sku-mapping.service'; import { PermissionService } from '../shared/services/permission.service'; import { ProductDimensionService } from '../shared/services/product-dimension.service'; import { SharedDataCacheService } from '../shared/services/shared-data-cache.service'; @Component({ selector: 'app-login', standalone: true, imports: [CommonModule, ReactiveFormsModule], templateUrl: './login.component.html', styleUrls: ['./login.component.scss'], }) export class LoginComponent { loginForm: FormGroup; isLoading = false; errorMessage = ''; returnUrl = '/voc-insight/products'; constructor( private readonly fb: FormBuilder, private readonly router: Router, private readonly route: ActivatedRoute, private readonly platform: SaasPlatformService, private readonly permissionService: PermissionService, private readonly productDimensionService: ProductDimensionService, private readonly asinSkuMappingService: AsinSkuMappingService, private readonly sharedDataCache: SharedDataCacheService, ) { this.loginForm = this.fb.group({ username: ['', [Validators.required, Validators.minLength(2)]], password: ['', [Validators.required, Validators.minLength(6)]], }); this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || this.returnUrl; } async onSubmit(): Promise { if (!this.loginForm.valid) { this.loginForm.markAllAsTouched(); return; } this.isLoading = true; this.errorMessage = ''; const { username, password } = this.loginForm.value; try { await MSQParse.User.logIn(username, password); const context = await firstValueFrom(this.platform.context()); if (!context.workspaces.length) { await MSQParse.User.logOut(); throw new Error('当前账号尚未加入 VOC 工作区'); } this.clearPermissionCaches(); await this.router.navigateByUrl(this.returnUrl); } catch (error: unknown) { const message = error instanceof Error ? error.message : ''; console.error('Login request failed:', message); this.errorMessage = message || '登录失败,请检查账号和密码后重试'; } finally { this.isLoading = false; } } private clearPermissionCaches(): void { this.permissionService.clearCache(); this.productDimensionService.clearCache(); this.asinSkuMappingService.clearCache(); this.sharedDataCache.invalidateAll(); } }