import { Component, Inject } 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 { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { MatIconModule } from '@angular/material/icon';

interface User {
  id: string;
  username: string;
  realName: string;
  email: string;
  phone: string;
  role: string;
  department: string;
  status: 'active' | 'inactive';
  createdAt: string;
  lastLogin: string;
}

@Component({
  selector: 'app-user-dialog',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatButtonModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatDatepickerModule,
    MatNativeDateModule,
    MatIconModule
  ],
  templateUrl: './user-dialog.html',
  styleUrl: './user-dialog.scss'
})
export class UserDialogComponent {
  user: User;
  isEditMode: boolean;
  roles: string[] = ['超级管理员', '客服', '设计师', '组长', '财务', '人事'];
  departments: string[] = ['管理层', '客户服务部', '设计部', '财务部', '人力资源部', '行政部'];
  statuses: { value: string; label: string }[] = [
    { value: 'active', label: '激活' },
    { value: 'inactive', label: '禁用' }
  ];

  constructor(
    public dialogRef: MatDialogRef<UserDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: User
  ) {
    this.isEditMode = !!data.id;
    this.user = {
      id: data.id || '',
      username: data.username || '',
      realName: data.realName || '',
      email: data.email || '',
      phone: data.phone || '',
      role: data.role || '',
      department: data.department || '',
      status: data.status || 'active',
      createdAt: data.createdAt || new Date().toISOString().split('T')[0],
      lastLogin: data.lastLogin || ''
    };
  }

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

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

  isFormValid(): boolean {
    // 验证用户名
    if (!this.user.username.trim() || this.user.username.length < 3) {
      alert('用户名至少需要3个字符');
      return false;
    }

    // 验证姓名
    if (!this.user.realName.trim()) {
      alert('请输入真实姓名');
      return false;
    }

    // 验证邮箱
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!emailRegex.test(this.user.email)) {
      alert('请输入有效的邮箱地址');
      return false;
    }

    // 验证手机号
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(this.user.phone)) {
      alert('请输入有效的手机号码');
      return false;
    }

    // 验证角色和部门
    if (!this.user.role || !this.user.department) {
      alert('请选择角色和部门');
      return false;
    }

    return true;
  }

  generateRandomPassword(): void {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()';
    let password = '';
    for (let i = 0; i < 12; i++) {
      password += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    alert(`生成的随机密码：${password}\n请妥善保存！`);
  }

  onRoleChange(): void {
    // 超级管理员只能属于管理层
    if (this.user.role === '超级管理员') {
      this.user.department = '管理层';
    }
  }
}