import {Component, ElementRef, ViewChild} from '@angular/core';
import {ToastController} from '@ionic/angular';
import {UserService} from 'src/modules/user/service-user/user.service';
// import {FmodeChatCompletion} from "fmode-ng";

import {
  AbstractControl, AsyncValidatorFn,
  FormBuilder,
  FormControl,
  FormGroup,
  NonNullableFormBuilder, ValidationErrors,
  ValidatorFn,
  Validators
} from "@angular/forms";
import Parse from 'parse';
import {AlertController} from "@ionic/angular";
import {Router} from "@angular/router";

Parse.serverURL = "https://web2023.fmode.cn/parse" // 配置服务器地址
Parse.initialize("dev") // 配置应用名称


@Component({
  selector: 'app-page-mine',
  templateUrl: './page-mine.component.html',
  styleUrls: ['./page-mine.component.scss']
})
export class PageMineComponent {
  account = this.userServ.currentUser.account;
  password = this.userServ.currentUser.password;

  isFirstRegister = this.userServ.currentUser.isFirstRegister;
  private readonly result: Promise<Parse.Object<Parse.Attributes>> | undefined;
  selectedTabIndex: number = 0; // 默认选中第一个标签页
  currentUser = Parse.User.current();


  constructor(private fb: FormBuilder, private toastCtrl: ToastController, public userServ: UserService, private alertCtrl: AlertController, private router: Router) {
    this.myForm = this.fb.group({
      phoneNumber: new FormControl('', [Validators.required, Validators.pattern(/^\d{10}$/)]),
      name: new FormControl('', [Validators.required]),
      employmentStatus: new FormControl('', Validators.required),
      educationLevel: new FormControl('', Validators.required),
      gender: new FormControl('', Validators.required),
    });

    this.validateForm = this.fb.group({

      oldPassword: '',
      // ['', [Validators.required, Validators.pattern('^(?=.*[a-zA-Z])(?=.*[0-9]).{6,10}$')]],
      newPassword: ['', [Validators.required, Validators.pattern('^(?=.*[a-zA-Z])(?=.*[0-9]).{6,10}$')]],
      removePassword: '',

    });


    if (this.isFirstRegister === 1) {
      this.selectedTabIndex = this.getTabIndexFromUrl();
    } else {

    }
    console.log(this.currentUser)
    console.log(this.myForm.valid)
  }

  ngOnInit() {

  }

  validateForm: FormGroup;
  myForm: FormGroup;

  // 完善信息


  async submitForm() {

    if (this.myForm.valid) {
      const params = {
        phoneNumber: this?.myForm.controls['phoneNumber'].value,
        employmentStatus: this?.myForm.controls['employmentStatus'].value,
        educationLevel: this?.myForm.controls['educationLevel'].value,
        gender: this?.myForm.controls['gender'].value,
        name: this?.myForm.controls['name'].value,
      };
      const user: any = Parse.User.current();
      user.set("phoneNumber", params.phoneNumber);
      user.set("employmentStatus", params.employmentStatus)
      user.set("educationLevel", params.educationLevel)
      user.set("gender", params.gender)
      user.set("name", params.name);
      user.save().then((updatedUser: any) => {
        console.log("---", updatedUser)
      }).catch((error: any) => {
        console.log("---", error)
      })
    }
    this.current += 1;
  }


  async logout() {
    localStorage.removeItem("USER_AUTH")
    let toast = await this.toastCtrl.create({
      message: "登出成功",
      position: "top",
      duration: 500
    })
    await toast.present();
  }

//按钮弹出框组件
  forgetPassword = false;
  changePassword = false;
  removePassword = false;
  actionTypeMap: {
    [key: string]: boolean
  }
    = {
    changePassword: false,
    forgetPassword: false,
    removePassword: false,
  }


  actionChange(key: string
  ):
    void {
    console.log(this.actionTypeMap[key])
    this.actionTypeMap[key] = true
  }

