import { Component, Input, Output, EventEmitter, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatIconModule } from '@angular/material/icon';

export interface CalendarStats {
  idleDays: number;
  recentOrders: number;
  totalOrders: number;
  stagnantProjects: number;
  lastOrderDate?: string;
  workloadPercentage: number;
  status: 'available' | 'busy' | 'overloaded' | 'stagnant';
}

export interface CalendarData {
  designerName: string;
  stats: CalendarStats;
  events: CalendarEvent[];
  calendar: CalendarDay[];
  currentMonth: Date;
}

export interface CalendarEvent {
  id: string;
  title: string;
  date: string;
  type: 'project' | 'review' | 'vacation';
  status: 'scheduled' | 'completed' | 'cancelled';
}

export interface CalendarDay {
  date: Date;
  orderCount: number;
  isReviewDay: boolean;
  tooltip: string;
  isCurrentMonth: boolean;
  isToday: boolean;
  isIdle: boolean;
}

@Component({
  selector: 'app-designer-calendar',
  standalone: true,
  imports: [CommonModule, MatIconModule],
  templateUrl: './designer-calendar.component.html',
  styleUrls: ['./designer-calendar.component.scss']
})
export class DesignerCalendarComponent implements OnInit, OnChanges {
  @Input() visible: boolean = false;
  @Input() calendarData: CalendarData | null = null;
  @Output() close = new EventEmitter<void>();

  currentMonth: Date = new Date();
  weekDays: string[] = ['日', '一', '二', '三', '四', '五', '六'];

  // 计算后的月份网格（包含前后补齐的非当月日期），保证每周 7 列完整显示
  monthGrid: CalendarDay[] = [];

