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, 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';
import { NzGridModule } from 'ng-zorro-antd/grid';
import { NzSpinModule } from 'ng-zorro-antd/spin';
@Component({
  selector: 'app-account-info',
  standalone: true,
  imports: [
    ReactiveFormsModule,
    CommonCompModule,
    CaptchaComponent,
    NzUploadModule,
    NzModalModule,
    CompUploadComponent,
    NzGridModule,
    NzSpinModule
  ],
  templateUrl: './account-info.component.html',
  styleUrls: ['./account-info.component.scss'],
})
export class AccountInfoComponent implements OnInit {
  url: string = `"http://hep-textbook.oss-cn-beijing.aliyuncs.com/6687b9417f823ff53c74cfd6/2024-7-15/1721044465100-%E2%80%9C%E5%8D%81%E5%9B%9B%E4%BA%94%E2%80%9D%E6%99%AE%E9%80%9A%E9%AB%98%E7%AD%89%E6%95%99%E8%82%B2%E6%9C%AC%E7%A7%91%E5%9B%BD%E5%AE%B6%E7%BA%A7%E8%A7%84%E5%88%92%E6%95%99%E6%9D%90%E6%8E%A8%E8%8D%90%E9%81%B4%E9%80%89%E5%B7%A5%E4%BD%9C%E8%81%94%E7%B3%BB%E4%BA%BA%E4%BF%A1%E6%81%AF%E8%A1%A8.doc"`;
  user: Parse.Object | undefined;
  validateForm: FormGroup<{
    username: FormControl<string>;
    password: FormControl<string>;
    name: FormControl<string>; //姓名
    phone: FormControl<string>; //手机号
    email: FormControl<string>; //电子邮箱
    // identity: FormControl<string>; //人员类型
    // telephone: FormControl<string>; //办公电话
    // province: FormControl<string>; //省份
    // idcard: FormControl<string>; //身份证号
    // departmentName: FormControl<string>; //所在部门
    // postName: FormControl<string>; //职务
  }> = this.fb.group({
    username: ['', [Validators.required]],
    password: ['', [Validators.required]],
    name: ['', [Validators.required]],
    phone: [''],
    email: ['', [Validators.required]],
    // identity: ['工作联系人', [Validators.required]],
    // telephone: [''],
    // province: [''],
    // idcard: ['', [Validators.required]],
    // departmentName: [''],
    // postName: [''],
  });
  identity:string = '工作联系人' //人员类型
  companyType: string = ''; //单位类型

  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) {
      this.message.success('请先退出登录');
      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({
    //   username: [user?.get('username'), [Validators.required]],
    //   password: ['', [Validators.required]],
    //   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]],
    //   // departmentName: [user?.get('departmentName') || ''],
    //   // postName: [profile?.get('postName') || ''],
    // });
    // this.identityFile = profile?.get('identityFile') || ''
    // this.companyId = user?.get('department')?.id || '';
    // this.companyType = profile?.get('companyType') || ''
    this.provinceChange();
  }
  async getUnitTypes() {
    let query = new Parse.Query('Department');
    query.equalTo('branch', undefined);
    query.equalTo('parent', undefined);
    query.notEqualTo('isDeleted', true);
    query.descending('createdAt')
    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.companyType);
    // console.log(parent);
    if (!parent?.id) return;
    let query = new Parse.Query('Department');
    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;
      }
      let m =
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/;
      if (!String(this.validateForm.value.phone).match(m)) {
        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 });
        }
      });
    }
  }
  loading:boolean = false
  async profileSave(params: any) {
    this.loading = true
    try {
      if(!await this.tbookSer.userFind(params.phone)){
        this.message.error('手机号已存在');
        this.loading = false
        return
      }
      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('单位名称未选择或与单位类型不匹配，请重新选择');
        this.loading = false
        return;
      }
      let u = Parse.Object.extend('_User');
      this.user = new u();
      this.user?.set('username', params.username);
      this.user?.set('password', params.password);
      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'));
      // if(this.validateForm.value.identity == '工作联系人'){
      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);
      let saveUser = 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', saveUser?.toPointer());
      profile?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.tbookSer.company,
      });
      // profile?.set('telephone', params.telephone);
      // if(this.validateForm.value.identity == '工作联系人'){
      profile?.set('companyType', this.companyType);
      profile?.set('identityFile', this.identityFile);
      // }
      profile?.set('email', params.email);
      // profile?.set('idcard', params.idcard);
      // profile?.set('postName', params.postName);
      profile?.set('identity', this.identity);
      let res = await profile?.save();
      this.loading = false
      this.modal.success({
        nzTitle: '提交成功',
        nzContent: `<p>请妥善保管您的用户名和密码，待审核认证通过后即可使用邮箱/手机号/用户名和密码登录</p>`,
        nzOnOk: () =>
          this.router.navigate(['/user/login'], { replaceUrl: true }),
      });
      Parse.Cloud.run('aliSmsSend',{
        "mobileList": [params.phone],"templateCode":"SMS_469060724","params":{},"signName":"普通高等教育教材网"
      })
    } catch (err: any) {
      this.loading = false
      console.log(err?.message);
      let msg = '注册失败';
      switch (err?.message) {
        case 'Account already exists for this email address.':
          msg = '注册失败，邮箱已存在';
          break;
        case 'Account already exists for this username.':
          msg = '注册失败，用户名已存在';
          break;
      }
      this.message.warning(msg);
    }
  }
  upload(e: any) {
    console.log(e);
    let file = e[0];
    this.identityFile = file?.url;
  }
  //验证手机号或邮箱是否注册
  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;
  }
  back(){
    history.back()
  }
}
