import { Component, OnInit, signal, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatTabsModule } from '@angular/material/tabs';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips';
import { MatDividerModule } from '@angular/material/divider';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatTableModule } from '@angular/material/table';
import { MatBadgeModule } from '@angular/material/badge';
import { MatDialogModule, MatDialog } from '@angular/material/dialog';
import { MatTooltipModule } from '@angular/material/tooltip';
import { ActivatedRoute } from '@angular/router';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

// 模拟数据接口
interface Designer {
  id: string;
  name: string;
  avatar: string;
  position: string;
  level: string;
  department: string;
  joinDate: string;
  skills: string[];
  styles: string[];
  availableDates: string[];
  certificates: {
    name: string;
    date: string;
    type: string;
  }[];
  projects: {
    id: string;
    name: string;
    clientType: string;
    role: string;
    deliveryDate: string;
    clientRating: number;
    tags: string[];
    feedback: string;
  }[];
  performance: {
    quarter: string;
    customerSatisfaction: number;
    excellentWorkRate: number;
    performanceValue: number;
    deductions: {
      reason: string;
      points: number;
      date: string;
    }[];
    finalGrade: string;
  }[];
}

// 作品集预览对话框组件
@Component({
  selector: 'portfolio-preview-dialog',
  standalone: true,
  imports: [CommonModule, MatDialogModule, MatButtonModule, MatIconModule],
  template: `
    <div class="portfolio-dialog">
      <div class="dialog-header">
        <h2>作品集预览</h2>
        <button mat-icon-button (click)="close()">
          <mat-icon>close</mat-icon>
        </button>
      </div>
      <div class="dialog-content">
        <div class="portfolio-gallery">
          <div class="portfolio-item" *ngFor="let item of portfolioItems">
            <img [src]="item.imageUrl" [alt]="item.title">
            <div class="portfolio-info">
              <h3>{{item.title}}</h3>
              <p>{{item.description}}</p>
              <div class="portfolio-tags">
                <span *ngFor="let tag of item.tags">{{tag}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  `,
  styles: [`
    .portfolio-dialog {
      padding: 0;
      max-width: 900px;
      width: 100%;
    }
    .dialog-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 24px;
      border-bottom: 1px solid #eee;
    }
    .dialog-header h2 {
      margin: 0;
      font-size: 20px;
      color: #1a3a6e;
    }
    .dialog-content {
      padding: 24px;
      max-height: 70vh;
      overflow-y: auto;
    }
    .portfolio-gallery {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 24px;
    }
    .portfolio-item {
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
      transition: transform 0.3s;
    }
    .portfolio-item:hover {
      transform: translateY(-5px);
    }
    .portfolio-item img {
      width: 100%;
      height: 180px;
      object-fit: cover;
    }
    .portfolio-info {
      padding: 16px;
    }
    .portfolio-info h3 {
      margin: 0 0 8px;
      font-size: 16px;
      color: #1a3a6e;
    }
    .portfolio-info p {
      margin: 0 0 12px;
      font-size: 14px;
      color: #666;
    }
    .portfolio-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
    .portfolio-tags span {
      background-color: #e6f7ff;
      color: #1a3a6e;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
    }
  `]
})
export class PortfolioPreviewDialog {
  portfolioItems = [
    {
      imageUrl: 'assets/images/portfolio-1.svg',
      title: '现代简约风客厅',
      description: '为装修公司客户打造的现代简约风格客厅效果图',
      tags: ['客厅', '现代简约', '3D建模']
    },
    {
      imageUrl: 'assets/images/portfolio-2.svg',
      title: '北欧风卧室',
      description: '设计工作室委托的北欧风格卧室设计',
      tags: ['卧室', '北欧风', '软装搭配']
    },
    {
      imageUrl: 'assets/images/portfolio-3.svg',
      title: '日式风格书房',
      description: '个人客户定制的日式风格书房设计',
      tags: ['书房', '日式', '全屋定制']
    },
    {
      imageUrl: 'assets/images/portfolio-4.svg',
      title: '工业风餐厅',
      description: '商业空间的工业风格餐厅设计',
      tags: ['餐厅', '工业风', '商业空间']
    }
  ];

  constructor(private dialog: MatDialog) {}

  close() {
    this.dialog.closeAll();
  }
}

@Component({
  selector: 'app-designer-profile',
  standalone: true,
  imports: [
    CommonModule,
    MatTabsModule,
    MatCardModule,
    MatButtonModule,
    MatIconModule,
    MatChipsModule,
    MatDividerModule,
    MatProgressBarModule,
    MatProgressSpinnerModule,
    MatTableModule,
    MatBadgeModule,
    MatDialogModule,
    MatTooltipModule,
    FormsModule,
    ReactiveFormsModule
  ],
  templateUrl: './designer-profile.html',
  styleUrls: ['./designer-profile.scss']
})
export class DesignerProfile implements OnInit {
  designer = signal<Designer | null>(null);
  activeTab = signal(0);
  projectColumns = ['name', 'clientType', 'role', 'deliveryDate', 'clientRating', 'actions'];
  performanceColumns = ['quarter', 'customerSatisfaction', 'excellentWorkRate', 'performanceValue', 'finalGrade', 'actions'];
  isLoading = signal(true);
  projectsLoading = signal(true);
  performanceLoading = signal(true);
  
  private route = inject(ActivatedRoute);
  private dialog = inject(MatDialog);

  constructor() {}

