import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { signal } from '@angular/core';
import { AuthService } from '../../../services/auth.service';

// 项目财务状态类型定义
export type FinancialStatus = 
  | 'pendingQuote'     // 待报价
  | 'quoted'           // 已报价
  | 'pendingPayment'   // 待收款
  | 'partialPayment'   // 部分收款
  | 'fullPayment'      // 全款到账
  | 'pendingSettlement' // 待结算
  | 'settled';         // 已结算

// 沟通日志类型定义
export interface CommunicationLog {
  id: string;
  content: string;
  timestamp: Date;
  hasRedLineContent: boolean;
}

// 项目类型定义
export interface Project {
  id: string;
  name: string;
  clientName: string;
  salesPerson: string;
  planType?: string;
  technicalType?: string;
  area?: number;
  price: number;
  cost: number;
  profitRate: number;
  financialStatus: FinancialStatus;
  updatedAt: Date;
  communicationLog: CommunicationLog[];
  quoteType?: 'fixedPrice' | 'hourlyRate' | 'materialCost';
}

// 工时标准配置接口
export interface HourlyRateConfig {
  [key: string]: {
    [key: string]: number;
  };
}

@Component({
  selector: 'app-project-records',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, RouterModule],
  templateUrl: './project-records.html',
  styleUrls: ['./project-records.scss']
})
export class ProjectRecords implements OnInit {
  // 使用signal管理项目列表数据
  projects = signal<Project[]>([]);
  
  // 用户角色
  userRole = signal<string>('teamLead');
  
  // 工时标准配置
  hourlyRateConfig = signal<HourlyRateConfig>({
    '建模': {
      '基础': 100,
      '标准': 150,
      '高级': 200
    },
    '渲染': {
      '基础': 120,
      '标准': 180,
      '高级': 250
    },
    '后期': {
      '基础': 80,
      '标准': 120,
      '高级': 180
    }
  });

  // 报价表单
  quoteForm: FormGroup;
  
  // 模态框状态
  showQuoteModal = signal(false);
  showCommunicationLogModal = signal(false);
  selectedProject = signal<Project | null>(null);

  constructor(private fb: FormBuilder, private authService: AuthService) {
    // 初始化报价表单
    this.quoteForm = this.fb.group({
      projectId: [''],
      planType: [''],
      technicalType: [''],
      area: [0],
      profitRate: [30]
    });
  }

  ngOnInit(): void {
    // 初始化用户角色
    this.initializeUserRole();
    // 初始化项目数据
    this.loadProjectData();
  }
  
  // 初始化用户角色
  initializeUserRole(): void {
    // 从AuthService获取用户角色
    const roles = this.authService.getUserRoles();
    // 默认使用teamLead角色
    let userRole = 'teamLead';
    
    // 如果用户有admin角色，也视为teamLead
    if (roles.includes('admin')) {
      userRole = 'teamLead';
    } else if (roles.length > 0) {
      // 否则使用第一个角色
      userRole = roles[0];
    }
    
    this.userRole.set(userRole);
  }

