import { Component, Input, OnInit } from '@angular/core';
import { IonicModule } from '@ionic/angular';
import { IonButton, IonContent, IonIcon, IonInput, ModalController } from '@ionic/angular/standalone';
import { CloudUser } from 'src/lib/ncloud';
import { addIcons } from 'ionicons';
import { arrowBackOutline, logoTux, logoWechat, phonePortraitOutline } from 'ionicons/icons';
import { FormsModule, } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
addIcons({ arrowBackOutline, logoWechat, phonePortraitOutline, logoTux });

@Component({
  selector: 'app-modal-user-login-main',
  templateUrl: './modal-user-login-main.component.html',
  styleUrls: ['./modal-user-login-main.component.scss'],
  standalone: true,
  imports: [IonContent, IonIcon, IonButton, FormsModule, IonInput],
})
export class ModalUserLoginMainComponent implements OnInit {
  phoneNumber: string = "";
  verCode: string = "";
  isVerCodeEnabled: boolean = false;
  isLoginButtonEnabled: boolean = false;
  trueVerCode: string = '';
  username: string = "";
  password: string = "";
  @Input() loginType: string = '';
  /**
   * @置顶函数
   */
  constructor(private modalCtrl: ModalController, private http: HttpClient) { }
  ngOnInit() { }
  goBack() {
    this.modalCtrl.dismiss(null, "cancel");
  }
  /**
   * @手机号登录页面功能函数
   */
  onPhoneNumberChange() {
    if (this.phoneNumber.length == 11) {
      this.isVerCodeEnabled = true;
      console.log("手机号码长度:" + this.phoneNumber.length + ", 成功")
    }
    else {
      this.isVerCodeEnabled = false;
      console.log("手机号码长度:" + this.phoneNumber.length + ", 失败")
    }
  }
  onVerCodeChange() {
    if (this.verCode.length >= 4) {
      this.isLoginButtonEnabled = true;
      console.log("验证码长度:" + this.verCode.length + ", 成功")
    }
    else {
      this.isLoginButtonEnabled = false;
      console.log("验证码长度:" + this.verCode.length + ", 失败")
    }
  }
  getVerCode() {
    //随机生成四位数的验证码
    this.trueVerCode = (Math.floor(Math.random() * 9000) + 1000).toString();
    console.log("获取验证码成功" + this.trueVerCode);
    const apiUrl = `http://api.smsbao.com/sms?u=peppa&p=94d5a383c32c4d85bfbfc2599e64a8dc&m=${this.phoneNumber}&c=${encodeURIComponent("【衣靠】您的验证码是" + this.trueVerCode)}`;
    console.log("请求地址:" + apiUrl);
    this.http.get(apiUrl).subscribe(response => {
      if (response === '0') {
        console.log("短信发送成功");
        // 处理登录成功逻辑
      } else {
        console.error("短信发送失败", response);
      }
    }, error => {
      console.error("请求失败", error);
    });
  }
  phoneToHide(phone: string): string {
    //将手机号隐藏中间四位数字，只显示前三位和后四位
    phone = phone.replace(/(\d{3})\d*(\d{4})/, '$1****$2');
    return phone;
  }
  async signByPhone() {
    console.log("登录被点击：手机号登录");
    let user: any = new CloudUser();
    user.set({ phone: this.phoneNumber, name: this.phoneToHide(this.phoneNumber), })
    console.log(user.data)
    user = await user.signByPhoneNumber(this.phoneNumber, this.verCode, this.trueVerCode, this.username, this.password, user.data);
    if (user?.id) {
      console.log("登录成功，关闭模态loginByUsername");
      this.modalCtrl.dismiss(user, "confirm")
      console.log("loginMain传递信息如下：")
      console.log(user)
      console.log("已关闭")
    } else {
      console.log("登录失败");
    }
  }
  /**
   * @用户名登录页面功能函数
   */
  async loginByUsername() {
    console.warn("-------------------------");
    console.warn("登录被点击：用户尝试使用用户名登录");
    if (!this.username || !this.password) {
      console.error("请输入完整用户名和密码！")
      return
    }
    let user: any = new CloudUser();
    await user.loginByUsername(this.username, this.password);
    console.log("已收到验证结果，如下：");
    console.log(user);
    if (user?.id) {
      console.log("登录成功，关闭模态loginByUsername");
      this.modalCtrl.dismiss(user, "confirm")
      console.log("loginMain传递信息如下：")
      console.log(user)
      console.log("loginMain模态已关闭")
    } else {
      console.log("登录失败");
    }
    console.warn("loginMain模态已关闭");
    console.warn("-------------------------")
  }
}

export async function openUserLoginMainModal(modalCtrl: ModalController, loginType: string): Promise<CloudUser | null> {
  const modal = await modalCtrl.create({
    component: ModalUserLoginMainComponent,
    componentProps: {
      loginType: loginType
    },
  });
  await modal.present();

  const { data, role } = await modal.onWillDismiss();

  if (role === 'confirm') {
    return data;
  }
  return null;
}