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 { NzUploadModule } from 'ng-zorro-antd/upload';
import { NzModalModule } from 'ng-zorro-antd/modal';
import { NzModalService } from 'ng-zorro-antd/modal';
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 { provinces } from '../../../services/provinces';
import { CompUploadComponent } from '../../../app/comp-upload/comp-upload.component';
import Parse from 'parse';
@Component({
  selector: 'app-account-info',
  standalone: true,
  imports: [
    ReactiveFormsModule,
    CommonCompModule,
    CaptchaComponent,
    NzUploadModule,
    NzModalModule,
    CompUploadComponent,
  ],
  templateUrl: './account-info.component.html',
  styleUrls: ['./account-info.component.scss'],
})
export class AccountInfoComponent implements OnInit {
  user: Parse.Object | undefined;
  validateForm: FormGroup<{
    name: FormControl<string>; //姓名
    phone: FormControl<string>; //手机号
    email: FormControl<string>; //电子邮箱
    telephone: FormControl<string>; //办公电话
    province: FormControl<string>; //省份
    identity: FormControl<string>; //人员类型
    companyType: FormControl<string>; //单位类型
    // idcard: FormControl<string>; //身份证号
    departmentName: FormControl<string>; //所在部门
    postName: FormControl<string>; //职务
  }> = this.fb.group({
    name: ['', [Validators.required]],
    phone: [''],
    email: ['', [Validators.required]],
    telephone: [''],
    province: [''],
    identity: ['', [Validators.required]],
    companyType: ['', [Validators.required]],
    // idcard: ['', [Validators.required]],
    departmentName: [''],
    postName: [''],
  });
  identityFile: string = ''; //单位联系人认证文件
  companyId: string = ''; //单位名称

  provinces: Array<string> = provinces.options; //省份
  unitTypes: Array<any> = [];
  companys: Array<any> = [];
  userType: Array<string> = ['工作联系人', '评审专家', '高校联系人', '个人'];

  constructor(
    public tbookSer: textbookServer,
    private fb: NonNullableFormBuilder,
    public router: Router,
    private authServr: AuthServr,
    private message: NzMessageService,
    private modal: NzModalService,
    private http: HttpClient
  ) {}

  async ngOnInit() {
    let user = Parse.User.current();
    if (!user?.id) history.back();
    this.user = user;
    await this.getUnitTypes();
    if (user?.get('accountState') == '已认证') {
      this.message.success('账号已认证，无需重复认证');
      this.authServr.profileVerify(this.modal);
      return;
    } else if (user?.get('accountState') == '已禁用') {
      this.message.success('账号已禁用');
      this.router.navigate(['/user/register'], { replaceUrl: true });
      return;
    }
    let queryProfile = new Parse.Query('Profile');
    queryProfile.equalTo('user', user?.id);
    let profile = await queryProfile.first();
    this.validateForm = this.fb.group({
      name: [user?.get('name') || '', [Validators.required]],
      phone: [user?.get('phone') || ''],
      email: [user?.get('email') || '', [Validators.required]],
      telephone: [profile?.get('telephone') || ''],
      province: [user?.get('province') || ''],
      identity: [profile?.get('identity') || '', [Validators.required]],
      companyType: [profile?.get('companyType') || '', [Validators.required]],
      departmentName: [user?.get('departmentName') || ''],
      postName: [profile?.get('postName') || ''],
    });
    this.identityFile = profile?.get('identityFile') || ''
    this.companyId = user?.get('department')?.id || '';
    this.provinceChange();
    // console.log(this.companyId, this.identityFile);
    // console.log(this.validateForm.value);
  }
  async getUnitTypes() {
    let query = new Parse.Query('Department');
    query.equalTo('branch', undefined);
    query.equalTo('parent', undefined);
    query.notEqualTo('isDeleted', true);
    query.select('name');
    let r = await query.find();
    r.forEach((item) => {
      this.unitTypes.push({ id: item.id, name: item.get('name') });
    });
  }
  //根据所选单位类型获取对应单位
  async provinceChange(val?: string, isChange?: boolean) {
    // console.log(val);
    if (isChange) this.companyId = '';
    this.companys = [];
    let parent = this.unitTypes.find(item=>item.name == this.validateForm.value.companyType)
    console.log(parent);
    let query = new Parse.Query('Department');
    // query.equalTo('branch', this.validateForm.value.companyType);
    query.equalTo('parent', parent.id);
    query.select('name', 'branch');
    query.limit(100);
    val && query.contains('name', val);
    let r = await query.find();
    if (r.length > 0) {
      this.companys = r.map((item: Parse.Object) =>{ return { id: item.id, name: item.get('name') }});
    }
  }
  submitForm(): void {
    console.log(this.validateForm.value);
    console.log(this.companyId);
    if (this.validateForm.valid) {
      if (!this.companyId) {
        this.message.error('单位名称未选择或与单位类型不匹配，请重新选择');
        return;
      }
      let a =
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (!String(this.validateForm.value.email).match(a)) {
        this.message.error('邮箱格式不正确');
        return;
      }
      if (!this.identityFile) {
        this.message.error('请上传单位联系人认证文件');
        return;
      }
      let params = this.validateForm.value;
      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) {
    let queryDepart = new Parse.Query('Department')
    queryDepart.equalTo('objectId', this.companyId);
    queryDepart.select('objectId');
    let depart = await queryDepart.first()
    if(!depart?.id){
      this.message.error('单位名称未选择或与单位类型不匹配，请重新选择');
      return;
    }
    this.user?.set('name', params.name);
    this.user?.set('email', params.email);
    this.user?.set('phone', params.phone);
    this.user?.set('province', params.province);
    this.user?.set('companyName', depart?.get('name'));
    this.user?.set('department', {
      __type: 'Pointer',
      className: 'Department',
      objectId: depart?.id,
    });
    !this.user?.get('accountState') && this.user?.set('accountState', '待认证');
    this.user?.set('departmentName', params.departmentName);
    await this.user?.save();

    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('telephone', params.telephone);
    profile?.set('companyType', params.companyType);
    profile?.set('email', params.email);
    // profile?.set('idcard', params.idcard);
    profile?.set('identity', params.identity);
    profile?.set('identityFile', this.identityFile);
    profile?.set('postName', params.postName);
    let res = await profile?.save();
    this.modal.success({
      nzTitle: '提交成功',
      nzContent: '',
      nzOnOk: () => this.router.navigate(['/user/login'], { replaceUrl: true }),
    });
  }
  upload(e: any) {
    console.log(e);
    let file = e[0];
    this.identityFile = file;
  }
  //验证手机号或邮箱是否注册
  async authUser(): Promise<boolean> {
    let query = new Parse.Query('_User');
    if (this.validateForm.value.phone) {
      query.equalTo('phone', this.validateForm.value.phone);
      let r = await query.first();
      if (r?.id) {
        this.message.warning('手机号已被注册');
        return false;
      }
    } else if (this.validateForm.value.email) {
      query.equalTo('email', this.validateForm.value.email);
      let r = await query.first();
      if (r?.id) {
        this.message.warning('邮箱已被注册');
        return false;
      }
    }
    return true;
  }
}
