import { Input, OnInit } from '@angular/core';
import { Component } from '@angular/core';
import { IonHeader, IonToolbar, IonTitle, IonContent, IonCard, IonCardContent, IonButton, IonCardHeader, IonCardTitle, IonCardSubtitle, ModalController, IonInput, IonItem, IonSegment, IonSegmentButton, IonLabel } from '@ionic/angular/standalone';
import { CloudUser } from 'src/lib/ncloud';

@Component({
  selector: 'app-modal-user-edit',
  templateUrl: './modal-user-edit.component.html',
  styleUrls: ['./modal-user-edit.component.scss'],
  standalone: true,
  imports: [IonHeader, IonToolbar, IonTitle, IonContent, 
    IonCard,IonCardContent,IonButton,IonCardHeader,IonCardTitle,IonCardSubtitle,
    IonInput,IonItem,
    IonSegment,IonSegmentButton,IonLabel,
  ],
})
export class ModalUserEditComponent  implements OnInit {

  currentUser:CloudUser|undefined
  userData:any = {}
  userDataChange(key:string,ev:any){
    let value = ev?.detail?.value
    if(value){
      this.userData[key] = value
    }
  }
  constructor(private modalCtrl:ModalController) { 
    this.currentUser = new CloudUser();
    this.userData = this.currentUser.data;
  }

  ngOnInit() {}

  async save(){
    Object.keys(this.userData).forEach(key=>{
      if(key=="age"){
        this.userData[key] = Number(this.userData[key])
      }
    })

    this.currentUser?.set(this.userData)
    await this.currentUser?.save()
    this.modalCtrl.dismiss(this.currentUser,"confirm")
  }
  cancel(){
    this.modalCtrl.dismiss(null,"cancel")

  }
}
// 导出一个异步函数，用于打开用户编辑模态框并返回编辑后的用户信息
export async function openUserEditModal(modalCtrl: ModalController): Promise<CloudUser | null> {
  
  // 创建模态框实例，指定要显示的组件和模态框的高度设置
  const modal = await modalCtrl.create({
    component: ModalUserEditComponent, // 指定模态框中要显示的组件
    breakpoints: [0.7, 1.0], // 设置模态框的可调整高度的断点
    initialBreakpoint: 1.0 // 设置模态框初始显示的高度为 70%
  });

  // 显示模态框
  modal.present();

  // 等待模态框关闭，并获取关闭时传递的数据和角色
  const { data, role } = await modal.onWillDismiss();

  // 如果模态框是通过确认操作关闭，返回传递的数据
  if (role === 'confirm') {
    return data; // 返回用户编辑后的数据
  }

  // 如果模态框是通过取消或其他方式关闭，返回 null
  return null;
}