import { Component, OnInit, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {
  AlertController,
  LoadingController,
  ModalController,
  ToastController,
} from '@ionic/angular';
import { AgreementComponent } from '../../login/agreement/agreement.component';
import { NavComponent } from '../../../app/components/nav/nav.component';
import { LiveService } from '../../../services/live.service';
import * as Parse from 'parse';
import { UploadComponent } from '../../../app/components/upload/upload.component';
import { Router } from '@angular/router';
import { AuthService } from '../../../services/auth.service';
import { ionicStandaloneModules } from '../../ionic-standalone.modules';
interface FormGroup {
  mobile: string;
  name: string;
  avatar: string;
  nickname: string;
  photo: Array<any>;
  video: string;
  sex?: string;
  remark: string;
}
@Component({
  selector: 'app-anchor',
  templateUrl: './anchor.component.html',
  styleUrls: ['./anchor.component.scss'],
  standalone: true,
  imports: [...ionicStandaloneModules, FormsModule, NavComponent, UploadComponent],
})
export class AnchorComponent implements OnInit {
  @ViewChild('upload') upload!: UploadComponent;
  profile?: Parse.Object; //身份信息
  user: Parse.Object = Parse.User.current()!;
  infoCollection?:Parse.Object
  formData: FormGroup = {
    mobile: '',
    name: '',
    avatar: '',
    nickname: '',
    photo: [],
    video: '',
    // sex: '',
    remark: '',
  };
  loading: any;
  agreement: boolean = false;
  registerAgreement: any;
  company: any;
  locadingComplete: boolean = false;
  constructor(
    private modalController: ModalController,
    public loadingCtrl: LoadingController,
    private toastController: ToastController,
    private authServ: AuthService,
    private alertController: AlertController,
    private router: Router,
    private liveService: LiveService
  ) {
    this.company = liveService.company;
  }
  ngOnInit() {
    this.getAgreement();
    this.getProfile();
  }
  async getProfile() {
    this.loading = await this.loadingCtrl.create({
      message: '加载中',
    });
    this.loading.present();
    if (!this.liveService.profile) {
      this.liveService.alertTips('请先完成实名认证', '提示', () => {
        this.router.navigate(['/user/certification'], { replaceUrl: true });
      });
      return;
    }
    let uid = Parse.User.current()?.id;
    let query = new Parse.Query('Profile');
    query.equalTo('user', uid);
    query.notEqualTo('isDeleted', true);
    this.profile = await query.first();
    if (this.profile?.id) {
      this.user = this.profile.get('user');
      this.formData.mobile = this.profile?.get('mobile');
      this.formData.name = this.profile?.get('name');
      this.formData.nickname = this.user?.get('nickname');
      this.formData.remark = this.profile?.get('remark');
      this.formData.avatar =
        this.user?.get('avatar') ||
        'https://file-cloud.fmode.cn/DXNgcD6zo6/20221202/j6p8kb034039.png';
    }
    let queryInfo = new Parse.Query('InfoCollection');
    queryInfo.equalTo('user', this.user?.id);
    queryInfo.notEqualTo('isDeleted', true);
    this.infoCollection = await queryInfo.first();
    if (this.infoCollection?.id) {
      this.formData.photo = this.infoCollection?.get('info')?.photo;
      this.formData.video = this.infoCollection?.get('info')?.video;
    }
    this.loading.dismiss();
    if(this.infoCollection?.get('isVerify') == '200' || this.infoCollection?.get('isVerify') == '300'){
      this.presentAlert(this.infoCollection?.get('isVerify') == '200' ? '审核已通过' : '审核未通过')
    }
    this.locadingComplete = true;
  }
  getAgreement() {
    let Agreement = new Parse.Query('ContractAgreement');
    Agreement.equalTo('company', this.company);
    Agreement.equalTo('type', 'live');
    Agreement.first().then((res) => {
      console.log(res);
      this.registerAgreement = res;
    });
  }
  onChangeFile(e: any, file: string, type: string) {
    let urls = e?.map((item: any) => item.url);
    if(file == 'video' || file == 'photo' || file == 'avatar'){
      this.formData[file] = type == 'array' ? urls : urls[0];
    }
  }
  async showAgreement() {
    const modal = await this.modalController.create({
      component: AgreementComponent,
      cssClass: 'my-custom-class',
      componentProps: {
        agreement: this.registerAgreement,
      },
    });
    return await modal.present();
  }

  async saveEdit() {
    if(!this.agreement){
      const toast = await this.toastController.create({
        message: `请先勾选${this.registerAgreement?.get('title')}`,
        color: 'warning',
        duration: 1500,
      });
      toast.present();
      return
    }
    this.loading = await this.loadingCtrl.create({
      message: '正在保存修改',
    });
    this.loading.present();
    let data:any = this.formData;
    for (const key in data) {
      if (!data[key] || (key == 'photo' && !data[key].length)) {
        console.log(key);
        console.log(data[key]);
        this.loading.dismiss();
        const toast = await this.toastController.create({
          message: '请填写完整信息',
          color: 'warning',
          duration: 1500,
        });
        toast.present();
        return
      }
    }
    console.log(this.formData);
    let user = Parse.User.current();
    if (!user?.id) {
      this.loading.dismiss();
      const alert = await this.alertController.create({
        header: '提示',
        message: '登录信息已过期，请重新登录',
        buttons: [
          {
            text: '好的',
            role: 'confirm',
            handler: () => {
              this.authServ.logout();
            },
          },
        ],
      });
      await alert.present();
      return;
    }
    user.set('avatar', this.formData.avatar);
    user.set('nickname', this.formData.nickname);
    // user.set('sex', this.formData.sex);
    await user.save();
    if (!this.profile?.id) {
      let obj = Parse.Object.extend('Profile');
      this.profile = new obj();
      this.profile?.set('user', Parse.User.current()?.toPointer());
      this.profile?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.authServ.company,
      });
    }
    this.profile?.set('mobile', Parse.User.current()?.get('mobile'));
    // this.profile?.set('sex', this.formData.sex);
    this.profile?.set('remark', this.formData.remark);
    await this.profile?.save();
    if(!this.infoCollection?.id){
      let obj = Parse.Object.extend('InfoCollection');
      this.infoCollection = new obj();
      this.infoCollection?.set('user', Parse.User.current()?.toPointer());
      this.infoCollection?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.authServ.company,
      });
    }
    let jsonData = {
      photo:this.formData.photo,
      video:this.formData.video,
    }
    this.infoCollection?.set('info', jsonData);
    this.infoCollection?.set('isVerify','101')
    await this.infoCollection?.save();
    this.loading.dismiss();
    this.getProfile();
    this.presentAlert('提交成功');
  }

  async presentAlert(msg: string,isBack?:boolean) {
    const alert = await this.alertController.create({
      header: '提示',
      message: msg,
      buttons: [
        {
          text: '好的',
          role: 'confirm',
          handler: () => {
            isBack && history.back();
          },
        },
      ],
    });
    await alert.present();
  }
}