  // 加载项目数据
  loadProjectData(): void {
    // 模拟从API获取项目数据
    const mockProjects: Project[] = [
      {
        id: 'PRJ-2023-001',
        name: '现代风格住宅室内设计',
        clientName: '星光地产',
        salesPerson: '张三',
        planType: '室内设计',
        technicalType: '建模/渲染/后期',
        area: 120,
        price: 85000,
        cost: 55000,
        profitRate: 35.3,
        financialStatus: 'pendingQuote',
        updatedAt: new Date('2023-09-15'),
        communicationLog: []
      },
      {
        id: 'PRJ-2023-002',
        name: '商业办公空间设计',
        clientName: '未来科技有限公司',
        salesPerson: '李四',
        planType: '办公设计',
        technicalType: '建模/渲染',
        area: 350,
        price: 120000,
        cost: 80000,
        profitRate: 33.3,
        financialStatus: 'quoted',
        updatedAt: new Date('2023-09-10'),
        communicationLog: [
          {
            id: 'LOG-001',
            content: '客户对报价表示基本接受，等待内部审批',
            timestamp: new Date('2023-09-12'),
            hasRedLineContent: false
          }
        ]
      },
      {
        id: 'PRJ-2023-003',
        name: '餐饮空间改造设计',
        clientName: '悦享餐饮集团',
        salesPerson: '王五',
        planType: '餐饮设计',
        technicalType: '建模/渲染/后期',
        area: 180,
        price: 95000,
        cost: 65000,
        profitRate: 31.6,
        financialStatus: 'pendingPayment',
        updatedAt: new Date('2023-09-05'),
        communicationLog: [
          {
            id: 'LOG-002',
            content: '已确认设计方案，准备支付首付款',
            timestamp: new Date('2023-09-08'),
            hasRedLineContent: false
          }
        ]
      },
      {
        id: 'PRJ-2023-004',
        name: '酒店大堂设计',
        clientName: '环球酒店集团',
        salesPerson: '赵六',
        planType: '酒店设计',
        technicalType: '建模/渲染/后期',
        area: 500,
        price: 250000,
        cost: 160000,
        profitRate: 36.0,
        financialStatus: 'partialPayment',
        updatedAt: new Date('2023-08-30'),
        communicationLog: [
          {
            id: 'LOG-003',
            content: '已收到50%预付款，开始正式设计工作',
            timestamp: new Date('2023-09-02'),
            hasRedLineContent: false
          }
        ]
      },
      {
        id: 'PRJ-2023-005',
        name: '品牌展厅设计',
        clientName: '时尚家居品牌',
        salesPerson: '张三',
        planType: '展厅设计',
        technicalType: '建模/渲染',
        area: 200,
        price: 110000,
        cost: 70000,
        profitRate: 36.4,
        financialStatus: 'fullPayment',
        updatedAt: new Date('2023-08-25'),
        communicationLog: [
          {
            id: 'LOG-004',
            content: '全款已到账，项目进入收尾阶段',
            timestamp: new Date('2023-08-28'),
            hasRedLineContent: false
          }
        ]
      },
      {
        id: 'PRJ-2023-006',
        name: '别墅花园景观设计',
        clientName: '私人业主',
        salesPerson: '李四',
        planType: '景观设计',
        technicalType: '渲染/后期',
        area: 300,
        price: 75000,
        cost: 45000,
        profitRate: 40.0,
        financialStatus: 'pendingSettlement',
        updatedAt: new Date('2023-08-20'),
        communicationLog: [
          {
            id: 'LOG-005',
            content: '项目已完成，等待财务结算',
            timestamp: new Date('2023-08-22'),
            hasRedLineContent: false
          }
        ]
      },
      {
        id: 'PRJ-2023-007',
        name: '零售店空间设计',
        clientName: '潮流服饰品牌',
        salesPerson: '王五',
        planType: '零售设计',
        technicalType: '建模/渲染/后期',
        area: 150,
        price: 80000,
        cost: 50000,
        profitRate: 37.5,
        financialStatus: 'settled',
        updatedAt: new Date('2023-08-15'),
        communicationLog: [
          {
            id: 'LOG-006',
            content: '项目已完成结算',
            timestamp: new Date('2023-08-18'),
            hasRedLineContent: false
          }
        ]
      }
    ];

    this.projects.set(mockProjects);
  }

  // 打开报价模态框
  openQuoteModal(project: Project): void {
    this.selectedProject.set(project);
    this.quoteForm.patchValue({
      projectId: project.id,
      planType: project.planType || '',
      technicalType: project.technicalType || '',
      area: project.area || 0,
      profitRate: 30
    });
    this.showQuoteModal.set(true);
  }

