import { Component, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { ProjectService } from '../../../services/project.service';
import {
  SkillTag,
  PerformanceData,
  MatchingOrder,
  Settlement,
  ProjectStage
} from '../../../models/project.model';

@Component({
  selector: 'app-personal-board',
  standalone: true,
  imports: [CommonModule, RouterModule],
  templateUrl: './personal-board.html',
  styleUrl: './personal-board.scss'
})
export class PersonalBoard implements OnInit, AfterViewInit {
  skillTags: SkillTag[] = [];
  performanceData: PerformanceData[] = [];
  matchingOrders: MatchingOrder[] = [];
  settlements: Settlement[] = [];
  totalSettlementAmount: number = 0;
  pendingSettlementAmount: number = 0;
  isJuniorDesigner: boolean = false; // 权限控制标记

  @ViewChild('performanceChart') performanceChart!: ElementRef;

  constructor(private projectService: ProjectService) {}

  ngOnInit(): void {
    this.checkDesignerLevel(); // 检查设计师级别
    this.loadData();
  }

  ngAfterViewInit(): void {
    // 数据加载完成后初始化图表
    if (this.performanceData.length > 0 && this.performanceChart) {
      this.initCustomChart();
    }
  }

  private initCustomChart(): void {
    try {
      const chartContainer = this.performanceChart.nativeElement;
      chartContainer.innerHTML = '';

      // 准备图表数据
      const months = this.performanceData.map(item => item.month);
      const projectCompletionRate = this.performanceData.map(item => item.projectCompletionRate);
      const customerSatisfaction = this.performanceData.map(item => item.customerSatisfaction);
      const deliveryOnTimeRate = this.performanceData.map(item => item.deliveryOnTimeRate);

      // 创建图表容器
      const chartWrapper = document.createElement('div');
      chartWrapper.className = 'custom-chart-wrapper';
      chartWrapper.style.height = '100%';
      chartWrapper.style.display = 'flex';
      chartWrapper.style.flexDirection = 'column';

      // 创建图例
      const legend = document.createElement('div');
      legend.className = 'custom-chart-legend';
      legend.style.display = 'flex';
      legend.style.justifyContent = 'center';
      legend.style.marginBottom = '10px';
      legend.innerHTML = `
        <div class="legend-item"><span class="legend-color project-completion"></span>项目完成率</div>
        <div class="legend-item"><span class="legend-color customer-satisfaction"></span>客户满意度</div>
        <div class="legend-item"><span class="legend-color delivery-on-time"></span>交付准时率</div>
      `;
      chartWrapper.appendChild(legend);

      // 创建图表主体
      const chartBody = document.createElement('div');
      chartBody.className = 'custom-chart-body';
      chartBody.style.flex = '1';
      chartBody.style.display = 'flex';
      chartBody.style.alignItems = 'flex-end';
      chartBody.style.justifyContent = 'space-around';
      chartBody.style.padding = '20px 0';

      // 创建Y轴刻度
      const yAxis = document.createElement('div');
      yAxis.className = 'custom-chart-yaxis';
      yAxis.style.position = 'absolute';
      yAxis.style.left = '0';
      yAxis.style.height = '100%';
      yAxis.style.display = 'flex';
      yAxis.style.flexDirection = 'column-reverse';
      yAxis.style.justifyContent = 'space-between';
      yAxis.innerHTML = `
        <div class="yaxis-label">100%</div>
        <div class="yaxis-label">75%</div>
        <div class="yaxis-label">50%</div>
        <div class="yaxis-label">25%</div>
        <div class="yaxis-label">0%</div>
      `;
      chartContainer.appendChild(yAxis);

      // 为每个月份创建柱状图组
      months.forEach((month, index) => {
        const barGroup = document.createElement('div');
        barGroup.className = 'custom-chart-bargroup';
        barGroup.style.display = 'flex';
        barGroup.style.alignItems = 'flex-end';
        barGroup.style.width = '25%';
        barGroup.style.position = 'relative';

        // 项目完成率柱子
        const projectBar = this.createBar(
          projectCompletionRate[index], 
          'project-completion', 
          `${projectCompletionRate[index]}%`
        );
        barGroup.appendChild(projectBar);

        // 客户满意度柱子
        const satisfactionBar = this.createBar(
          customerSatisfaction[index], 
          'customer-satisfaction', 
          `${customerSatisfaction[index]}%`
        );
        barGroup.appendChild(satisfactionBar);

        // 交付准时率柱子
        const ontimeBar = this.createBar(
          deliveryOnTimeRate[index], 
          'delivery-on-time', 
          `${deliveryOnTimeRate[index]}%`
        );
        barGroup.appendChild(ontimeBar);

        // 添加月份标签
        const monthLabel = document.createElement('div');
        monthLabel.className = 'custom-chart-month-label';
        monthLabel.textContent = month;
        monthLabel.style.position = 'absolute';
        monthLabel.style.bottom = '-25px';
        monthLabel.style.textAlign = 'center';
        monthLabel.style.width = '100%';
        barGroup.appendChild(monthLabel);

        chartBody.appendChild(barGroup);
      });

      chartWrapper.appendChild(chartBody);
      chartContainer.appendChild(chartWrapper);

      // 动态添加样式
      this.addChartStyles();
    } catch (error) {
      console.error('Failed to initialize custom chart:', error);
    }
  }

  private createBar(value: number, className: string, tooltip: string): HTMLDivElement {
    const bar = document.createElement('div');
    bar.className = `custom-chart-bar ${className}`;
    bar.style.height = `${value}%`;
    bar.style.width = '20px';
    bar.style.margin = '0 2px';
    bar.style.position = 'relative';
    bar.title = tooltip;

    const barFill = document.createElement('div');
    barFill.className = 'custom-chart-bar-fill';
    barFill.style.height = '100%';
    barFill.style.width = '100%';
    barFill.style.borderRadius = '4px 4px 0 0';
    bar.appendChild(barFill);

    return bar;
  }

  private addChartStyles(): void {
    // 检查是否已存在样式
    let styleElement = document.getElementById('custom-chart-styles');
    if (styleElement) return;

    styleElement = document.createElement('style');
    styleElement.id = 'custom-chart-styles';
    styleElement.textContent = `
      .custom-chart-wrapper {
        position: relative;
        width: 100%;
        height: 100%;
      }
      .custom-chart-legend .legend-item {
        display: flex;
        align-items: center;
        margin: 0 15px;
        font-size: 12px;
      }
      .custom-chart-legend .legend-color {
        display: inline-block;
        width: 12px;
        height: 12px;
        margin-right: 5px;
        border-radius: 2px;
      }
      .legend-color.project-completion {
        background-color: #1890ff;
      }
      .legend-color.customer-satisfaction {
        background-color: #52c41a;
      }
      .legend-color.delivery-on-time {
        background-color: #fa8c16;
      }
      .custom-chart-body {
        position: relative;
        margin-left: 40px;
      }
      .custom-chart-bargroup {
        height: 100%;
      }
      .custom-chart-bar {
        cursor: pointer;
        transition: opacity 0.3s;
      }
      .custom-chart-bar:hover {
        opacity: 0.8;
      }
      .custom-chart-bar-fill {
        transition: height 0.5s ease-out;
      }
      .project-completion .custom-chart-bar-fill {
        background-color: #1890ff;
      }
      .customer-satisfaction .custom-chart-bar-fill {
        background-color: #52c41a;
      }
      .delivery-on-time .custom-chart-bar-fill {
        background-color: #fa8c16;
      }
      .custom-chart-month-label {
        font-size: 12px;
        color: #666;
      }
      .custom-chart-yaxis {
        width: 40px;
        font-size: 10px;
        color: #999;
      }
      .yaxis-label {
        text-align: right;
        padding-right: 5px;
      }
    `;
    document.head.appendChild(styleElement);
  }

  checkDesignerLevel(): void {
    // 实际应用中应从用户服务获取级别信息
    // 这里模拟初级设计师权限
    this.isJuniorDesigner = false; // 临时设置为false，可根据实际需求调整
  }

  loadData(): void {
    this.loadSkillTags();
    this.loadPerformanceData();
    this.loadMatchingOrders();
    this.loadSettlements();
  }

  loadSkillTags(): void {
    this.projectService.getSkillTags().subscribe(tags => {
      this.skillTags = tags.sort((a, b) => b.level - a.level);
    });
  }

  loadPerformanceData(): void {
    this.projectService.getPerformanceData().subscribe(data => {
      this.performanceData = data;
      // 在数据加载完成后初始化图表（确保DOM已经渲染完成）
      setTimeout(() => {
        if (this.performanceChart) {
          this.initCustomChart();
        }
      }, 0);
    });
  }

  loadMatchingOrders(): void {
    this.projectService.getMatchingOrders().subscribe(orders => {
      this.matchingOrders = orders.sort((a, b) => b.matchRate - a.matchRate);
    });
  }

  loadSettlements(): void {
    this.projectService.getSettlements().subscribe(settlements => {
      this.settlements = settlements;
      
      // 计算总金额和待结算金额
      this.totalSettlementAmount = settlements.reduce((sum, s) => sum + s.amount, 0);
      this.pendingSettlementAmount = settlements
        .filter(s => s.status === '待结算')
        .reduce((sum, s) => sum + s.amount, 0);
    });
  }

  acceptOrder(orderId: string): void {
    // 接受订单功能
    console.log('接受订单:', orderId);
    alert('订单接受成功！');
    // 实际应用中应调用API接受订单
  }

  viewSettlementDetails(): void {
    // 查看结算明细功能
    console.log('查看结算明细');
  }

  // 根据项目阶段获取对应的结算比例
  getStagePercentage(stage: ProjectStage): number {
    const percentages: Record<ProjectStage, number> = {
      '订单分配': 0,
      '需求沟通': 0,
      '方案确认': 0,
      '建模': 30,
      '软装': 0,
      '渲染': 50,
      '后期': 20,
      '尾款结算': 0,
      '客户评价': 0,
      '投诉处理': 0
    };
    return percentages[stage] || 0;
  }

}
