import { Injectable } from '@angular/core';
import { Observable, of, BehaviorSubject } from 'rxjs';
import { 
  WorkHourRecord, 
  MonthlyWorkHourStats, 
  WorkHourDashboardData, 
  DifficultyCoefficient,
  PerformanceCriteria,
  PricingRule,
  PricingScript,
  AutoQuotationResult,
  PriceAdjustment,
  PerformanceLevel,
  SpaceType,
  ProjectStyle,
  DEFAULT_DIFFICULTY_COEFFICIENTS,
  DEFAULT_PERFORMANCE_CRITERIA,
  DEFAULT_PRICING_RULES
} from '../models/work-hour.model';

@Injectable({
  providedIn: 'root'
})
export class WorkHourService {
  private workHourRecords: WorkHourRecord[] = [];
  private monthlyStats: MonthlyWorkHourStats[] = [];
  private difficultyCoefficients = DEFAULT_DIFFICULTY_COEFFICIENTS;
  private performanceCriteria = DEFAULT_PERFORMANCE_CRITERIA;
  private pricingRules = DEFAULT_PRICING_RULES;
  private pricingScripts: PricingScript[] = [];
  
  // 数据变更通知
  private workHourDataSubject = new BehaviorSubject<WorkHourRecord[]>([]);
  public workHourData$ = this.workHourDataSubject.asObservable();

  constructor() {
    this.initializeMockData();
  }

  // 初始化模拟数据
  private initializeMockData(): void {
    // 模拟工时记录数据
    const mockRecords: WorkHourRecord[] = [
      {
        id: 'wh001',
        projectId: 'p001',
        projectName: '现代简约客厅设计',
        designerId: 'd001',
        designerName: '张设计师',
        phase: '建模',
        startTime: new Date('2024-01-15T09:00:00'),
        endTime: new Date('2024-01-17T18:00:00'),
        actualHours: 16,
        status: '完成',
        spaceType: '客餐厅',
        projectStyle: '现代简约',
        difficultyCoefficient: 1.0,
        effectiveHours: 16,
        notes: '按时完成建模工作'
      },
      {
        id: 'wh002',
        projectId: 'p002',
        projectName: '新中式别墅设计',
        designerId: 'd002',
        designerName: '李设计师',
        phase: '建模',
        startTime: new Date('2024-01-10T09:00:00'),
        endTime: new Date('2024-01-13T18:00:00'),
        actualHours: 24,
        status: '完成',
        pauseReason: '客户2天未反馈',
        pauseHours: 16,
        spaceType: '别墅',
        projectStyle: '新中式',
        difficultyCoefficient: 1.8, // 1.5 * 1.2
        effectiveHours: 43.2, // 24 * 1.8
        notes: '复杂项目，需要多次沟通'
      },
      {
        id: 'wh003',
        projectId: 'p003',
        projectName: '轻奢卧室设计',
        designerId: 'd001',
        designerName: '张设计师',
        phase: '渲染',
        startTime: new Date('2024-01-18T09:00:00'),
        endTime: new Date('2024-01-19T15:00:00'),
        actualHours: 12,
        status: '完成',
        spaceType: '卧室',
        projectStyle: '轻奢',
        difficultyCoefficient: 1.04, // 0.8 * 1.3
        effectiveHours: 12.48,
        notes: '渲染效果优秀'
      }
    ];

    this.workHourRecords = mockRecords;
    this.workHourDataSubject.next(mockRecords);

    // 初始化报价话术库
    this.pricingScripts = [
      {
        id: 'ps001',
        category: '高端报价解释',
        title: '高端报价价值说明',
        content: '我们的高端报价包含更精细的建模工艺、4K高清渲染交付、以及专业的后期处理，确保您获得更好的视觉表现效果。相比标准版本，高端版本在细节处理和最终效果上有显著提升。',
        applicableScenarios: ['客户质疑高端报价', '解释价格差异'],
        tags: ['高端', '价值', '效果']
      },
      {
        id: 'ps002',
        category: '价格构成说明',
        title: '报价构成详细说明',
        content: '我们的报价主要包含三个部分：1）建模费用（占40%）- 根据空间复杂度计算；2）渲染费用（占35%）- 包含灯光、材质、后期处理；3）设计服务费（占25%）- 包含方案沟通、修改服务等。',
        applicableScenarios: ['客户询问价格构成', '报价透明化说明'],
        tags: ['构成', '透明', '详细']
      },
      {
        id: 'ps003',
        category: '修改服务说明',
        title: '修改次数和范围说明',
        content: '标准报价包含1次小图修改（调整色彩、材质等细节），如需大幅度修改方案或增加修改次数，会根据工作量适当调整费用。我们建议在建模阶段充分沟通需求，以减少后期修改。',
        applicableScenarios: ['客户询问修改政策', '设定修改预期'],
        tags: ['修改', '服务', '范围']
      }
    ];
  }