  // 计算报价
  calculateQuote(): void {
    if (!this.selectedProject()) return;

    const formValue = this.quoteForm.value;
    const { area = 0, profitRate = 30, planType, technicalType } = formValue;
    
    let baseCost = 0;
    
    // 基于方案类型和技术类型计算基础成本
    if (planType === '室内设计') {
      baseCost = area * 300;
    } else if (planType === '办公设计') {
      baseCost = area * 250;
    } else if (planType === '餐饮设计') {
      baseCost = area * 350;
    } else if (planType === '酒店设计') {
      baseCost = area * 400;
    } else if (planType === '展厅设计') {
      baseCost = area * 500;
    }
    
    // 基于技术复杂度调整
    if (technicalType?.includes('后期')) {
      baseCost *= 1.2;
    }
    
    // 计算带利润率的报价
    const price = Math.round(baseCost * (1 + profitRate / 100));

    // 更新项目数据
    const updatedProjects = this.projects().map(project => {
      if (project.id === this.selectedProject()?.id) {
        return {
          ...project,
          planType: planType,
          technicalType: technicalType,
          area: area,
          cost: baseCost,
          price: price,
          profitRate: profitRate,
          financialStatus: 'quoted' as FinancialStatus,
          updatedAt: new Date()
        };
      }
      return project;
    });

    this.projects.set(updatedProjects);
    this.showQuoteModal.set(false);
    
    // 重置选择的项目
    this.selectedProject.set(null);
  }

  // 更新财务状态
  updateFinancialStatus(project: Project, newStatus: FinancialStatus): void {
    const updatedProjects = this.projects().map(p => {
      if (p.id === project.id) {
        return {
          ...p,
          financialStatus: newStatus,
          updatedAt: new Date()
        };
      }
      return p;
    });

    this.projects.set(updatedProjects);
  }

  // 打开沟通日志弹窗
  openCommunicationLogModal(project: Project): void {
    this.selectedProject.set(project);
    this.showCommunicationLogModal.set(true);
  }

  // 添加沟通记录（简化版，实际项目中应该有更完整的实现）
  addCommunicationLog(content: string, hasRedLineContent: boolean): void {
    if (!this.selectedProject()) return;

    const newLog: CommunicationLog = {
      id: `LOG-${Date.now()}`,
      content: content,
      timestamp: new Date(),
      hasRedLineContent: hasRedLineContent
    };

    const updatedProjects = this.projects().map(project => {
      if (project.id === this.selectedProject()?.id) {
        return {
          ...project,
          communicationLog: [...project.communicationLog, newLog],
          updatedAt: new Date()
        };
      }
      return project;
    });

    this.projects.set(updatedProjects);
  }

  // 获取财务状态文本
  getStatusText(status: FinancialStatus): string {
    const statusMap: Record<FinancialStatus, string> = {
      'pendingQuote': '待报价',
      'quoted': '已报价',
      'pendingPayment': '待收款',
      'partialPayment': '部分收款',
      'fullPayment': '全款到账',
      'pendingSettlement': '待结算',
      'settled': '已结算'
    };
    return statusMap[status] || status;
  }

  // 获取财务状态样式类
  getStatusClass(status: FinancialStatus): string {
    const statusClassMap: Record<FinancialStatus, string> = {
      'pendingQuote': 'status-pending',
      'quoted': 'status-quoted',
      'pendingPayment': 'status-warning',
      'partialPayment': 'status-info',
      'fullPayment': 'status-success',
      'pendingSettlement': 'status-warning',
      'settled': 'status-completed'
    };
    return statusClassMap[status] || '';
  }

  // 获取报价类型标签
  getQuoteTypeLabel(project: Project): string {
    if (!project.quoteType) return '';
    const labelMap: Record<string, string> = {
      'fixedPrice': '固定价格',
      'hourlyRate': '按小时计费',
      'materialCost': '材料成本+人工费'
    };
    return labelMap[project.quoteType] || '';
  }

  // 获取报价类型样式类
  getQuoteTypeClass(project: Project): string {
    if (!project.quoteType) return '';
    return `quote-type-${project.quoteType}`;
  }

  // 格式化日期
  formatDate(date: Date): string {
    if (!date) return '';
    return new Date(date).toLocaleDateString('zh-CN');
  }

  // 格式化金额
  formatAmount(amount: number): string {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0
    }).format(amount);
  }

  // 获取项目类型标签
  getProjectTypeLabel(project: Project): string {
    return project.planType || '未设置';
  }
  
  // 获取技术类型标签
  getTechnicalTypeLabel(project: Project): string {
    return project.technicalType || '未设置';
  }
}
