import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { DesignerCalendarComponent } from '../../../../customer-service/consultation-order/components/designer-calendar/designer-calendar.component';
import { Designer as CalendarDesigner } from '../../../../customer-service/consultation-order/components/designer-calendar/designer-calendar.component';

export interface Designer {
  id: string;
  name: string;
  avatar?: string;
  teamId: string;
  teamName: string;
  isTeamLeader: boolean;
  status: 'idle' | 'busy' | 'reviewing' | 'stagnant';
  idleDays: number;
  recentOrders: number;
  lastOrderDate?: string;
  reviewDates: string[]; // 对图日期，这些日期不能安排其他工作
  workload: number; // 当前工作量 (0-100)
  skills: string[];
  isInStagnantProject: boolean; // 是否处于停滞期项目
  availableDates: string[]; // 空闲日期
  // 为了兼容designer-calendar组件，添加以下属性
  groupId: string; // 对应teamId
  groupName: string; // 对应teamName
  isLeader: boolean; // 对应isTeamLeader
  currentProjects: number; // 当前项目数量
}

export interface ProjectTeam {
  id: string;
  name: string;
  leaderId: string;
  leaderName: string;
  members: Designer[];
  description?: string;
}

export interface DesignerAssignmentResult {
  selectedDesigners: Designer[];
  primaryTeamId: string;
  crossTeamCollaborators: Designer[];
  quotationAssignments: any[];
}

@Component({
  selector: 'app-designer-team-assignment-modal',
  standalone: true,
  imports: [CommonModule, FormsModule, DesignerCalendarComponent],
  templateUrl: './designer-team-assignment-modal.component.html',
  styleUrls: ['./designer-team-assignment-modal.component.scss']
})
export class DesignerTeamAssignmentModalComponent implements OnInit {
  @Input() isVisible = false;
  @Input() visible = false; // 添加visible属性以兼容父组件
  @Input() quotationItems: any[] = [];
  @Input() projectTeams: ProjectTeam[] = []; // 添加projectTeams输入属性
  @Input() selectedTeamId: string = ''; // 添加selectedTeamId输入属性
  @Input() selectedDesigners: any[] = []; // 添加selectedDesigners输入属性
  @Input() crossTeamCollaborators: any[] = []; // 添加crossTeamCollaborators输入属性
  @Output() close = new EventEmitter<void>();
  @Output() confirm = new EventEmitter<DesignerAssignmentResult>();

  // 项目组数据（作为默认数据，如果没有通过@Input传入）
  defaultProjectTeams: ProjectTeam[] = [
    {
      id: 'team-1',
      name: '家装设计组',
      leaderId: 'designer-1',
      leaderName: '张组长',
      description: '专注于家庭装修设计，包括客厅、卧室、厨房等空间设计',
      members: [
        {
          id: 'designer-1',
          name: '张组长',
          avatar: '/assets/images/avatars/zhang.jpg',
          teamId: 'team-1',
          teamName: '家装设计组',
          isTeamLeader: true,
          status: 'busy',
          idleDays: 0,
          recentOrders: 3,
          lastOrderDate: '2024-01-15',
          reviewDates: ['2024-01-20', '2024-01-25'],
          workload: 85,
          skills: ['家装设计', '软装搭配', '项目管理'],
          isInStagnantProject: false,
          availableDates: [],
          groupId: 'team-1',
          groupName: '家装设计组',
          isLeader: true,
          currentProjects: 3
        },
        {
          id: 'designer-2',
          name: '李设计师',
          avatar: '/assets/images/avatars/li.jpg',
          teamId: 'team-1',
          teamName: '家装设计组',
          isTeamLeader: false,
          status: 'idle',
          idleDays: 5,
          recentOrders: 1,
          lastOrderDate: '2024-01-10',
          reviewDates: [],
          workload: 30,
          skills: ['家装设计', '3D建模'],
          isInStagnantProject: false,
          availableDates: ['2024-01-18', '2024-01-19', '2024-01-20'],
          groupId: 'team-1',
          groupName: '家装设计组',
          isLeader: false,
          currentProjects: 1
        },
        {
          id: 'designer-3',
          name: '王设计师',
          avatar: '/assets/images/avatars/wang.jpg',
          teamId: 'team-1',
          teamName: '家装设计组',
          isTeamLeader: false,
          status: 'idle',
          idleDays: 15,
          recentOrders: 0,
          lastOrderDate: '2024-01-01',
          reviewDates: [],
          workload: 10,
          skills: ['家装设计', '效果图制作'],
          isInStagnantProject: false,
          availableDates: ['2024-01-16', '2024-01-17', '2024-01-18', '2024-01-19', '2024-01-20'],
          groupId: 'team-1',
          groupName: '家装设计组',
          isLeader: false,
          currentProjects: 0
        }
      ]
    },
    {
      id: 'team-2',
      name: '工装设计组',
      leaderId: 'designer-4',
      leaderName: '赵组长',
      description: '专注于商业空间设计，包括办公室、商铺、餐厅等',
      members: [
        {
          id: 'designer-4',
          name: '赵组长',
          avatar: '/assets/images/avatars/zhao.jpg',
          teamId: 'team-2',
          teamName: '工装设计组',
          isTeamLeader: true,
          status: 'reviewing',
          idleDays: 0,
          recentOrders: 2,
          lastOrderDate: '2024-01-14',
          reviewDates: ['2024-01-18', '2024-01-22'],
          workload: 70,
          skills: ['工装设计', '商业空间', '项目管理'],
          isInStagnantProject: false,
          availableDates: ['2024-01-19', '2024-01-21'],
          groupId: 'team-2',
          groupName: '工装设计组',
          isLeader: true,
          currentProjects: 2
        },
        {
          id: 'designer-5',
          name: '孙设计师',
          avatar: '/assets/images/avatars/sun.jpg',
          teamId: 'team-2',
          teamName: '工装设计组',
          isTeamLeader: false,
          status: 'idle',
          idleDays: 12,
          recentOrders: 0,
          lastOrderDate: '2024-01-03',
          reviewDates: [],
          workload: 10,
          skills: ['工装设计', '效果图制作'],
          isInStagnantProject: false,
          availableDates: ['2024-01-16', '2024-01-17', '2024-01-18', '2024-01-19'],
          groupId: 'team-2',
          groupName: '工装设计组',
          isLeader: false,
          currentProjects: 0
        }
      ]
    },
    {
      id: 'team-3',
      name: '软装设计组',
      leaderId: 'designer-6',
      leaderName: '周组长',
      description: '专注于软装搭配设计，包括家具、饰品、色彩搭配等',
      members: [
        {
          id: 'designer-6',
          name: '周组长',
          avatar: '/assets/images/avatars/zhou.jpg',
          teamId: 'team-3',
          teamName: '软装设计组',
          isTeamLeader: true,
          status: 'idle',
          idleDays: 3,
          recentOrders: 1,
          lastOrderDate: '2024-01-12',
          reviewDates: [],
          workload: 40,
          skills: ['软装设计', '色彩搭配', '家具选配'],
          isInStagnantProject: false,
          availableDates: ['2024-01-17', '2024-01-18', '2024-01-19'],
          groupId: 'team-3',
          groupName: '软装设计组',
          isLeader: true,
          currentProjects: 1
        }
      ]
    }
  ];

