import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { CharacterService } from '../services/character.service';
import { LoadingController } from '@ionic/angular';

@Component({
  selector: 'app-character-creator',
  templateUrl: './character-creator.page.html',
  styleUrls: ['./character-creator.page.scss'],
  standalone: true,
  imports: [CommonModule, IonicModule, FormsModule, ReactiveFormsModule]
})
export class CharacterCreatorPage {
  characterForm!: FormGroup;
  selectedImage: string | ArrayBuffer | null = null;

  constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private characterService: CharacterService,
    private loadingController: LoadingController
  ) {
    this.initForm();
  }

  private initForm() {
    this.characterForm = this.formBuilder.group({
      name: ['', Validators.required],
      gender: ['male', Validators.required],
      appearance: ['', [Validators.required, Validators.minLength(20)]],
      personality: ['', [Validators.required, Validators.minLength(20)]]
    });
  }

  onFileSelected(event: Event) {
    const file = (event.target as HTMLInputElement).files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = () => {
        this.selectedImage = reader.result; // 将图片数据存储到 selectedImage
      };
      reader.readAsDataURL(file);
    }
  }

  async generateCharacter() {
    if (this.characterForm.valid) {
      const loading = await this.loadingController.create({
        message: '正在创建角色...'
      });
      await loading.present();

      try {
        const characterData = this.characterForm.value;
        characterData.avatar = this.selectedImage; // 将上传的图片作为角色头像
        const character = await this.characterService.createCharacterAgent({
          ...characterData,
          id: Date.now().toString()
        }).toPromise();

        await loading.dismiss();
        this.router.navigate(['/character']);
      } catch (error) {
        console.error('创建角色失败:', error);
        await loading.dismiss();
      }
    }
  }
}