  // 获取工时记录
  getWorkHourRecords(designerId?: string, projectId?: string): Observable<WorkHourRecord[]> {
    let records = this.workHourRecords;
    
    if (designerId) {
      records = records.filter(r => r.designerId === designerId);
    }
    
    if (projectId) {
      records = records.filter(r => r.projectId === projectId);
    }
    
    return of(records);
  }

  // 添加工时记录
  addWorkHourRecord(record: Omit<WorkHourRecord, 'id' | 'effectiveHours'>): Observable<WorkHourRecord> {
    const newRecord: WorkHourRecord = {
      ...record,
      id: `wh${Date.now()}`,
      effectiveHours: this.calculateEffectiveHours(record.actualHours, record.spaceType, record.projectStyle)
    };
    
    this.workHourRecords.push(newRecord);
    this.workHourDataSubject.next(this.workHourRecords);
    
    return of(newRecord);
  }

  // 计算有效工时
  calculateEffectiveHours(actualHours: number, spaceType: SpaceType, projectStyle: ProjectStyle): number {
    const spaceCoeff = this.difficultyCoefficients.find(c => c.spaceType === spaceType)?.spaceCoefficient || 1.0;
    const styleCoeff = this.difficultyCoefficients.find(c => c.styleType === projectStyle)?.styleCoefficient || 1.0;
    const totalCoeff = spaceCoeff * styleCoeff;
    
    return actualHours * totalCoeff;
  }

  // 获取月度统计数据
  getMonthlyStats(designerId?: string, month?: string): Observable<MonthlyWorkHourStats[]> {
    // 基于工时记录计算月度统计
    const stats = this.calculateMonthlyStats(designerId, month);
    return of(stats);
  }

  // 计算月度统计
  private calculateMonthlyStats(designerId?: string, month?: string): MonthlyWorkHourStats[] {
    const records = this.workHourRecords.filter(r => {
      if (designerId && r.designerId !== designerId) return false;
      if (month && !r.startTime.toISOString().startsWith(month)) return false;
      return true;
    });

    const groupedByDesigner = records.reduce((acc, record) => {
      const key = record.designerId;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(record);
      return acc;
    }, {} as Record<string, WorkHourRecord[]>);

    return Object.entries(groupedByDesigner).map(([designerId, records]) => {
      const totalActualHours = records.reduce((sum, r) => sum + r.actualHours, 0);
      const totalEffectiveHours = records.reduce((sum, r) => sum + r.effectiveHours, 0);
      const totalPauseHours = records.reduce((sum, r) => sum + (r.pauseHours || 0), 0);
      const completedProjects = new Set(records.map(r => r.projectId)).size;
      const averageCustomerSatisfaction = 4.5; // 模拟数据
      
      const performanceLevel = this.calculatePerformanceLevel(
        totalEffectiveHours,
        completedProjects,
        averageCustomerSatisfaction
      );

      return {
        designerId,
        designerName: records[0].designerName,
        month: month || new Date().toISOString().substring(0, 7),
        totalActualHours,
        totalEffectiveHours,
        totalPauseHours,
        completedProjects,
        averageCustomerSatisfaction,
        performanceLevel,
        onTimeCompletionRate: 85, // 模拟数据
        excellentWorkRate: 78, // 模拟数据
        records
      };
    });
  }

  // 计算绩效等级
  private calculatePerformanceLevel(effectiveHours: number, completedProjects: number, satisfaction: number): PerformanceLevel {
    if (satisfaction >= 5.0 && effectiveHours > 100) return 'S';
    if (satisfaction >= 4.0 && effectiveHours > 80) return 'A';
    if (satisfaction >= 4.0) return 'B';
    return 'C';
  }

