import { Component, OnInit, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {
  LoadingController,
  ModalController,
  ToastController,
} from '@ionic/angular';
import { HttpService } from '../../../services/http.service';
import { identityCodeValid } from '../../../services/utils';
import { AgreementComponent } from '../../login/agreement/agreement.component';
import * as Parse from 'parse';
import { NavComponent } from '../../../app/components/nav/nav.component';
import {
  AlertController,
  ionicStandaloneModules,
} from '../../ionic-standalone.modules';
import { UploadComponent } from '../../../app/components/upload/upload.component';

@Component({
  selector: 'app-certification',
  templateUrl: './certification.component.html',
  styleUrls: ['./certification.component.scss'],
  standalone: true,
  imports: [
    ...ionicStandaloneModules,
    FormsModule,
    NavComponent,
    UploadComponent,
  ],
})
export class CertificationComponent implements OnInit {
  @ViewChild('upload') upload!: UploadComponent;

  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;
  cardtype: 'regions' | 'cn' = 'cn'; // 身份证类型
  eduImage: string = '';

  constructor(
    private service: HttpService,
    public loadCtrl: LoadingController,
    private modalController: ModalController,
    private alertController: AlertController,
    private 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');
      if (this.isReal) {
        localStorage.setItem('profile', JSON.stringify(this.profile.toJSON()));
        this.secretIdCard = this.profile.get('idcard')?.slice(0, 6);
        this.secretName = this.profile.get('name')?.slice(0, 1);
      } else if (this.profile.get('cardtype') === 'regions') {
        this.cardtype = 'regions'
        this.name = this.profile.get('name');
        this.idCard = this.profile.get('idcard');
        this.eduImage = this.profile.get('eduImage')
        this.presentAlert('审核中',true);
      }
    }
  }
  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 submit() {
    if (!this.agreement) {
      this.presentToast('请先阅读且同意隐私协议', 1500, 'danger');
      return;
    }
    this.loading = await this.loadCtrl.create();
    this.loading.present();
    this.time && clearTimeout(this.time);
    this.time = setTimeout(async () => {
      this.name = this.name.trim();
      this.idCard = this.idCard.trim();
      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 = identityCodeValid(this.idCard);
      console.log(pass);
      if (!pass) {
        this.loading.dismiss();
        await this.presentToast(
          '认证失败，请填写真实的身份信息',
          1500,
          'danger'
        );
        return;
      }
      if (this.getAgeFromIdCard(this.idCard) < 18) {
        this.loading.dismiss();
        await this.presentToast(
          '根据平台规定，仅限满18周岁用户使用。',
          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, city } = res.data.result.IdCardInfor;
          this.anthProfile(sex, city);
          return;
        }
        this.loading.dismiss();
        await this.presentToast(
          '认证失败，请填写真实的身份信息',
          1500,
          'danger'
        );
      } else {
        this.loading.dismiss();
        await this.presentToast('认证失败', 1500, 'danger');
      }
    }, 500);
  }

  async anthProfile(sex?: string, city?: 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);
    // query.notEqualTo('user', Parse.User.current()?.id);
    // 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('cardtype', this.cardtype);
    if (this.cardtype === 'cn') {
      this.profile?.set('sex', sex);
      this.profile?.set('city', city);
      this.profile?.set('isCross', true);
      this.profile?.set(
        'birthdate',
        String(this.getAgeFromIdCard(this.idCard))
      );
      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);
      }
    } else {
      this.profile?.set('eduImage',this.eduImage)
      await this.profile?.save();
      if (this.profile?.id) {
        localStorage.setItem('profile', JSON.stringify(this.profile.toJSON()));
        this.loading.dismiss();
        this.presentAlert('提交成功，等待审核',true);
      }
    }
    Parse.User.current()?.set('agentLevel', {
      __type: 'Pointer',
        className: 'UserAgentLevel',
        objectId: '2fzw2QMceW',
    });
    await Parse.User.current()?.save();
  }

  getAgeFromIdCard(idCard: string): number {
    // 提取出生日期部分
    const birthDateStr = idCard.substring(6, 14);
    const year = parseInt(birthDateStr.substring(0, 4), 10);
    const month = parseInt(birthDateStr.substring(4, 6), 10);
    const day = parseInt(birthDateStr.substring(6, 8), 10);
    // 创建出生日期对象
    const birthDate = new Date(year, month - 1, day);
    // 获取当前日期
    const today = new Date();
    // 计算年龄
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    if (
      monthDiff < 0 ||
      (monthDiff === 0 && today.getDate() < birthDate.getDate())
    ) {
      age--;
    }
    return age;
  }

  async changeFile(e: any) {
    this.eduImage = e[0]?.url;
    console.log(this.eduImage);
  }
  async submitRegions() {
    if (!this.agreement) {
      this.presentToast('请先阅读且同意隐私协议', 1500, 'danger');
      return;
    }
    this.loading = await this.loadCtrl.create();
    this.loading.present();
    this.time && clearTimeout(this.time);
    this.time = setTimeout(async () => {
      this.name = this.name.trim();
      this.idCard = this.idCard.trim();
      console.log(this.name, this.idCard);
      if (!this.idCard || !this.name || !this.eduImage) {
        this.loading.dismiss();
        await this.presentToast('请填写完整信息', 1500, 'danger');
        return;
      }
      this.anthProfile();
    }, 500);
  }
  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();
  }
}
