import { Component, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { CloudSeUser } from 'src/lib/cloudSeuser';  // 引入CloudSeUser类
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-page-edit',
  templateUrl: './page-edit.component.html',
  styleUrls: ['./page-edit.component.scss'],
  imports: [IonicModule, FormsModule],
  standalone: true,
})
export class PageEditComponent implements OnInit {

  // 初始化表单字段
  name: string = '';
  email: string = '';
  phone: string = '';
  age: number | null = null;
  gender: string = '';
  height: number | null = null;
  weight: number | null = null;
  activityLevel: string = '';
  dietPreference: string = '';
  dietGroup: string = '';
  avatar: string | null = null;
  allergies: string = '';

  nameInput(ev: any) {
    this.name = ev.detail.value;
  }
  emailInput(ev: any) {
    this.email = ev.detail.value;
  }
  phoneInput(ev: any) {
    this.phone = ev.detail.value;
  }
  ageInput(ev: any) {
    this.age = ev.detail.value;
  }
  genderInput(ev: any) {
    this.gender = ev.detail.value;
  }
  heightInput(ev: any) {
    this.height = ev.detail.value;
  }
  weightInput(ev: any) {
    this.weight = ev.detail.value;
  }
  activityLevelInput(ev: any) {
    this.activityLevel = ev.detail.value;
  }
  dietPreferenceInput(ev: any) {
    this.dietPreference = ev.detail.value;
  }
  dietGroupInput(ev: any) {
    this.dietGroup = ev.detail.value;
  }
  avatarInput(ev: any) {
    this.avatar = ev.detail.value;
  }
  allergiesInput(ev: any) {
    this.allergies = ev.detail.value;
  }


  // 正则表达式
  emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
  phonePattern = /^[0-9]{10,15}$/;
  heightPattern = /^[1-9][0-9]{1,2}$/;
  weightPattern = /^[1-9][0-9]{1,2}$/;

  cloudSeUser: CloudSeUser;  // 引入CloudSeUser实例

  constructor(private modalCtrl: ModalController) {
    this.cloudSeUser = new CloudSeUser();  // 实例化CloudSeUser
  }

  ngOnInit(): void {
    this.loadUserData();  // 页面初始化时加载用户数据
  }

  // 从 seUser 表加载当前用户数据
  async loadUserData() {
    try {
      const userData = await this.cloudSeUser.getCurrentUserInfo();
      if (userData) {
        // 通过 get() 方法获取 CloudSeUser 中的数据
        this.name = userData.get('name') || '';  
        this.email = userData.get('email') || '';  
        this.phone = userData.get('phone') || '';  
        this.age = userData.get('age') || null;  
        this.gender = userData.get('gender') || '';  
        this.height = userData.get('height') || null;  
        this.weight = userData.get('weight') || null;  
        this.activityLevel = userData.get('activityLevel') || '';  
        this.dietPreference = userData.get('dietPreference') || '';  
        this.dietGroup = userData.get('dietGroup') || '';  
        this.avatar = userData.get('avatar') || null;  
        this.allergies = userData.get('allergies') || '';  
      }
    } catch (error) {
      console.error('加载用户数据失败', error);
    }
  }

  // 取消操作，关闭页面
  cancel() {
    this.modalCtrl.dismiss();
  }

  // 确认操作，提交用户数据
  async confirm() {
    // 验证表单内容是否完整
    if (!this.name || !this.email || !this.phone || !this.age || !this.gender || !this.height || !this.weight || !this.dietPreference || !this.dietGroup) {
      alert("请确保所有必填项已填写！");
      return;
    }

    const userData = {
      name: this.name,
      email: this.email,
      phone: this.phone,
      age: Number(this.age),
      gender: this.gender,
      height: Number(this.height),  // 转换 height 为 Number
      weight: Number(this.weight),  // 转换 weight 为 Number
      activityLevel: this.activityLevel,
      dietPreference: this.dietPreference,
      dietGroup: this.dietGroup,
      avatar: this.avatar,
      allergies: this.allergies
    };
    try {
      // 判断是否已有用户数据，如果存在则更新，否则创建新用户
      const userDataFromServer = await this.cloudSeUser.getCurrentUserInfo();
      if (userDataFromServer) {
        // 如果已有数据，执行更新
        const updatedUser = await this.cloudSeUser.updateUserInfo(userData);
        if (updatedUser) {
          console.log("用户信息更新成功");
          this.modalCtrl.dismiss();  // 更新成功后关闭页面
        } else {
          alert("更新失败，请稍后再试");
        }
      } else {
        // 如果没有用户数据，执行保存（创建新用户）
        const newUser = await this.cloudSeUser.saveUserInfo(userData);
        if (newUser) {
          console.log("新用户信息保存成功");
          this.modalCtrl.dismiss();  // 保存成功后关闭页面
        } else {
          alert("保存失败，请稍后再试");
        }
      }
    } catch (error) {
      console.error("保存用户数据时出错", error);
      alert("保存数据时出错，请稍后再试");
    }
  }

  // 上传头像
  uploadAvatar() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';

    input.onchange = (event: any) => {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e: any) => {
          this.avatar = e.target.result;
        };
        reader.readAsDataURL(file);
      }
    };

    input.click();
  }
}