  // 内部状态变量
  internalSelectedTeamId: string = '';
  internalSelectedDesigners: Designer[] = [];
  internalCrossTeamCollaborators: Designer[] = [];
  showDesignerCalendar = false;
  selectedDesignerForCalendar: Designer | null = null;
  // 为日历组件准备的设计师数据（转换成客户服务模块的 Designer 类型）
  selectedCalendarDesigners: CalendarDesigner[] = [];
  allowCrossTeamSelection = true;

  constructor() {}

  ngOnInit() {
    // 如果没有传入projectTeams，使用默认数据
    if (this.projectTeams.length === 0) {
      this.projectTeams = [...this.defaultProjectTeams];
    }
    
    // 初始化内部状态
    this.internalSelectedTeamId = this.selectedTeamId;
    
    // 过滤掉处于停滞期项目的设计师
    this.filterStagnantDesigners();
  }

  // 过滤停滞期项目的设计师
  filterStagnantDesigners() {
    this.projectTeams.forEach(team => {
      team.members = team.members.filter(designer => !designer.isInStagnantProject);
    });
  }

  // 选择项目组
  selectTeam(teamId: string) {
    this.internalSelectedTeamId = teamId;
    this.internalSelectedDesigners = [];
    this.internalCrossTeamCollaborators = [];
  }

  // 获取选中的项目组
  getSelectedTeam(): ProjectTeam | undefined {
    return this.projectTeams.find(team => team.id === this.internalSelectedTeamId);
  }

  // 切换设计师选择
  toggleDesignerSelection(designer: Designer) {
    const index = this.internalSelectedDesigners.findIndex(d => d.id === designer.id);
    if (index > -1) {
      this.internalSelectedDesigners.splice(index, 1);
    } else {
      this.internalSelectedDesigners.push(designer);
    }
  }

  // 切换跨组合作设计师
  toggleCrossTeamCollaborator(designer: Designer) {
    const index = this.internalCrossTeamCollaborators.findIndex(d => d.id === designer.id);
    if (index > -1) {
      this.internalCrossTeamCollaborators.splice(index, 1);
    } else {
      this.internalCrossTeamCollaborators.push(designer);
    }
  }

  // 检查设计师是否被选中
  isDesignerSelected(designer: Designer): boolean {
    return this.internalSelectedDesigners.some(d => d.id === designer.id) ||
           this.internalCrossTeamCollaborators.some(d => d.id === designer.id);
  }

