/**
 * 工时跟踪器
 * 用于自动从任务执行中记录和同步工时
 */

interface WorkHourRecord {
  id: string;
  staffId: string;
  staffName: string;
  taskId?: string;
  taskName?: string;
  date: string;
  startTime: string;
  endTime: string;
  totalHours: number;
  workType: string;
  fieldName: string;
  area: number;
  notes: string;
  status: '待审核' | '已审核' | '已驳回';
  recordType: '自动记录' | '手动录入';
  createdAt: string;
}

/**
 * 从任务完成时自动创建工时记录
 * 在任务状态更新为"已完成"时调用此函数
 */
export function createWorkHourFromTask(task: {
  id: string;
  taskName: string;
  executor: string;
  executorId?: string;
  actualStartTime: string;
  actualEndTime: string;
  operationType?: string;
  fieldName?: string;
  area?: number;
}): WorkHourRecord | null {
  try {
    // 验证必要字段
    if (!task.actualStartTime || !task.actualEndTime || !task.executor) {
      console.warn('任务缺少必要的工时信息:', task);
      return null;
    }

    // 计算工时
    const start = new Date(task.actualStartTime);
    const end = new Date(task.actualEndTime);
    
    if (end <= start) {
      console.warn('任务时间无效:', task);
      return null;
    }

    const totalHours = (end.getTime() - start.getTime()) / (1000 * 60 * 60);

    // 创建工时记录
    const workHour: WorkHourRecord = {
      id: `hour-auto-${task.id}-${Date.now()}`,
      staffId: task.executorId || 'unknown',
      staffName: task.executor,
      taskId: task.id,
      taskName: task.taskName,
      date: task.actualStartTime.split('T')[0],
      startTime: start.toTimeString().slice(0, 5),
      endTime: end.toTimeString().slice(0, 5),
      totalHours: parseFloat(totalHours.toFixed(2)),
      workType: task.operationType || '其他',
      fieldName: task.fieldName || '',
      area: task.area || 0,
      notes: `从任务"${task.taskName}"自动生成`,
      status: '已审核', // 从任务自动生成的工时默认已审核
      recordType: '自动记录',
      createdAt: new Date().toISOString(),
    };

    return workHour;
  } catch (error) {
    console.error('创建工时记录失败:', error);
    return null;
  }
}

/**
 * 保存工时记录到 localStorage
 */
export function saveWorkHour(workHour: WorkHourRecord): boolean {
  try {
    const data = localStorage.getItem('smart_agriculture_work_hours');
    let hours: WorkHourRecord[] = data ? JSON.parse(data) : [];

    // 检查是否已存在相同任务的工时记录
    if (workHour.taskId) {
      const exists = hours.some(h => h.taskId === workHour.taskId);
      if (exists) {
        console.log('该任务的工时记录已存在，跳过创建');
        return false;
      }
    }

    // 添加新记录
    hours.unshift(workHour);
    localStorage.setItem('smart_agriculture_work_hours', JSON.stringify(hours));
    
    console.log('工时记录已保存:', workHour);
    return true;
  } catch (error) {
    console.error('保存工时记录失败:', error);
    return false;
  }
}

/**
 * 批量从任务列表创建工时记录
 */
export function batchCreateWorkHoursFromTasks(tasks: any[]): number {
  let count = 0;
  
  tasks.forEach(task => {
    // 只处理已完成的任务
    if (task.status !== '已完成') return;
    
    const workHour = createWorkHourFromTask(task);
    if (workHour && saveWorkHour(workHour)) {
      count++;
    }
  });
  
  return count;
}

/**
 * 获取指定员工的工时统计
 */
export function getStaffWorkHourStats(staffId: string, startDate?: string, endDate?: string): {
  totalHours: number;
  approvedHours: number;
  pendingHours: number;
  recordCount: number;
} {
  try {
    const data = localStorage.getItem('smart_agriculture_work_hours');
    if (!data) {
      return { totalHours: 0, approvedHours: 0, pendingHours: 0, recordCount: 0 };
    }

    let hours: WorkHourRecord[] = JSON.parse(data);
    
    // 筛选指定员工的记录
    hours = hours.filter(h => h.staffId === staffId);
    
    // 日期范围筛选
    if (startDate) {
      hours = hours.filter(h => h.date >= startDate);
    }
    if (endDate) {
      hours = hours.filter(h => h.date <= endDate);
    }

    const totalHours = hours.reduce((sum, h) => sum + h.totalHours, 0);
    const approvedHours = hours
      .filter(h => h.status === '已审核')
      .reduce((sum, h) => sum + h.totalHours, 0);
    const pendingHours = hours
      .filter(h => h.status === '待审核')
      .reduce((sum, h) => sum + h.totalHours, 0);

    return {
      totalHours: parseFloat(totalHours.toFixed(2)),
      approvedHours: parseFloat(approvedHours.toFixed(2)),
      pendingHours: parseFloat(pendingHours.toFixed(2)),
      recordCount: hours.length,
    };
  } catch (error) {
    console.error('获取工时统计失败:', error);
    return { totalHours: 0, approvedHours: 0, pendingHours: 0, recordCount: 0 };
  }
}

/**
 * 导出工时记录（用于薪酬核算）
 */
export function exportWorkHoursForPayroll(startDate: string, endDate: string): any[] {
  try {
    const data = localStorage.getItem('smart_agriculture_work_hours');
    if (!data) return [];

    let hours: WorkHourRecord[] = JSON.parse(data);
    
    // 筛选日期范围和已审核的记录
    hours = hours.filter(h => 
      h.date >= startDate && 
      h.date <= endDate && 
      h.status === '已审核'
    );

    // 按员工汇总
    const payrollData = new Map<string, any>();
    
    hours.forEach(h => {
      if (!payrollData.has(h.staffId)) {
        payrollData.set(h.staffId, {
          staffId: h.staffId,
          staffName: h.staffName,
          totalHours: 0,
          recordCount: 0,
          workTypes: new Map<string, number>(),
        });
      }
      
      const staff = payrollData.get(h.staffId);
      staff.totalHours += h.totalHours;
      staff.recordCount++;
      
      const currentHours = staff.workTypes.get(h.workType) || 0;
      staff.workTypes.set(h.workType, currentHours + h.totalHours);
    });

    // 转换为数组格式
    return Array.from(payrollData.values()).map(staff => ({
      ...staff,
      totalHours: parseFloat(staff.totalHours.toFixed(2)),
      workTypes: Object.fromEntries(staff.workTypes),
    }));
  } catch (error) {
    console.error('导出工时数据失败:', error);
    return [];
  }
}
