import { Component, OnInit, ViewChild } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { catchError } from 'rxjs/operators';
import { NzUploadChangeParam } from 'ng-zorro-antd/upload';
import { NzUploadModule } from 'ng-zorro-antd/upload';
import {
  FormControl,
  FormGroup,
  NonNullableFormBuilder,
  Validators,
} from '@angular/forms';
import { CommonCompModule } from '../common.modules';
import { textbookServer } from '../../../services/textbook';
import { AuthServr } from '../../../services/auth.service';
import { CaptchaComponent } from '../../../app/captcha/captcha.component';
import { NzMessageService } from 'ng-zorro-antd/message';
import Parse from 'parse';
@Component({
  selector: 'app-account-info',
  standalone: true,
  imports: [
    ReactiveFormsModule,
    CommonCompModule,
    CaptchaComponent,
    NzUploadModule,
  ],
  templateUrl: './account-info.component.html',
  styleUrls: ['./account-info.component.scss'],
})
export class AccountInfoComponent implements OnInit {
  user: Parse.Object = Parse.User.current()!;
  validateForm: FormGroup<{
    name: FormControl<string>; //姓名
    // mobile: FormControl<string>; //手机号
    email: FormControl<string>; //电子邮箱
    province: FormControl<string>; //省份
    unitType: FormControl<string>; //单位类型
    unit: FormControl<string>; //单位名称
    idcard: FormControl<string>; //身份证号
    identity: FormControl<string>; //用户类型
    file: FormControl<string>; //单位联系人认证文件
  }> = this.fb.group({
    name: ['', [Validators.required]],
    // mobile: ['', [Validators.required]],
    email: ['', [Validators.required]],
    province: ['', [Validators.required]],
    unitType: ['', [Validators.required]],
    unit: ['', [Validators.required]],
    idcard: ['', [Validators.required]],
    identity: ['', [Validators.required]],
    file: ['暂无', [Validators.required]],
  });
  nonRequired: any = {
    workPhone: '',
    branch: '',
    job: '',
  };
  mobile: string = '';

  //省份
  provinces: Array<string> = [
    '北京市',
    '天津市',
    '河北省',
    '山西省',
    '内蒙古自治区',
    '辽宁省',
    '吉林省',
    '黑龙江省',
    '上海市',
    '江苏省',
    '浙江省',
    '安徽省',
    '福建省',
    '江西省',
    '山东省',
    '河南省',
    '湖北省',
    '湖南省',
    '广东省',
    '广西壮族自治区',
    '海南省',
    '重庆市',
    '四川省',
    '贵州省',
    '云南省',
    '西藏自治区',
    '陕西省',
    '甘肃省',
    '青海省',
    '宁夏回族自治区',
    '新疆维吾尔自治区',
    '台湾省',
    '香港特别行政区',
    '澳门特别行政区',
  ];
  unitTypes: Array<string> = [
    '个体工商户',
    '企业公司',
    '国有机构或事业单位',
    '非营利组织或公益机构',
    '教育机构',
    '自由职业者或个人',
    '其他特定单位类型',
  ];
  identitys: Array<string> = [
    '国家级管理员',
    '省级教育行政部门',
    '合集管理员',
    '省属高校联系人',
    '教材评审组成员',
    '作者/教师/主编',
  ];
  constructor(
    public tbookSer: textbookServer,
    private fb: NonNullableFormBuilder,
    public router: Router,
    private authServr: AuthServr,
    private message: NzMessageService,
    private http: HttpClient
  ) {}

  ngOnInit() {
    if (Parse.User.current()?.id) {
      // this.validateForm.value.mobile = Parse.User.current()?.get('mobile');
      this.mobile = this.user.get('mobile');
      this.authProfile();
    } else {
      this.router.navigate(['user/login']);
    }
  }
  async authProfile() {
    let query = new Parse.Query('Profile');
    query.equalTo('user', Parse.User.current()?.id);
    query.notEqualTo('isDeleted', true);
    let r = await query.first();
    if (r?.id) {
      if (!r.get('verify')) {
        this.message.info('您已完成身份认证，即将跳转到管理后台');
        return;
      }
      this.validateForm = this.fb.group({
        name: [r.get('name'), [Validators.required]],
        // mobile: [Parse.User.current()?.get('mobile') || r.get('mobile'), [Validators.required]],
        email: [r.get('email'), [Validators.required]],
        province: [r.get('province'), [Validators.required]],
        unitType: [r.get('unitType'), [Validators.required]],
        unit: [r.get('unit'), [Validators.required]],
        idcard: [r.get('idcard'), [Validators.required]],
        identity: [r.get('identity'), [Validators.required]],
        file: [r.get('file'), [Validators.required]],
      });
      this.nonRequired = {
        workPhone: r.get('workPhone'),
        branch: r.get('branch'),
        job: r.get('job'),
      };
    }
  }
  submitForm(): void {
    console.log(this.validateForm.value);
    if (this.validateForm.valid) {
      let {
        name,
        // mobile,
        email,
        province,
        unitType,
        unit,
        idcard,
        identity,
        file,
      } = this.validateForm.value;
  
      let a =
        /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/;
      if (!String(idcard).match(a)) {
        this.message.error('身份证格式错误');
        return;
      }
      let params = {
        name,
        mobile: this.mobile,
        email,
        province,
        unitType,
        unit,
        idcard,
        identity,
        file,
        workPhone: this.nonRequired.workPhone,
        branch: this.nonRequired.branch,
        job: this.nonRequired.job,
      };
      this.profileSave(params);
    } else {
      this.message.warning('请填写完整的信息');
      Object.values(this.validateForm.controls).forEach((control) => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  async profileSave(params: any) {
    console.log(params);
    let query = new Parse.Query('Profile');
    query.equalTo('user', Parse.User.current()?.id);
    query.notEqualTo('isDeleted', true);
    let profile = await query.first();
    if (!profile?.id) {
      let obj = Parse.Object.extend('Profile');
      profile = new obj();
    }
    profile?.set('user', Parse.User.current()?.toPointer());
    profile?.set('company', {
      __type: 'Pointer',
      className: 'Company',
      objectId: this.tbookSer.company,
    });
    profile?.set('name', params.name);
    profile?.set('email', params.email);
    profile?.set('mobile', params.email);
    profile?.set('province', params.province);
    profile?.set('unitType', params.unitType);
    profile?.set('unit', params.unit);
    profile?.set('idcard', params.idcard);
    profile?.set('identity', params.identity);
    profile?.set('file', params.file);
    profile?.set('workPhone', params.workPhone);
    profile?.set('branch', params.branch);
    profile?.set('job', params.job);
    profile?.set('verify', true);
    let res = await profile?.save();
    this.authServr.profileVerify()
  }
  handleChange(info: NzUploadChangeParam): void {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      this.message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      this.message.error(`${info.file.name} file upload failed.`);
    }
  }
}