  ngOnInit(): void {
    if (this.calendarData && this.calendarData.currentMonth) {
      this.currentMonth = new Date(this.calendarData.currentMonth);
    }
    this.buildMonthGrid();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['calendarData'] && this.calendarData) {
      // 输入数据变更时同步当前月份
      this.currentMonth = new Date(this.calendarData.currentMonth || new Date());
      this.buildMonthGrid();
    }
    if (changes['visible']) {
      // 弹窗打开时也确保构建网格
      this.buildMonthGrid();
    }
  }

  onClose(): void {
    this.close.emit();
  }

  getStatusText(stats: CalendarStats): string {
    const statusMap = {
      'available': '空闲',
      'busy': '忙碌',
      'overloaded': '满载',
      'stagnant': '停滞期'
    };
    return statusMap[stats.status] || stats.status;
  }

  getStatusColor(stats: CalendarStats): string {
    const colorMap = {
      'available': '#10b981',
      'busy': '#f59e0b',
      'overloaded': '#ef4444',
      'stagnant': '#6b7280'
    };
    return colorMap[stats.status] || '#6b7280';
  }

  getWorkloadClass(percentage: number): string {
    if (percentage >= 80) return 'high';
    if (percentage >= 50) return 'medium';
    return 'low';
  }

  getEventTypeText(type: string): string {
    const typeMap = {
      'project': '项目',
      'review': '评审',
      'vacation': '休假'
    };
    return typeMap[type as keyof typeof typeMap] || type;
  }

  getEventStatusClass(status: string): string {
    return `event-${status}`;
  }

  // 获取工作负荷百分比
  getWorkloadPercentage(stats: CalendarStats): number {
    return stats.workloadPercentage || 0;
  }

  // 上一个月
  previousMonth(): void {
    if (this.calendarData) {
      this.currentMonth = new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth() - 1, 1);
      this.calendarData.currentMonth = this.currentMonth;
      this.buildMonthGrid();
    }
  }

  // 下一个月
  nextMonth(): void {
    if (this.calendarData) {
      this.currentMonth = new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth() + 1, 1);
      this.calendarData.currentMonth = this.currentMonth;
      this.buildMonthGrid();
    }
  }

  // 格式化日期
  formatDate(date: Date): string {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    return `${year}年${month}月`;
  }

  // 获取日期样式类
  getDayClass(day: CalendarDay): string {
    const classes = ['calendar-day'];
    
    if (!day.isCurrentMonth) classes.push('other-month');
    if (day.isToday) classes.push('today');
    if (day.isIdle && day.isCurrentMonth) classes.push('idle');
    if (day.orderCount > 0 && day.isCurrentMonth) classes.push('busy');
    if (day.isReviewDay && day.isCurrentMonth) classes.push('review');
    
    // 周末样式
    const dayOfWeek = day.date.getDay();
    if (dayOfWeek === 0 || dayOfWeek === 6) {
      classes.push('weekend');
    }
    
    return classes.join(' ');
  }

  // 点击日期
  onDayClick(day: CalendarDay): void {
    if (day.isIdle && day.isCurrentMonth && !day.isReviewDay) {
      // 可以在这里添加分配订单的逻辑
      console.log('点击空闲日期:', day.date);
      // 可以触发一个事件让父组件处理
      // this.assignOrder.emit({ date: day.date, designerId: this.calendarData?.designerId });
    }
  }

  // 构建完整的月份网格，包含前后补齐的日期，保证每行 7 列
  private buildMonthGrid(): void {
    const result: CalendarDay[] = [];
    if (!this.calendarData) {
      this.monthGrid = result;
      return;
    }

    // 以当前月第一天为基准
    const monthStart = new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth(), 1);
    const startWeekday = monthStart.getDay(); // 0-6, 周日为0
    const daysInMonth = new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth() + 1, 0).getDate();

    // 建立当月数据索引（按 yyyy-mm-dd）
    const dataIndex = new Map<string, CalendarDay>();
    for (const d of (this.calendarData.calendar || [])) {
      const key = this.dateKey(d.date);
      dataIndex.set(key, d);
    }

    // 前置补齐：上个月的最后几天
    for (let i = startWeekday - 1; i >= 0; i--) {
      const date = new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth(), -i);
      result.push(this.emptyDay(date));
    }

    // 当前月天数
    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth(), day);
      const key = this.dateKey(date);
      const existing = dataIndex.get(key);
      
      if (existing) {
        result.push({ 
          ...existing, 
          date, 
          isCurrentMonth: true, 
          isToday: this.isToday(date),
          tooltip: this.generateTooltip(existing)
        });
      } else {
        result.push({
          date,
          orderCount: 0,
          isReviewDay: false,
          tooltip: '空闲可分配',
          isCurrentMonth: true,
          isToday: this.isToday(date),
          isIdle: true
        });
      }
    }

    // 后置补齐：直到整除 7 列
    const remainder = result.length % 7;
    if (remainder !== 0) {
      const need = 7 - remainder;
      const lastDay = new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth(), daysInMonth);
      for (let i = 1; i <= need; i++) {
        const date = new Date(lastDay);
        date.setDate(lastDay.getDate() + i);
        result.push(this.emptyDay(date));
      }
    }

    this.monthGrid = result;
  }

  private dateKey(date: Date): string {
    const y = date.getFullYear();
    const m = date.getMonth() + 1;
    const d = date.getDate();
    return `${y}-${m}-${d}`;
  }

  private isToday(date: Date): boolean {
    const now = new Date();
    return now.getFullYear() === date.getFullYear() &&
           now.getMonth() === date.getMonth() &&
           now.getDate() === date.getDate();
  }

  private emptyDay(date: Date): CalendarDay {
    return {
      date,
      orderCount: 0,
      isReviewDay: false,
      tooltip: '',
      isCurrentMonth: false,
      isToday: this.isToday(date),
      isIdle: false
    };
  }

  private generateTooltip(day: CalendarDay): string {
    if (day.isReviewDay) {
      return '对图日期 - 不可分配其他工作';
    }
    if (day.orderCount > 0) {
      return `已有${day.orderCount}个订单 - ${day.orderCount >= 2 ? '工作负荷较高' : '可继续分配'}`;
    }
    return '空闲可分配新订单';
  }

  // 获取日期状态（用于样式）
  getDayStatus(day: CalendarDay): string {
    if (!day.isCurrentMonth) return 'other-month';
    if (day.isReviewDay) return 'review';
    if (day.orderCount >= 2) return 'busy-high';
    if (day.orderCount > 0) return 'busy-medium';
    if (day.isIdle) return 'idle';
    return 'normal';
  }

  // 获取详细的 tooltip
  getDayTooltip(day: CalendarDay): string {
    if (!day.isCurrentMonth) return '';
    
    const parts: string[] = [];
    
    if (day.isToday) {
      parts.push('【今天】');
    }
    
    if (day.isReviewDay) {
      parts.push('🔴 对图日期 - 完全不可分配');
    } else if (day.orderCount >= 2) {
      parts.push(`🔵 已有${day.orderCount}个订单 - 工作负荷高`);
    } else if (day.orderCount === 1) {
      parts.push(`🔵 已有1个订单 - 可继续分配`);
    } else if (day.isIdle) {
      parts.push('🟢 空闲 - 可分配新订单');
    }
    
    return parts.join(' ');
  }

  // 导出 Math 对象供模板使用
  Math = Math;
}