import { Component, Inject, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatIconModule } from '@angular/material/icon';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';

interface WorkflowStage {
  id: string;
  name: string;
  order: number;
  description: string;
  isActive: boolean;
}

interface SOPTemplate {
  id: string;
  name: string;
  description: string;
  steps: string[];
  category: string;
  isActive: boolean;
}

interface PricingRule {
  id: string;
  name: string;
  description: string;
  formula: string;
  category: string;
  isActive: boolean;
}

interface PerformanceRule {
  id: string;
  name: string;
  description: string;
  metric: string;
  threshold: number;
  reward: string;
  isActive: boolean;
}

interface DialogData {
  type: 'workflow' | 'sop' | 'pricing' | 'performance';
  item: WorkflowStage | SOPTemplate | PricingRule | PerformanceRule;
  categories?: string[];
  metrics?: string[];
}

@Component({
  selector: 'app-setting-dialog',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatButtonModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatIconModule,
    MatSlideToggleModule
  ],
  templateUrl: './setting-dialog.html',
  styleUrl: './setting-dialog.scss'
})
export class SettingDialogComponent implements OnInit {
  type: 'workflow' | 'sop' | 'pricing' | 'performance';
  item: WorkflowStage | SOPTemplate | PricingRule | PerformanceRule;
  categories: string[] = [];
  metrics: string[] = [];
  currentStep: string = '';
  isEditMode: boolean = false;

  // 安全访问绩效规则属性的getter
  get performanceItem(): PerformanceRule {
    return this.item as PerformanceRule;
  }
  
  // 安全访问报价规则属性的getter
  get pricingItem(): PricingRule {
    return this.item as PricingRule;
  }
  
  // 安全访问工作流阶段属性的getter
  get workflowItem(): WorkflowStage {
    return this.item as WorkflowStage;
  }
  
  // 安全访问SOP模板属性的getter
  get sopItem(): SOPTemplate {
    return this.item as SOPTemplate;
  }

  constructor(
    public dialogRef: MatDialogRef<SettingDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData
  ) {
    this.type = data.type;
    this.item = { ...data.item };
    this.categories = data.categories || [];
    this.metrics = data.metrics || [];
    this.isEditMode = !!this.item.id;
  }

  ngOnInit(): void {
    // 根据类型初始化特殊处理
    if (this.type === 'sop' && !(this.item as SOPTemplate).steps) {
      (this.item as SOPTemplate).steps = [];
    }
  }

  onCancel(): void {
    this.dialogRef.close();
  }

  onSave(): void {
    if (this.isFormValid()) {
      this.dialogRef.close(this.item);
    }
  }

  isFormValid(): boolean {
    // 通用验证 - 名称和描述
    if (!this.item.name || !this.item.name.trim()) {
      alert('请输入名称');
      return false;
    }

    if (!this.item.description || !this.item.description.trim()) {
      alert('请输入描述');
      return false;
    }

    // 根据类型进行特定验证
    switch (this.type) {
      case 'workflow':
        const workflowItem = this.item as WorkflowStage;
        if (!workflowItem.order || workflowItem.order <= 0) {
          alert('请输入有效的阶段顺序');
          return false;
        }
        break;
      case 'sop':
        const sopItem = this.item as SOPTemplate;
        if (!sopItem.category) {
          alert('请选择模板分类');
          return false;
        }
        if (!sopItem.steps || sopItem.steps.length === 0) {
          alert('请至少添加一个流程步骤');
          return false;
        }
        break;
      case 'pricing':
        const pricingItem = this.item as PricingRule;
        if (!pricingItem.category) {
          alert('请选择报价分类');
          return false;
        }
        if (!pricingItem.formula || !pricingItem.formula.trim()) {
          alert('请输入计算公式');
          return false;
        }
        break;
      case 'performance':
        const performanceItem = this.item as PerformanceRule;
        if (!performanceItem.metric) {
          alert('请选择绩效指标');
          return false;
        }
        if (performanceItem.threshold === undefined || performanceItem.threshold < 0 || performanceItem.threshold > 100) {
          alert('请输入有效的阈值（0-100）');
          return false;
        }
        if (!performanceItem.reward || !performanceItem.reward.trim()) {
          alert('请输入奖励方式');
          return false;
        }
        break;
    }

    return true;
  }

  // SOP模板步骤管理
  addStep(): void {
    if (this.type === 'sop' && this.currentStep.trim()) {
      const sopItem = this.item as SOPTemplate;
      sopItem.steps.push(this.currentStep.trim());
      this.currentStep = '';
    }
  }

  removeStep(index: number): void {
    if (this.type === 'sop') {
      const sopItem = this.item as SOPTemplate;
      sopItem.steps.splice(index, 1);
    }
  }

  moveStep(fromIndex: number, toIndex: number): void {
    if (this.type === 'sop') {
      const sopItem = this.item as SOPTemplate;
      const step = sopItem.steps.splice(fromIndex, 1)[0];
      sopItem.steps.splice(toIndex, 0, step);
    }
  }

  // 获取对话框标题
  get dialogTitle(): string {
    const typeTitles = {
      workflow: this.isEditMode ? '编辑项目阶段' : '添加项目阶段',
      sop: this.isEditMode ? '编辑SOP模板' : '添加SOP模板',
      pricing: this.isEditMode ? '编辑报价规则' : '添加报价规则',
      performance: this.isEditMode ? '编辑绩效规则' : '添加绩效规则'
    };
    return typeTitles[this.type];
  }
}