  inActionChange(key: string):
    void {
    this.actionTypeMap[key] = false;
  }

//数据获取逻辑
  async alertError(err: string | undefined) {
    const alert = await this.alertCtrl.create({
      header: '密码修改失败',
      subHeader: '请检查新旧密码是否正确',
      message: err,
      buttons: ['好的'],
    });

    await alert.present();
  }

  async searchObject(): Promise<boolean> {
    if (this.result) {
      if (this.password === this.validateForm.controls['oldPassword'].value && this.validateForm.controls['newPassword'].valid && this.validateForm.controls['oldPassword'].value != this.validateForm.controls['newPassword'].value) {
        (await this.result).set('password', this.validateForm.controls['newPassword'].value);
        // 保存修改后的密码
        await this.logout();
        await (await this.result).save();
        return true;
      } else {
        await this.alertError("密码错误获取新旧密码相同")
        return false;
      }
    } else {
      return false;
    }
  }

  async removeSearch() {
    if (this.result) {
      if (this.password == this.validateForm.controls['removePassword'].value) {
        (await this.result).destroy().then(() => {
          this.logout();
          return true;
        }).catch(() => {
          this.alertError("数据删除失败,密码错误")
          return false;
        });
      }
    }
    return true;
  }

//显示不显密码
  passwordVisible = false;


  async handleChange(key: string):
    Promise<void> {
    //修改密码逻辑
    if (await this.searchObject()
    ) {
      this.actionTypeMap[key] = false;
    } else {
      this.alertError("密码错误")
    }
  }

  async handleRemove(key: string): Promise<void> {
    //删除密码逻辑
    if (await this.removeSearch()) {
      this.actionTypeMap[key] = false;
    }
  }

  handleForget(): void {
    //忘记密码逻辑
    this.forgetPassword = false;
  }


  //跳转到设置的方法
  getTabIndexFromUrl(): number {
    const fragment = this.router.parseUrl(this.router.url).fragment;
    console.log(fragment)
    if (fragment === 'setting') {
      return 2
    }
    return 0;
  }

  //设置页面跳转next-preview的逻辑
  current = 0;

  index = 'First-content';

  pre(): void {
    this.current -= 1;
    // this.changeContent();
  }

  next(): void {
    this.current += 1;
    // this.changeContent();
  }

  done(): void {
    this.router.navigate(['/home/minterviews'])
  }


  // 聊天框逻辑
  messages = [
    {avatar: 'assets/images/page-mine/myAvatar.png', content: 'Hello', isReceived: false},
    // 这是左边的内容

    {avatar: 'assets/images/page-mine/myAvatar.png', content: 'Hi', isReceived: true},
    //  这是右边的内容
  ];


  inputMessages: any[] = [];


  inputText = '';

  @ViewChild('chatMessages') chatMessages!: ElementRef;
  newMessage: string = ""

  sendMessage() {
    if (this.inputText.trim() !== '') {
      const newMessage = {
        avatar: 'assets/images/page-mine/myAvatar.png',
        content: this.inputText,
        isReceived: true,
      };
      let messageList = [
        {role: "user", content: "填写你发送过的历史消息：可用于Prompt定义AI扮演的角色细节"},
        {role: "assistant", content: "填写AI回复的历史消息"},
        {role: "user", content: "FmodeAiTest测试问题"}, // 填写你要发送的消息
      ]
      this.messages.push(newMessage);
      this.inputText = '';
      // let completion = new FmodeChatCompletion(messageList);
      // completion.sendCompletion().subscribe((message: any) => {
      //   this.newMessage = message;
      //   console.log(newMessage)
      //   console.log(this.messages)
      // })

      // Scroll to the bottom of the chat window
      setTimeout(() => {
        this.chatMessages.nativeElement.scrollTop = this.chatMessages.nativeElement.scrollHeight;
      }, 0);
    }
  }


}