  // 获取设计师状态颜色
  getDesignerStatusColor(status: string): string {
    switch (status) {
      case 'idle': return '#52c41a';
      case 'busy': return '#faad14';
      case 'reviewing': return '#1890ff';
      case 'stagnant': return '#ff4d4f';
      default: return '#d9d9d9';
    }
  }

  // 获取设计师状态文本
  getDesignerStatusText(status: string): string {
    switch (status) {
      case 'idle': return '空闲';
      case 'busy': return '忙碌';
      case 'reviewing': return '对图中';
      case 'stagnant': return '停滞期';
      default: return '未知';
    }
  }

  // 获取工作量状态类
  getWorkloadClass(workload: number): string {
    if (workload < 30) return 'low';
    if (workload < 70) return 'medium';
    return 'high';
  }

  // 获取闲置天数状态类
  getIdleDaysClass(idleDays: number): string {
    if (idleDays === 0) return 'active';
    if (idleDays < 7) return 'recent';
    if (idleDays < 15) return 'moderate';
    return 'long';
  }

  // 显示设计师详细日历
  showDesignerDetailCalendar(designer: Designer) {
    this.selectedDesignerForCalendar = designer;
    // 转换为客户服务模块的 Designer 类型
    const calendarStatus: 'available' | 'busy' | 'stagnant' | 'overloaded' =
      designer.status === 'idle' ? 'available' :
      designer.status === 'stagnant' ? 'stagnant' : 'busy';

    this.selectedCalendarDesigners = [{
      id: designer.id,
      name: designer.name,
      avatar: designer.avatar,
      groupId: designer.groupId || designer.teamId,
      groupName: designer.groupName || designer.teamName,
      isLeader: designer.isLeader ?? designer.isTeamLeader,
      status: calendarStatus,
      currentProjects: designer.currentProjects ?? 0,
      lastOrderDate: designer.lastOrderDate,
      idleDays: designer.idleDays,
      workload: designer.workload,
      nextAvailableDate: designer.availableDates && designer.availableDates.length > 0
        ? new Date(designer.availableDates[0])
        : undefined
    }];
    this.showDesignerCalendar = true;
  }

  // 关闭设计师日历
  closeDesignerCalendar() {
    this.showDesignerCalendar = false;
    this.selectedDesignerForCalendar = null;
    this.selectedCalendarDesigners = [];
  }

  // 获取其他项目组的设计师
  getOtherTeamDesigners(): Designer[] {
    return this.projectTeams
      .filter(team => team.id !== this.internalSelectedTeamId)
      .flatMap(team => team.members);
  }

  // 获取推荐的设计师（长期闲置的优先）
  getRecommendedDesigners(): Designer[] {
    const selectedTeam = this.getSelectedTeam();
    if (!selectedTeam) return [];

    return selectedTeam.members
      .filter(designer => designer.status === 'idle')
      .sort((a, b) => b.idleDays - a.idleDays); // 按闲置天数降序排列
  }

  // 关闭弹窗
  closeModal() {
    this.close.emit();
  }

  // 确认分配
  confirmAssignment() {
    const result: DesignerAssignmentResult = {
      selectedDesigners: [...this.internalSelectedDesigners],
      primaryTeamId: this.internalSelectedTeamId,
      crossTeamCollaborators: [...this.internalCrossTeamCollaborators],
      quotationAssignments: [] // 这里可以根据需要生成报价分配
    };

    this.confirm.emit(result);
  }

  // 检查是否可以确认分配
  canConfirmAssignment(): boolean {
    return this.internalSelectedTeamId !== '' && 
           (this.internalSelectedDesigners.length > 0 || this.internalCrossTeamCollaborators.length > 0);
  }

  // 获取最近接单情况文本
  getRecentOrdersText(designer: Designer): string {
    if (designer.recentOrders === 0) {
      return `已闲置 ${designer.idleDays} 天`;
    } else {
      return `最近 30 天接了 ${designer.recentOrders} 单`;
    }
  }

  // 获取空闲日期文本
  getAvailableDatesText(designer: Designer): string {
    if (designer.availableDates.length === 0) {
      return '暂无空闲日期';
    }
    return `空闲日期：${designer.availableDates.slice(0, 3).join(', ')}${designer.availableDates.length > 3 ? '...' : ''}`;
  }

  // 获取团队空闲设计师数量
  getIdleDesignersCount(team: ProjectTeam): number {
    return team.members.filter(m => m.status === 'idle').length;
  }

  // 检查是否为跨团队合作者
  isCrossTeamCollaborator(designer: Designer): boolean {
    return this.internalCrossTeamCollaborators.some(d => d.id === designer.id);
  }

  // 获取选中设计师姓名列表
  getSelectedDesignersNames(): string {
    return this.internalSelectedDesigners.map(d => d.name).join(', ');
  }

  // 获取跨团队合作者姓名列表
  getCrossTeamCollaboratorsNames(): string {
    return this.internalCrossTeamCollaborators.map(d => d.name).join(', ');
  }
}