  // 获取仪表板数据
  getDashboardData(): Observable<WorkHourDashboardData> {
    const monthlyStats = this.calculateMonthlyStats();
    
    const dashboardData: WorkHourDashboardData = {
      totalDesigners: new Set(this.workHourRecords.map(r => r.designerId)).size,
      totalProjects: new Set(this.workHourRecords.map(r => r.projectId)).size,
      averageEffectiveHours: monthlyStats.reduce((sum, s) => sum + s.totalEffectiveHours, 0) / monthlyStats.length || 0,
      performanceDistribution: {
        S: monthlyStats.filter(s => s.performanceLevel === 'S').length,
        A: monthlyStats.filter(s => s.performanceLevel === 'A').length,
        B: monthlyStats.filter(s => s.performanceLevel === 'B').length,
        C: monthlyStats.filter(s => s.performanceLevel === 'C').length
      },
      monthlyTrends: [
        { month: '2024-01', totalHours: 320, effectiveHours: 384, efficiency: 120 },
        { month: '2024-02', totalHours: 280, effectiveHours: 336, efficiency: 120 },
        { month: '2024-03', totalHours: 360, effectiveHours: 432, efficiency: 120 }
      ],
      topPerformers: monthlyStats
        .sort((a, b) => b.totalEffectiveHours - a.totalEffectiveHours)
        .slice(0, 5)
        .map(s => ({
          designerId: s.designerId,
          designerName: s.designerName,
          effectiveHours: s.totalEffectiveHours,
          performanceLevel: s.performanceLevel,
          efficiency: Math.round((s.totalEffectiveHours / s.totalActualHours) * 100)
        }))
    };

    return of(dashboardData);
  }

  // 获取报价规则
  getPricingRules(): Observable<PricingRule[]> {
    return of(this.pricingRules);
  }

  // 自动生成报价
  generateAutoQuotation(spaceType: SpaceType, projectStyle: ProjectStyle, estimatedWorkDays: number = 3): Observable<AutoQuotationResult> {
    const rule = this.pricingRules.find(r => r.spaceType === spaceType && r.styleType === projectStyle);
    
    if (!rule) {
      throw new Error(`未找到匹配的报价规则: ${spaceType} - ${projectStyle}`);
    }

    const quotation: AutoQuotationResult = {
      id: `aq${Date.now()}`,
      spaceType,
      projectStyle,
      estimatedWorkDays,
      basePrice: rule.basePrice,
      styleMultiplier: rule.styleMultiplier,
      finalPrice: rule.finalPrice * estimatedWorkDays,
      serviceIncludes: [...rule.serviceIncludes],
      createdAt: new Date(),
      createdBy: 'current-user', // 应该从认证服务获取
      status: 'draft'
    };

    return of(quotation);
  }

  // 获取报价话术库
  getPricingScripts(category?: string): Observable<PricingScript[]> {
    let scripts = this.pricingScripts;
    
    if (category) {
      scripts = scripts.filter(s => s.category === category);
    }
    
    return of(scripts);
  }

  // 添加价格调整记录
  addPriceAdjustment(quotationId: string, adjustment: Omit<PriceAdjustment, 'id'>): Observable<PriceAdjustment> {
    const newAdjustment: PriceAdjustment = {
      ...adjustment,
      id: `pa${Date.now()}`
    };
    
    // 在实际应用中，这里应该更新对应的报价记录
    console.log('价格调整记录已添加:', newAdjustment);
    
    return of(newAdjustment);
  }

  // 获取难度系数配置
  getDifficultyCoefficients(): Observable<DifficultyCoefficient[]> {
    return of(this.difficultyCoefficients);
  }

  // 更新难度系数配置
  updateDifficultyCoefficients(coefficients: DifficultyCoefficient[]): Observable<boolean> {
    this.difficultyCoefficients = coefficients;
    return of(true);
  }

  // 获取绩效标准配置
  getPerformanceCriteria(): Observable<PerformanceCriteria[]> {
    return of(this.performanceCriteria);
  }

  // 更新绩效标准配置
  updatePerformanceCriteria(criteria: PerformanceCriteria[]): Observable<boolean> {
    this.performanceCriteria = criteria;
    return of(true);
  }
}