import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {
  IonicModule,
  LoadingController,
  ModalController,
  ToastController,
} from '@ionic/angular';
import { HttpService } from '../../../services/http.service';
import * as utils from '../../../services/utils';
import { AgreementComponent } from '../../login/agreement/agreement.component';
import * as Parse from 'parse';
import { NavComponent } from '../../../app/components/nav/nav.component';

@Component({
  selector: 'app-certification',
  templateUrl: './certification.component.html',
  styleUrls: ['./certification.component.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, NavComponent],
})
export class CertificationComponent implements OnInit {
  name: string = '';
  idCard: string = '';
  title: string =
    '根据相关法律法规要求,用户需先进行实名认证，方可使用本平台。请尽快完成下方实名认证，本平台将对您的信息严格保密。';
  company: any = window.localStorage.getItem('company');
  isReal: boolean = false;
  loading: any;
  time: any; //节流
  secretName: any;
  secretIdCard: any;
  agreement: boolean = false;
  registerAgreement: any;
  profile?: Parse.Object;
  constructor(
    private service: HttpService,
    public loadCtrl: LoadingController,
    private modalController: ModalController,
    public toastController: ToastController
  ) {}

  ngOnInit() {
    this.getAgreement();
    this.getProfile();
  }
  getAgreement() {
    let Agreement = new Parse.Query('ContractAgreement');
    Agreement.equalTo('company', this.company);
    Agreement.equalTo('type', 'register');
    Agreement.first().then((res) => {
      console.log(res);
      this.registerAgreement = res;
    });
  }
  async getProfile() {
    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.isReal = this.profile.get('isCross');
      this.secretIdCard = this.profile.get('idcard')?.slice(0, 6);
      this.secretName = this.profile.get('name')?.slice(0, 1);
    }
  }
  async showAgreement() {
    const modal = await this.modalController.create({
      component: AgreementComponent,
      cssClass: 'my-custom-class',
      componentProps: {
        agreement: this.registerAgreement,
      },
    });
    return await modal.present();
  }

  async presentToast(title: string, time: number, color: string) {
    const toast = await this.toastController.create({
      message: title,
      duration: time,
      color: color,
    });
    toast.present();
  }

  async check() {
    this.loading = await this.loadCtrl.create();
    this.loading.present();
    this.time && clearTimeout(this.time);
    this.time = setTimeout(async () => {
      console.log(this.name, this.idCard);
      if (!this.idCard || this.idCard.length != 18 || !this.name) {
        this.loading.dismiss();
        await this.presentToast('格式错误', 1500, 'danger');
        return;
      }
      let pass = utils.fun.IdentityCodeValid(this.idCard);
      console.log(pass);
      if (!pass) {
        this.loading.dismiss();
        await this.presentToast(
          '认证失败，请填写真实的身份信息',
          1500,
          'danger'
        );
        return;
      }

      let res: any = await this.service.postAuth(
        this.company,
        this.idCard,
        this.name
      );
      if (res.code == 1) {
        let { isok } = res.data.result;
        console.log(isok);
        if (isok) {
          let { sex } = res.data.result.IdCardInfor;
          this.anthProfile(sex);
          return;
        }
        this.loading.dismiss();
        await this.presentToast(
          '认证失败，请填写真实的身份信息',
          1500,
          'danger'
        );
      } else {
        this.loading.dismiss();
        await this.presentToast('认证失败', 1500, 'danger');
      }
    }, 500);
  }

  async anthProfile(sex: string) {
    let user = Parse.User.current();
    let query = new Parse.Query('Profile');
    query.equalTo('idcard', this.idCard);
    query.equalTo('company', this.company);
    query.notEqualTo('isDeleted', true);
    let res = await query.first();
    if (res && res.id) {
      this.loading.dismiss();
      await this.presentToast('认证失败，该身份已被认证', 1500, 'danger');
      return;
    }
    user?.set('sex', sex);
    user?.set('idcard', this.idCard);
    user?.set('name', this.name);
    await user?.save();
    if (!this.profile?.id) {
      let obj = Parse.Object.extend('Profile');
      this.profile = new obj();
      this.profile?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.company,
      });
      this.profile?.set('user', {
        __type: 'Pointer',
        className: '_User',
        objectId: user?.id,
      });
      this.profile?.set('mobile', Parse.User.current()?.get('mobile'));
    }
    this.profile?.set('idcard', this.idCard);
    this.profile?.set('name', this.name);
    this.profile?.set('sex', sex);
    this.profile?.set('isCross', true);
    await this.profile?.save();
    if (this.profile?.id) {
      localStorage.setItem('profile', JSON.stringify(this.profile.toJSON()));
      this.loading.dismiss();
      this.isReal = true;
      await this.presentToast('认证成功', 1500, 'primary');
      setTimeout(() => {
        history.back();
      }, 1500);
    }
  }
}
