import { Component, OnInit, signal, Inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { MatDialogModule, MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatSnackBarModule, MatSnackBar } from '@angular/material/snack-bar';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatMenuModule } from '@angular/material/menu';
import { Employee, Department, Position, Contract, Certificate, EmployeeStatus } from '../../../models/hr.model';

// 创建新增员工对话框组件
@Component({
  selector: 'app-add-employee-dialog',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatInputModule,
    MatSelectModule,
    MatDatepickerModule,
    MatNativeDateModule,
    MatButtonModule
  ],
  template: `
    <div class="dialog-header">
      <h2>新增员工</h2>
      <button class="close-btn" (click)="dialogRef.close()">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <line x1="18" y1="6" x2="6" y2="18"></line>
          <line x1="6" y1="6" x2="18" y2="18"></line>
        </svg>
      </button>
    </div>
    <form [formGroup]="employeeForm" (ngSubmit)="onSubmit()" class="employee-form">
      <div class="form-row">
        <div class="form-group">
          <label>员工姓名 <span class="required-mark">*</span></label>
          <input matInput formControlName="name" placeholder="请输入姓名">
        </div>
        <div class="form-group">
          <label>工号 <span class="required-mark">*</span></label>
          <input matInput formControlName="employeeId" placeholder="请输入工号">
        </div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label>部门 <span class="required-mark">*</span></label>
          <mat-select formControlName="department">
            <mat-option *ngFor="let dept of departments" [value]="dept.name">
              {{ dept.name }}
            </mat-option>
          </mat-select>
        </div>
        <div class="form-group">
          <label>岗位 <span class="required-mark">*</span></label>
          <input matInput formControlName="position" placeholder="请输入岗位">
        </div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label>手机号码 <span class="required-mark">*</span></label>
          <input matInput formControlName="phone" placeholder="请输入手机号码">
        </div>
        <div class="form-group">
          <label>邮箱 <span class="required-mark">*</span></label>
          <input matInput formControlName="email" placeholder="请输入邮箱">
        </div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label>性别</label>
          <mat-select formControlName="gender">
            <mat-option value="男">男</mat-option>
            <mat-option value="女">女</mat-option>
          </mat-select>
        </div>
        <div class="form-group">
          <label>出生日期</label>
          <input matInput [matDatepicker]="birthDatePicker" formControlName="birthDate">
          <mat-datepicker-toggle matSuffix [for]="birthDatePicker"></mat-datepicker-toggle>
          <mat-datepicker #birthDatePicker></mat-datepicker>
        </div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label>入职日期 <span class="required-mark">*</span></label>
          <input matInput [matDatepicker]="hireDatePicker" formControlName="hireDate">
          <mat-datepicker-toggle matSuffix [for]="hireDatePicker"></mat-datepicker-toggle>
          <mat-datepicker #hireDatePicker></mat-datepicker>
        </div>
        <div class="form-group">
          <label>状态 <span class="required-mark">*</span></label>
          <mat-select formControlName="status">
            <mat-option value="在职">在职</mat-option>
            <mat-option value="试用期">试用期</mat-option>
            <mat-option value="离职">离职</mat-option>
          </mat-select>
        </div>
      </div>
      <div class="dialog-actions">
        <button type="button" mat-button (click)="dialogRef.close()">取消</button>
        <button type="submit" mat-raised-button color="primary" [disabled]="!employeeForm.valid">保存</button>
      </div>
    </form>
  `,
  styles: [`
    .dialog-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 32px;
      padding-bottom: 20px;
      border-bottom: 2px solid #e5e7eb;
    }
    
    .close-btn {
      background: none;
      border: none;
      cursor: pointer;
      color: #9ca3af;
      padding: 6px;
      border-radius: 50%;
      transition: all 0.2s ease;
      
      &:hover {
        color: #1f2937;
        background-color: #f3f4f6;
        transform: scale(1.15);
      }
      
      &:active {
        transform: scale(0.95);
      }
    }
    
    .employee-form {
      max-width: 100%;
    }
    
    .form-row {
      display: flex;
      gap: 24px;
      margin-bottom: 24px;
      flex-wrap: wrap;
    }
    
    .form-group {
      flex: 1;
      min-width: 250px;
    }
    
    label {
      display: block;
      margin-bottom: 8px;
      font-weight: 600;
      color: #374151;
      font-size: 16px;
    }
    
    .required-mark {
      color: #ef4444;
      font-size: 16px;
    }
    
    .dialog-actions {
      display: flex;
      justify-content: flex-end;
      gap: 16px;
      margin-top: 32px;
      padding-top: 20px;
      border-top: 1px solid #e5e7eb;
    }
    
    // 表单元素聚焦效果
    .mat-form-field-appearance-fill .mat-form-field-focus-overlay {
      background-color: rgba(30, 64, 175, 0.05);
    }
    
    // 错误状态样式
    .mat-error {
      color: #ef4444;
      font-size: 14px;
      margin-top: 4px;
      display: block;
    }
    
    .mat-form-field-invalid .mat-input-element {
      color: #ef4444;
    }
  `]
}) class AddEmployeeDialog {
  employeeForm: FormGroup;
  departments = departmentsMock;
  
  constructor(
    private fb: FormBuilder,
    public dialogRef: MatDialogRef<AddEmployeeDialog>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.employeeForm = this.fb.group({
      name: ['', Validators.required],
      employeeId: ['', Validators.required],
      department: ['', Validators.required],
      position: ['', Validators.required],
      phone: ['', [Validators.required, Validators.pattern(/^1[3-9]\d{9}$/)]],
      email: ['', [Validators.required, Validators.email]],
      gender: ['男'],
      birthDate: [null],
      hireDate: [new Date(), Validators.required],
      status: ['在职', Validators.required]
    });
  }
  
  onSubmit() {
    if (this.employeeForm.valid) {
      this.dialogRef.close(this.employeeForm.value);
    }
  }
}

