import { Component, signal, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router, RouterOutlet, RouterLinkActive, RouterLink } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { WxworkAuth } from "fmode-ng/core";
@Component({
  selector: 'app-customer-service-layout',
  standalone: true,
  imports: [CommonModule, RouterOutlet, RouterLink, RouterLinkActive, FormsModule],
  templateUrl: './customer-service-layout.html',
  styleUrl: './customer-service-layout.scss'
}) 
export class CustomerServiceLayout implements OnInit, OnDestroy {
  sidebarOpen = true;
  searchTerm = '';
  currentDate = new Date();
  
  // 通知相关状态
  notifications = signal<string[]>([
    '客户张三提交了新的咨询请求',
    '项目A设计方案已完成审核',
    '紧急任务需要处理：客户李四的修改需求'
  ]);
  showNotifications = signal(false);

  constructor(private router: Router) {
    this.loadProfile();
  }

  ngOnInit() {
    // 监听来自iframe的消息
    window.addEventListener('message', this.handleIframeMessage.bind(this));
  }
  currentUser:any = {}
  async loadProfile(){
      let cid = localStorage.getItem("company");
      if(cid){
        let wwAuth = new WxworkAuth({cid:cid})
        let profile = await wwAuth.currentProfile();
        this.currentUser  = {
          name: profile?.get("name") || profile?.get("mobile"),
          avatar: profile?.get("avatar"),
          roleName: profile?.get("roleName")
        }
      }
    }

  ngOnDestroy() {
    // 清理事件监听器
    window.removeEventListener('message', this.handleIframeMessage.bind(this));
  }

  // 处理来自iframe的消息
  private handleIframeMessage(event: MessageEvent) {
    // 验证消息来源（可以根据需要添加更严格的验证）
    if (event.origin !== window.location.origin) {
      return;
    }

    // 处理导航消息
    if (event.data && event.data.type === 'navigate') {
      const { url } = event.data;
      console.log('收到iframe导航请求:', url);
      this.router.navigateByUrl(url);
    }
  }

  toggleSidebar() {
    this.sidebarOpen = !this.sidebarOpen;
  }

  // 切换消息通知显示状态
  toggleNotifications() {
    this.showNotifications.set(!this.showNotifications());
  }

  // 退出登录功能
  logout() {
    // 在实际应用中，这里会清除用户会话、token等
    console.log('用户退出登录');
    // 重定向到登录页面
    this.router.navigate(['/login']);
  }

  // 处理全局搜索
  handleSearch() {
    console.log('执行全局搜索:', this.searchTerm);
    // 在实际应用中，这里会执行搜索逻辑
  }
}