import { Component, OnInit, signal, computed, Inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatTabsModule } from '@angular/material/tabs';
import { MatIconModule } from '@angular/material/icon';
import { MatTableModule } from '@angular/material/table';
import { MatCardModule } from '@angular/material/card';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatDialogModule, MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Attendance as AttendanceModel, Employee } from '../../../models/hr.model';

// 补卡申请对话框组件
@Component({
  selector: 'app-attendance-dialog',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatButtonModule,
    MatIconModule
  ],
  template: `
    <div class="dialog-header">
      <h2>补卡申请</h2>
      <button class="close-btn" (click)="dialogRef.close()">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <line x1="18" y1="6" x2="6" y2="18"></line>
          <line x1="6" y1="6" x2="18" y2="18"></line>
        </svg>
      </button>
    </div>
    <div class="dialog-content">
      <div class="info-item">
        <label>员工姓名:</label>
        <span>{{ attendanceData.employeeName }}</span>
      </div>
      <div class="info-item">
        <label>异常日期:</label>
        <span>{{ formatDate(attendanceData.date) }}</span>
      </div>
      <div class="info-item">
        <label>异常类型:</label>
        <span>{{ attendanceData.status }}</span>
      </div>
      <div class="form-group">
        <label>补卡说明:</label>
        <textarea 
          [(ngModel)]="reason" 
          placeholder="请输入补卡原因..." 
          rows="3"
          class="reason-input"
        ></textarea>
      </div>
    </div>
    <div class="dialog-actions">
      <button mat-button (click)="dialogRef.close()">取消</button>
      <button mat-raised-button color="primary" (click)="submit()">提交申请</button>
    </div>
  `,
  styles: [`
    .dialog-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      padding-bottom: 16px;
      border-bottom: 1px solid #e5e7eb;
    }
    .close-btn {
      background: none;
      border: none;
      cursor: pointer;
      color: #6b7280;
      padding: 4px;
    }
    .dialog-content {
      max-width: 500px;
    }
    .info-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 12px;
      padding: 8px 0;
      border-bottom: 1px solid #f3f4f6;
    }
    .form-group {
      margin-top: 20px;
    }
    label {
      display: block;
      margin-bottom: 4px;
      font-weight: 500;
      color: #374151;
    }
    .reason-input {
      width: 100%;
      padding: 8px 12px;
      border: 1px solid #e5e7eb;
      border-radius: 6px;
      font-size: 14px;
      resize: vertical;
    }
    .dialog-actions {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      margin-top: 24px;
    }
  `]
}) class AttendanceDialog {
  attendanceData: any;
  reason = '';
  
  constructor(
    public dialogRef: MatDialogRef<AttendanceDialog>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.attendanceData = data;
  }
  
  formatDate(date: Date | string): string {
    if (!date) return '';
    const d = new Date(date);
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
  }
  
  submit() {
    if (!this.reason.trim()) {
      alert('请输入补卡原因');
      return;
    }
    this.dialogRef.close({ reason: this.reason });
  }
}