// 模拟数据
const departmentsMock: Department[] = [
  { id: '1', name: '管理层', employeeCount: 5 },
  { id: '2', name: '设计部', employeeCount: 20 },
  { id: '3', name: '客户服务部', employeeCount: 15 },
  { id: '4', name: '财务部', employeeCount: 8 },
  { id: '5', name: '人力资源部', employeeCount: 5 }
];

// 生成模拟员工数据
const generateMockEmployees = (): Employee[] => {
  const statuses: EmployeeStatus[] = ['在职', '试用期', '离职'];
  const genders = ['男', '女'];
  const departments = departmentsMock.map(d => d.name);
  const positions = ['经理', '设计师', '客服专员', '财务专员', '人事专员', '助理'];
  const employees: Employee[] = [];
  
  for (let i = 1; i <= 30; i++) {
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    const hireDate = new Date();
    hireDate.setMonth(hireDate.getMonth() - Math.floor(Math.random() * 36));
    
    // 随机生成合同信息
    const contractEndDate = new Date(hireDate);
    contractEndDate.setFullYear(contractEndDate.getFullYear() + 1);
    
    // 判断合同是否即将到期（7天内）
    const today = new Date();
    const daysUntilExpiry = Math.ceil((contractEndDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
    const isExpiringSoon = daysUntilExpiry <= 7 && daysUntilExpiry >= 0;
    
    employees.push({
      id: `emp-${i}`,
      name: `员工${i}`,
      employeeId: `EMP${2023}${String(i).padStart(3, '0')}`,
      department: departments[Math.floor(Math.random() * departments.length)],
      position: positions[Math.floor(Math.random() * positions.length)],
      phone: `138${Math.floor(Math.random() * 100000000)}`,
      email: `employee${i}@example.com`,
      gender: genders[Math.floor(Math.random() * genders.length)],
      birthDate: new Date(1980 + Math.floor(Math.random() * 20), Math.floor(Math.random() * 12), Math.floor(Math.random() * 28) + 1),
      hireDate,
      status,
      avatar: `https://picsum.photos/seed/emp${i}/40/40`,
      contract: {
        id: `contract-${i}`,
        startDate: hireDate,
        endDate: contractEndDate,
        type: '劳动合同',
        isExpiringSoon
      },
      certificates: i % 3 === 0 ? [
        {
          id: `cert-${i}-1`,
          name: '身份证',
          type: '身份证件',
          number: `110101${Math.floor(Math.random() * 1000000000000000000)}`,
          issueDate: new Date(2010 + Math.floor(Math.random() * 10), Math.floor(Math.random() * 12), Math.floor(Math.random() * 28) + 1),
          expiryDate: new Date(2030 + Math.floor(Math.random() * 10), Math.floor(Math.random() * 12), Math.floor(Math.random() * 28) + 1)
        }
      ] : undefined
    });
  }
  
  return employees;
};

// 主组件
@Component({
  selector: 'app-assets',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    MatButtonModule,
    MatInputModule,
    MatSelectModule,
    MatDialogModule,
    MatTableModule,
    MatPaginatorModule,
    MatCheckboxModule,
    MatSnackBarModule,
    MatIconModule,
    MatTooltipModule,
    MatMenuModule
  ],
  templateUrl: './assets.html',
  styleUrl: './assets.scss'
}) export class Assets implements OnInit {
  // 暴露Math对象给模板使用
  readonly Math = Math;
  
  // 员工数据
  employees = signal<Employee[]>([]);
  filteredEmployees = signal<Employee[]>([]);
  selectedEmployees = signal<string[]>([]);
  
  // 搜索和筛选
  searchTerm = signal('');
  departmentFilter = signal('');
  statusFilter = signal('');
  
  // 分页
  pageSize = 10;
  pageIndex = 0;
  
  // 表格列
  displayedColumns: string[] = ['select', 'name', 'employeeId', 'department', 'position', 'phone', 'email', 'hireDate', 'status', 'contract', 'actions'];
  
  // 部门和状态选项
  departments = departmentsMock;
  statuses: EmployeeStatus[] = ['在职', '试用期', '离职'];
  
  constructor(
    private dialog: MatDialog,
    private snackBar: MatSnackBar
  ) {}
  
  ngOnInit() {
    // 加载模拟数据
    this.employees.set(generateMockEmployees());
    this.applyFilters();
  }
  
  // 应用筛选
  applyFilters() {
    let filtered = this.employees();
    
    // 搜索筛选
    if (this.searchTerm()) {
      const term = this.searchTerm().toLowerCase();
      filtered = filtered.filter(emp => 
        emp.name.toLowerCase().includes(term) ||
        emp.employeeId.toLowerCase().includes(term) ||
        emp.phone.includes(term) ||
        emp.email.toLowerCase().includes(term)
      );
    }
    
    // 部门筛选
    if (this.departmentFilter()) {
      filtered = filtered.filter(emp => emp.department === this.departmentFilter());
    }
    
    // 状态筛选
    if (this.statusFilter()) {
      filtered = filtered.filter(emp => emp.status === this.statusFilter());
    }
    
    this.filteredEmployees.set(filtered);
  }
  
  // 打开新增员工对话框
  openAddEmployeeDialog() {
    const dialogRef = this.dialog.open(AddEmployeeDialog, {
      width: '600px',
      maxWidth: '90vw',
      disableClose: true,
      panelClass: 'custom-dialog'
    });
    
    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        const newEmployee: Employee = {
          id: `emp-${Date.now()}`,
          ...result,
          avatar: `https://picsum.photos/seed/emp${Date.now()}/40/40`,
          contract: {
            id: `contract-${Date.now()}`,
            startDate: result.hireDate,
            endDate: new Date(result.hireDate),
            type: '劳动合同',
            isExpiringSoon: false
          }
        };
        
        // 更新合同结束日期（假设一年合同）
        if (newEmployee.contract) {
          newEmployee.contract.endDate.setFullYear(newEmployee.contract.endDate.getFullYear() + 1);
        }
        
        this.employees.update(emps => [newEmployee, ...emps]);
        this.applyFilters();
        this.showSuccessMessage('员工添加成功');
      }
    });
  }
  
  // 编辑员工
  editEmployee(employee: Employee) {
    // 在实际应用中，这里会打开编辑对话框
    this.showSuccessMessage('编辑功能待实现');
  }
  
  // 删除员工
  deleteEmployee(id: string) {
    if (confirm('确定要删除该员工吗？')) {
      this.employees.update(emps => emps.filter(emp => emp.id !== id));
      this.applyFilters();
      this.showSuccessMessage('员工删除成功');
    }
  }
  
  // 批量删除
  batchDelete() {
    if (this.selectedEmployees().length === 0) {
      this.showErrorMessage('请先选择要删除的员工');
      return;
    }
    
    if (confirm(`确定要删除选中的 ${this.selectedEmployees().length} 名员工吗？`)) {
      this.employees.update(emps => emps.filter(emp => !this.selectedEmployees().includes(emp.id)));
      this.selectedEmployees.set([]);
      this.applyFilters();
      this.showSuccessMessage('批量删除成功');
    }
  }
  
  // 导出数据
  exportData(format: 'excel' | 'pdf') {
    this.showSuccessMessage(`${format.toUpperCase()} 导出功能待实现`);
  }
  
  // 切换员工选择
  toggleEmployeeSelection(id: string) {
    this.selectedEmployees.update(selected => {
      if (selected.includes(id)) {
        return selected.filter(selectedId => selectedId !== id);
      } else {
        return [...selected, id];
      }
    });
  }
  
  // 全选/取消全选
  toggleSelectAll() {
    if (this.isAllSelected()) {
      this.selectedEmployees.set([]);
    } else {
      this.selectedEmployees.set(this.filteredEmployees().map(emp => emp.id));
    }
  }
  
  // 判断是否全选
  isAllSelected() {
    return this.selectedEmployees().length > 0 && 
           this.selectedEmployees().length === this.filteredEmployees().length;
  }
  
  // 切换员工状态
  changeEmployeeStatus(employee: Employee, newStatus: EmployeeStatus) {
    if (employee.status === newStatus) return;
    
    this.employees.update(emps => 
      emps.map(emp => 
        emp.id === employee.id ? { ...emp, status: newStatus } : emp
      )
    );
    this.applyFilters();
    this.showSuccessMessage(`员工状态已更新为${newStatus}`);
  }
  
  // 格式化日期
  formatDate(date: Date | string): string {
    if (!date) return '';
    const d = new Date(date);
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
  }
  
  // 显示成功消息
  showSuccessMessage(message: string) {
    this.snackBar.open(message, '关闭', {
      duration: 3000,
      verticalPosition: 'top',
      panelClass: 'success-snackbar'
    });
  }
  
  // 显示错误消息
  showErrorMessage(message: string) {
    this.snackBar.open(message, '关闭', {
      duration: 3000,
      verticalPosition: 'top',
      panelClass: 'error-snackbar'
    });
  }
  
  // 分页事件处理
  onPageChange(event: any) {
    this.pageIndex = event.pageIndex;
    this.pageSize = event.pageSize;
  }
}