  ngOnInit() {
    // 从路由参数获取设计师ID
    this.route.paramMap.subscribe(params => {
      const id = params.get('id');
      if (id) {
        this.loadDesignerData(id);
      }
    });
    
    // 模拟加载项目数据
    setTimeout(() => {
      this.projectsLoading.set(false);
    }, 1500);

    // 模拟加载绩效数据和初始化性能趋势图表数据
    setTimeout(() => {
      this.performanceLoading.set(false);
      const performanceData = this.generatePerformanceTrend();
      console.log('Performance trend data:', performanceData);
      // 这里可以添加图表初始化代码
    }, 2000);
  }

  loadDesignerData(id: string) {
    // 模拟API调用加载设计师数据
    setTimeout(() => {
      this.designer.set({
        id,
        name: '张明',
        avatar: 'assets/images/default-avatar.svg',
        position: '高级设计师',
        level: '高级',
        department: '设计部-效果图组',
        joinDate: '2020-05-15',
        skills: ['3D建模', '渲染', '后期处理', 'CAD制图'],
        styles: ['现代简约', '北欧风格', '新中式'],
        availableDates: ['2023-06-15', '2023-06-16', '2023-06-17'],
        certificates: [
          { name: '3D效果图高级设计师认证', date: '2021-03-10', type: '技能认证' },
          { name: '优秀设计师季度奖', date: '2022-12-20', type: '荣誉证书' }
        ],
        projects: [
          {
            id: 'P001',
            name: '城市花园小区-89平米-现代简约',
            clientType: '装修公司',
            role: '效果图设计',
            deliveryDate: '2023-05-20',
            clientRating: 4.8,
            tags: ['住宅', '现代简约'],
            feedback: '设计师理解需求准确，效果图质量高，客户非常满意。'
          },
          {
            id: 'P002',
            name: '星河湾别墅-280平米-新中式',
            clientType: '设计工作室',
            role: '建模+渲染',
            deliveryDate: '2023-04-15',
            clientRating: 4.5,
            tags: ['别墅', '新中式'],
            feedback: '建模细节处理到位，渲染效果自然，符合预期。'
          },
          {
            id: 'P003',
            name: '商业广场-咖啡厅设计',
            clientType: '装修公司',
            role: '全案设计',
            deliveryDate: '2023-03-10',
            clientRating: 5.0,
            tags: ['商业空间', '工业风'],
            feedback: '从建模到后期一条龙服务，效率高，质量好，客户非常满意。'
          }
        ],
        performance: [
          {
            quarter: '2023-Q1',
            customerSatisfaction: 92,
            excellentWorkRate: 85,
            performanceValue: 88,
            deductions: [
              { reason: '项目延期', points: 3, date: '2023-02-15' }
            ],
            finalGrade: 'A'
          },
          {
            quarter: '2022-Q4',
            customerSatisfaction: 88,
            excellentWorkRate: 80,
            performanceValue: 85,
            deductions: [],
            finalGrade: 'A-'
          },
          {
            quarter: '2022-Q3',
            customerSatisfaction: 85,
            excellentWorkRate: 78,
            performanceValue: 82,
            deductions: [
              { reason: '客户投诉', points: 5, date: '2022-08-10' }
            ],
            finalGrade: 'B+'
          }
        ]
      });
    }, 500);
  }

  openPortfolioPreview() {
    this.dialog.open(PortfolioPreviewDialog, {
      width: '80%',
      maxWidth: '1200px',
      panelClass: 'portfolio-dialog-container'
    });
  }

  getPerformanceTrend(metric: 'customerSatisfaction' | 'excellentWorkRate' | 'performanceValue'): string {
    if (!this.designer() || this.designer()!.performance.length < 2) {
      return 'stable';
    }

    const performance = this.designer()!.performance;
    const current = performance[0][metric];
    const previous = performance[1][metric];

    if (current > previous + 3) return 'up';
    if (current < previous - 3) return 'down';
    return 'stable';
  }

  // 性能趋势分析
  generatePerformanceTrend() {
    // 模拟生成过去12个月的性能数据
    const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
    const data = months.map(month => ({
      month,
      score: Math.floor(Math.random() * 30) + 70, // 70-100之间的随机分数
      projects: Math.floor(Math.random() * 5) + 1, // 1-5之间的随机项目数
      revenue: Math.floor(Math.random() * 10000) + 5000 // 5000-15000之间的随机收入
    }));
    
    // 确保数据有一定的趋势性，而不是完全随机
    for (let i = 1; i < data.length; i++) {
      // 让分数有一定的连续性
      data[i].score = Math.max(70, Math.min(100, 
        data[i-1].score + (Math.random() > 0.5 ? 1 : -1) * Math.floor(Math.random() * 5)));
    }
    
    return data;
  }

  getPerformanceColor(grade: string): string {
    if (grade.startsWith('A')) return '#52c41a';
    if (grade.startsWith('B')) return '#1890ff';
    if (grade.startsWith('C')) return '#faad14';
    return '#f5222d';
  }

  changeTab(index: number) {
    this.activeTab.set(index);
  }

  getRatingStars(rating: number): string[] {
    const fullStars = Math.floor(rating);
    const halfStar = rating % 1 >= 0.5;
    const emptyStars = 5 - fullStars - (halfStar ? 1 : 0);
    
    return [
      ...Array(fullStars).fill('star'),
      ...(halfStar ? ['star_half'] : []),
      ...Array(emptyStars).fill('star_border')
    ];
  }
}