// 生成模拟考勤数据
const generateMockAttendanceData = (): AttendanceModel[] => {
  const statuses: Array<'正常' | '迟到' | '早退' | '旷工' | '请假'> = ['正常', '迟到', '早退', '旷工', '请假'];
  const attendanceList: AttendanceModel[] = [];
  const today = new Date();
  const projectIds = ['proj-001', 'proj-002', 'proj-003', 'proj-004'];
  const projectNames = ['现代风格客厅设计', '欧式厨房改造', '极简卧室设计', '办公室规划'];
  
  // 生成最近30天的考勤数据
  for (let i = 29; i >= 0; i--) {
    const date = new Date();
    date.setDate(today.getDate() - i);
    
    // 为每个部门生成3-5个员工的考勤数据
    const departmentCount = Math.floor(Math.random() * 3) + 3;
    
    for (let j = 1; j <= departmentCount; j++) {
      const statusIndex = Math.floor(Math.random() * 10);
      let status: typeof statuses[0];
      
      // 80%概率正常，10%概率迟到，5%概率早退，3%概率请假，2%概率旷工
      if (statusIndex < 8) {
        status = '正常';
      } else if (statusIndex < 9) {
        status = '迟到';
      } else if (statusIndex < 9.5) {
        status = '早退';
      } else if (statusIndex < 9.8) {
        status = '请假';
      } else {
        status = '旷工';
      }
      
      // 随机选择一个项目
      const projectIndex = Math.floor(Math.random() * projectIds.length);
      const projectId = projectIds[projectIndex];
      const projectName = projectNames[projectIndex];
      
      // 生成打卡时间
      let checkInTime: Date | undefined;
      let checkOutTime: Date | undefined;
      let workHours = 0;
      
      if (status !== '旷工' && status !== '请假') {
        checkInTime = new Date(date);
        checkInTime.setHours(9 + (status === '迟到' ? Math.floor(Math.random() * 2) : 0));
        checkInTime.setMinutes(Math.floor(Math.random() * 60));
        
        checkOutTime = new Date(date);
        checkOutTime.setHours(18 - (status === '早退' ? Math.floor(Math.random() * 2) : 0));
        checkOutTime.setMinutes(Math.floor(Math.random() * 60));
        
        // 计算工作时长（小时）
        workHours = Math.round((checkOutTime.getTime() - checkInTime.getTime()) / (1000 * 60 * 60) * 10) / 10;
      }
      
      attendanceList.push({
        id: `att-${date.getTime()}-${j}`,
        employeeId: `emp-${j}`,
        date,
        checkInTime,
        checkOutTime,
        status,
        workHours,
        projectId,
        projectName
      });
    }
  }
  
  return attendanceList;
};

// 生成模拟员工数据
const generateMockEmployees = (): Employee[] => {
  const employees: Employee[] = [];
  const departments = ['设计部', '客户服务部', '财务部', '人力资源部'];
  const positions = ['设计师', '客服专员', '财务专员', '人事专员', '经理', '助理'];
  const names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'];
  
  for (let i = 1; i <= 20; i++) {
    employees.push({
      id: `emp-${i}`,
      name: names[i % names.length] + i,
      department: departments[Math.floor(Math.random() * departments.length)],
      position: positions[Math.floor(Math.random() * positions.length)],
      employeeId: `EMP2023${String(i).padStart(3, '0')}`,
      phone: `138${Math.floor(Math.random() * 100000000)}`,
      email: `employee${i}@example.com`,
      gender: i % 2 === 0 ? '女' : '男',
      birthDate: new Date(1980 + Math.floor(Math.random() * 20), Math.floor(Math.random() * 12), Math.floor(Math.random() * 28) + 1),
      hireDate: new Date(2020 + Math.floor(Math.random() * 3), Math.floor(Math.random() * 12), Math.floor(Math.random() * 28) + 1),
      status: '在职',
      avatar: `https://via.placeholder.com/40?text=${i}`
    });
  }
  
  return employees;
};

