import { Component, OnInit, Input, Output, EventEmitter, computed, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { DesignerCalendarComponent } from '../designer-calendar/designer-calendar.component';

export interface Designer {
  id: string;
  name: string;
  avatar?: string;
  groupId: string;
  groupName: string;
  isLeader: boolean;
  status: 'available' | 'busy' | 'stagnant' | 'overloaded';
  currentProjects: number;
  lastOrderDate?: string;
  idleDays?: number;
}

export interface ProjectGroup {
  id: string;
  name: string;
  leader: string;
  leaderId: string;
  members: Designer[];
}

export interface DesignerAssignment {
  id: string;
  designer: Designer;
  quotationItemIds: string[];
  assignedAmount: number;
  workloadPercentage: number;
  isCrossGroup: boolean;
}

export interface QuotationItem {
  id: string;
  roomType: string;
  amount: number;
  description?: string;
}

@Component({
  selector: 'app-designer-assignment',
  standalone: true,
  imports: [CommonModule, FormsModule, DesignerCalendarComponent],
  templateUrl: './designer-assignment.component.html',
  styleUrls: ['./designer-assignment.component.scss']
})
export class DesignerAssignmentComponent {
  @Input() quotationItems = signal<QuotationItem[]>([]);
  @Input() selectedDesigners = signal<DesignerAssignment[]>([]);
  @Output() designerChange = new EventEmitter<DesignerAssignment[]>();

  designerAssignments = signal<DesignerAssignment[]>([]);
  availableDesigners = signal<Designer[]>([]);
  showDesignerCalendar = signal(false);
  selectedDate = signal(new Date());
  selectedProjectGroup = '';
  allowCrossGroupCollaboration = false;
  openDropdownId = signal<string | null>(null);

  // 项目组数据
  projectGroups: ProjectGroup[] = [
    {
      id: 'group1',
      name: '家装设计组',
      leader: '张设计师',
      leaderId: 'designer1',
      members: []
    },
    {
      id: 'group2', 
      name: '工装设计组',
      leader: '李设计师',
      leaderId: 'designer2',
      members: []
    },
    {
      id: 'group3',
      name: '软装设计组', 
      leader: '王设计师',
      leaderId: 'designer3',
      members: []
    }
  ];

  // 计算总分配金额
  totalAssignedAmount = computed(() => {
    return this.designerAssignments().reduce((sum, assignment) => sum + assignment.assignedAmount, 0);
  });

  // 计算总报价金额
  totalQuotationAmount = computed(() => {
    return this.quotationItems().reduce((sum, item) => sum + item.amount, 0);
  });

  // 计算分配进度
  assignmentProgress = computed(() => {
    const total = this.totalQuotationAmount();
    const assigned = this.totalAssignedAmount();
    return total > 0 ? (assigned / total) * 100 : 0;
  });

  // 计算剩余金额
  remainingAmount = computed(() => {
    return this.totalQuotationAmount() - this.totalAssignedAmount();
  });

  constructor() {
    this.loadAvailableDesigners();
  }

  ngOnInit() {
    if (this.selectedDesigners().length > 0) {
      this.designerAssignments.set(this.selectedDesigners());
    }
  }

  private loadAvailableDesigners() {
    // 模拟设计师数据
    const mockDesigners: Designer[] = [
      {
        id: 'designer1',
        name: '张设计师',
        avatar: document.baseURI+'/assets/avatars/designer1.jpg',
        groupId: 'group1',
        groupName: '家装设计组',
        isLeader: true,
        status: 'available',
        currentProjects: 2,
        lastOrderDate: '2024-01-15',
        idleDays: 3
      },
      {
        id: 'designer2',
        name: '李设计师',
        avatar: document.baseURI+'/assets/avatars/designer2.jpg',
        groupId: 'group2',
        groupName: '工装设计组',
        isLeader: true,
        status: 'busy',
        currentProjects: 4,
        lastOrderDate: '2024-01-18'
      },
      {
        id: 'designer3',
        name: '王设计师',
        avatar: document.baseURI+'/assets/avatars/designer3.jpg',
        groupId: 'group3',
        groupName: '软装设计组',
        isLeader: true,
        status: 'available',
        currentProjects: 1,
        lastOrderDate: '2024-01-10',
        idleDays: 8
      },
      {
        id: 'designer4',
        name: '赵设计师',
        groupId: 'group1',
        groupName: '家装设计组',
        isLeader: false,
        status: 'stagnant',
        currentProjects: 0,
        lastOrderDate: '2023-12-20',
        idleDays: 28
      },
      {
        id: 'designer5',
        name: '刘设计师',
        groupId: 'group2',
        groupName: '工装设计组',
        isLeader: false,
        status: 'available',
        currentProjects: 2,
        lastOrderDate: '2024-01-16',
        idleDays: 2
      }
    ];

    this.availableDesigners.set(mockDesigners);
  }

  // 项目组变更
  onProjectGroupChange(groupId: string) {
    this.selectedProjectGroup = groupId;
    
    if (groupId) {
      const group = this.projectGroups.find(g => g.id === groupId);
      if (group) {
        // 自动添加组长
        const leader = this.availableDesigners().find(d => d.id === group.leaderId);
        if (leader && !this.designerAssignments().find(a => a.designer.id === leader.id)) {
          this.addDesignerToAssignment(leader);
        }
      }
    }
  }

  // 跨组合作变更
  onCrossGroupChange(allowed: boolean) {
    this.allowCrossGroupCollaboration = allowed;
  }

  // 添加设计师分配
  addDesignerAssignment() {
    // 这里可以打开设计师选择对话框
    // 暂时添加一个可用的设计师
    const availableDesigner = this.availableDesigners().find(d => 
      !this.designerAssignments().find(a => a.designer.id === d.id)
    );
    
    if (availableDesigner) {
      this.addDesignerToAssignment(availableDesigner);
    }
  }

  private addDesignerToAssignment(designer: Designer) {
    const newAssignment: DesignerAssignment = {
      id: this.generateId(),
      designer,
      quotationItemIds: [],
      assignedAmount: 0,
      workloadPercentage: 0,
      isCrossGroup: this.selectedProjectGroup ? designer.groupId !== this.selectedProjectGroup : false
    };

    const currentAssignments = this.designerAssignments();
    this.designerAssignments.set([...currentAssignments, newAssignment]);
    this.emitChange();
  }

  // 移除设计师分配
  removeAssignment(assignmentId: string) {
    const currentAssignments = this.designerAssignments();
    const filteredAssignments = currentAssignments.filter(a => a.id !== assignmentId);
    this.designerAssignments.set(filteredAssignments);
    this.emitChange();
  }

  // 编辑分配
  editAssignment(assignment: DesignerAssignment) {
    // 这里可以打开编辑对话框
    console.log('编辑分配:', assignment);
  }

  // 切换报价项目下拉菜单
  toggleQuotationDropdown(assignmentId: string) {
    const currentOpen = this.openDropdownId();
    this.openDropdownId.set(currentOpen === assignmentId ? null : assignmentId);
  }

  // 获取未分配的报价项目
  getUnassignedQuotationItems(currentAssignmentId: string): QuotationItem[] {
    const allAssignedIds = this.designerAssignments()
      .filter(a => a.id !== currentAssignmentId)
      .flatMap(a => a.quotationItemIds);
    
    return this.quotationItems().filter(item => !allAssignedIds.includes(item.id));
  }

  // 添加报价项目到分配
  addQuotationToAssignment(assignmentId: string, quotationItemId: string) {
    const currentAssignments = this.designerAssignments();
    const updatedAssignments = currentAssignments.map(assignment => {
      if (assignment.id === assignmentId) {
        const quotationItem = this.quotationItems().find(q => q.id === quotationItemId);
        if (quotationItem) {
          return {
            ...assignment,
            quotationItemIds: [...assignment.quotationItemIds, quotationItemId],
            assignedAmount: assignment.assignedAmount + quotationItem.amount,
            workloadPercentage: this.calculateWorkloadPercentage(assignment.assignedAmount + quotationItem.amount)
          };
        }
      }
      return assignment;
    });

    this.designerAssignments.set(updatedAssignments);
    this.openDropdownId.set(null);
    this.emitChange();
  }

  // 从分配中移除报价项目
  removeQuotationFromAssignment(assignmentId: string, quotationItemId: string) {
    const currentAssignments = this.designerAssignments();
    const updatedAssignments = currentAssignments.map(assignment => {
      if (assignment.id === assignmentId) {
        const quotationItem = this.quotationItems().find(q => q.id === quotationItemId);
        if (quotationItem) {
          return {
            ...assignment,
            quotationItemIds: assignment.quotationItemIds.filter(id => id !== quotationItemId),
            assignedAmount: assignment.assignedAmount - quotationItem.amount,
            workloadPercentage: this.calculateWorkloadPercentage(assignment.assignedAmount - quotationItem.amount)
          };
        }
      }
      return assignment;
    });

    this.designerAssignments.set(updatedAssignments);
    this.emitChange();
  }

  // 获取报价项目名称
  getQuotationItemName(quotationItemId: string): string {
    const item = this.quotationItems().find(q => q.id === quotationItemId);
    return item ? item.roomType : '未知项目';
  }

  // 计算工作量占比
  private calculateWorkloadPercentage(assignedAmount: number): number {
    const total = this.totalQuotationAmount();
    return total > 0 ? (assignedAmount / total) * 100 : 0;
  }

  // 获取设计师状态文本
  getDesignerStatusText(status: Designer['status']): string {
    const statusMap = {
      'available': '空闲可接单',
      'busy': '忙碌中',
      'stagnant': '停滞期',
      'overloaded': '满载'
    };
    return statusMap[status] || '未知状态';
  }

  // 设计师选择事件
  onDesignerSelect(designer: Designer) {
    if (!this.designerAssignments().find(a => a.designer.id === designer.id)) {
      this.addDesignerToAssignment(designer);
    }
  }

  // 日期变更事件
  onDateChange(date: Date) {
    this.selectedDate.set(date);
  }

  private emitChange() {
    this.designerChange.emit(this.designerAssignments());
  }

  private generateId(): string {
    return 'assignment_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }
}