// 主组件
@Component({
  selector: 'app-attendance',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatButtonModule,
    MatTabsModule,
    MatIconModule,
    MatTableModule,
    MatCardModule,
    MatTooltipModule,
    MatDialogModule
  ],
  templateUrl: './attendance.html',
  styleUrl: './attendance.scss'
}) export class Attendance implements OnInit {
  // 数据
  attendanceData = signal<AttendanceModel[]>([]);
  employees = signal<Employee[]>([]);
  selectedView = signal<'day' | 'week' | 'month'>('month');
  selectedDate = signal<Date>(new Date());
  selectedEmployeeId = signal<string>('');
  selectedProjectId = signal<string>('');
  
  // 获取日期tooltip信息
  getDayTooltip(day: any): string {
    if (!day.attendance) {
      return '休息日';
    }
    
    const status = day.attendance.status;
    let tooltip = `状态: ${status}`;
    
    if (day.attendance.workHours) {
      tooltip += `\n工作时长: ${day.attendance.workHours}小时`;
    }
    
    if (day.attendance.checkInTime) {
      const checkIn = new Date(day.attendance.checkInTime);
      tooltip += `\n签到: ${checkIn.getHours().toString().padStart(2, '0')}:${checkIn.getMinutes().toString().padStart(2, '0')}`;
    }
    
    if (day.attendance.checkOutTime) {
      const checkOut = new Date(day.attendance.checkOutTime);
      tooltip += `\n签退: ${checkOut.getHours().toString().padStart(2, '0')}:${checkOut.getMinutes().toString().padStart(2, '0')}`;
    }
    
    if (day.attendance.projectName) {
      tooltip += `\n项目: ${day.attendance.projectName}`;
    }
    
    return tooltip;
  }
  
  // 检查日期是否为今天
  isToday(date: Date): boolean {
    const today = new Date();
    const checkDate = new Date(date);
    return today.toDateString() === checkDate.toDateString();
  }
  
  // 计算属性
  filteredAttendance = computed(() => {
    let filtered = this.attendanceData();
    
    // 按员工筛选
    if (this.selectedEmployeeId()) {
      filtered = filtered.filter(item => item.employeeId === this.selectedEmployeeId());
    }
    
    // 按项目筛选
    if (this.selectedProjectId()) {
      filtered = filtered.filter(item => item.projectId === this.selectedProjectId());
    }
    
    // 按视图筛选（日/周/月）
    const selectedDate = this.selectedDate();
    if (this.selectedView() === 'day') {
      filtered = filtered.filter(item => {
        const itemDate = new Date(item.date);
        return itemDate.getDate() === selectedDate.getDate() &&
               itemDate.getMonth() === selectedDate.getMonth() &&
               itemDate.getFullYear() === selectedDate.getFullYear();
      });
    } else if (this.selectedView() === 'week') {
      // 获取本周的起止日期
      const startOfWeek = new Date(selectedDate);
      const day = startOfWeek.getDay() || 7; // 调整周日为7
      startOfWeek.setDate(startOfWeek.getDate() - day + 1);
      const endOfWeek = new Date(startOfWeek);
      endOfWeek.setDate(endOfWeek.getDate() + 6);
      
      filtered = filtered.filter(item => {
        const itemDate = new Date(item.date);
        return itemDate >= startOfWeek && itemDate <= endOfWeek;
      });
    } else if (this.selectedView() === 'month') {
      filtered = filtered.filter(item => {
        const itemDate = new Date(item.date);
        return itemDate.getMonth() === selectedDate.getMonth() &&
               itemDate.getFullYear() === selectedDate.getFullYear();
      });
    }
    
    return filtered;
  });
  
  // 异常考勤列表
  exceptionAttendance = computed(() => {
    return this.filteredAttendance().filter(item => 
      item.status === '迟到' || item.status === '早退' || item.status === '旷工'
    ).sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  });
  
  // 考勤统计
  attendanceStats = computed(() => {
    const data = this.filteredAttendance();
    const totalDays = data.length;
    const normalDays = data.filter(item => item.status === '正常').length;
    const lateDays = data.filter(item => item.status === '迟到').length;
    const earlyLeaveDays = data.filter(item => item.status === '早退').length;
    const absentDays = data.filter(item => item.status === '旷工').length;
    const leaveDays = data.filter(item => item.status === '请假').length;
    
    const totalWorkHours = data.reduce((sum, item) => sum + item.workHours, 0);
    const avgWorkHours = totalDays > 0 ? (totalWorkHours / (totalDays - leaveDays - absentDays || 1)).toFixed(1) : '0.0';
    
    return {
      totalDays,
      normalDays,
      lateDays,
      earlyLeaveDays,
      absentDays,
      leaveDays,
      totalWorkHours: totalWorkHours.toFixed(1),
      avgWorkHours,
      complianceRate: totalDays > 0 ? Math.round((normalDays / totalDays) * 100) : 0
    };
  });
  
  // 部门考勤对比数据
  departmentAttendanceData = computed(() => {
    const departmentMap = new Map<string, { total: number; compliant: number }>();
    
    this.attendanceData().forEach(item => {
      const employee = this.employees().find(emp => emp.id === item.employeeId);
      if (employee) {
        const dept = employee.department;
        const current = departmentMap.get(dept) || { total: 0, compliant: 0 };
        current.total++;
        if (item.status === '正常') {
          current.compliant++;
        }
        departmentMap.set(dept, current);
      }
    });
    
    const result: { department: string; complianceRate: number; total: number; compliant: number }[] = [];
    departmentMap.forEach((value, key) => {
      result.push({
        department: key,
        complianceRate: Math.round((value.compliant / value.total) * 100),
        total: value.total,
        compliant: value.compliant
      });
    });
    
    return result.sort((a, b) => b.complianceRate - a.complianceRate);
  });
  
  // 显示的表格列
  displayedColumns = ['date', 'employeeName', 'status', 'workHours', 'projectName', 'actions'];
  
  constructor(private dialog: MatDialog) {}
  
  ngOnInit() {
    // 加载模拟数据
    this.attendanceData.set(generateMockAttendanceData());
    this.employees.set(generateMockEmployees());
  }
  
  // 切换视图（日/周/月）
  switchView(view: 'day' | 'week' | 'month') {
    this.selectedView.set(view);
  }
  
  // 获取员工姓名
  getEmployeeName(employeeId: string): string {
    const employee = this.employees().find(emp => emp.id === employeeId);
    return employee ? employee.name : '未知员工';
  }
  
  // 格式化日期
  formatDate(date: Date | string): string {
    if (!date) return '';
    const d = new Date(date);
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
  }
  
  // 格式化时间
  formatTime(date: Date | string): string {
    if (!date) return '';
    const d = new Date(date);
    return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
  }
  
  // 获取状态样式类
  getStatusClass(status: string): string {
    switch (status) {
      case '正常':
        return 'status-normal';
      case '迟到':
        return 'status-late';
      case '早退':
        return 'status-early';
      case '旷工':
        return 'status-absent';
      case '请假':
        return 'status-leave';
      default:
        return '';
    }
  }
  
  // 切换日期
  navigateDate(direction: 'prev' | 'next') {
    const newDate = new Date(this.selectedDate());
    
    if (this.selectedView() === 'day') {
      newDate.setDate(newDate.getDate() + (direction === 'prev' ? -1 : 1));
    } else if (this.selectedView() === 'week') {
      newDate.setDate(newDate.getDate() + (direction === 'prev' ? -7 : 7));
    } else if (this.selectedView() === 'month') {
      newDate.setMonth(newDate.getMonth() + (direction === 'prev' ? -1 : 1));
    }
    
    this.selectedDate.set(newDate);
  }
  
  // 打开补卡申请对话框
  openAttendanceDialog(attendance: AttendanceModel) {
    const employee = this.employees().find(emp => emp.id === attendance.employeeId);
    const dialogRef = this.dialog.open(AttendanceDialog, {
      width: '500px',
      maxWidth: '90vw',
      disableClose: true,
      data: {
        ...attendance,
        employeeName: employee ? employee.name : '未知员工'
      }
    });
    
    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        // 在实际应用中，这里会提交补卡申请到服务器
        alert('补卡申请已提交，等待审核');
      }
    });
  }
  
  // 导出考勤数据
  exportAttendanceData() {
    alert('考勤数据导出功能待实现');
  }
  
  // 获取日历数据
  getCalendarDays() {
    const year = this.selectedDate().getFullYear();
    const month = this.selectedDate().getMonth();
    
    // 获取当月第一天和最后一天
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    
    // 获取当月第一天是星期几
    const firstDayIndex = firstDay.getDay();
    
    const days = [];
    
    // 添加上月的最后几天
    for (let i = firstDayIndex; i > 0; i--) {
      const day = new Date(year, month, -i + 1);
      days.push({
        date: day,
        dayOfMonth: day.getDate(),
        currentMonth: false,
        attendance: null
      });
    }
    
    // 添加当月的天数
    for (let i = 1; i <= lastDay.getDate(); i++) {
      const day = new Date(year, month, i);
      const dayAttendance = this.attendanceData().filter(item => {
        const itemDate = new Date(item.date);
        return itemDate.getDate() === i &&
               itemDate.getMonth() === month &&
               itemDate.getFullYear() === year &&
               (!this.selectedEmployeeId() || item.employeeId === this.selectedEmployeeId());
      });
      
      days.push({
        date: day,
        dayOfMonth: i,
        currentMonth: true,
        attendance: dayAttendance.length > 0 ? dayAttendance[0] : null
      });
    }
    
    // 添加下月的前几天，凑够42天（6行7列）
    const remainingDays = 42 - days.length;
    for (let i = 1; i <= remainingDays; i++) {
      const day = new Date(year, month + 1, i);
      days.push({
        date: day,
        dayOfMonth: i,
        currentMonth: false,
        attendance: null
      });
    }
    
    return days;
  }
  
  // 获取星期几的中文名称
  getWeekdayName(index: number): string {
    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    return weekdays[index];
  }
}
