import { Component, Input, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { CommonCompModule } from '../../../../services/common.modules';
import { NzTabsModule } from 'ng-zorro-antd/tabs';
import { ActivatedRoute, Router } from '@angular/router';
import Parse from 'parse';
import { NzAvatarModule } from 'ng-zorro-antd/avatar';
import { NzDropDownModule } from 'ng-zorro-antd/dropdown';
import { NzPopoverModule } from 'ng-zorro-antd/popover';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ReactiveFormsModule } from '@angular/forms';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { NzRadioModule } from 'ng-zorro-antd/radio';
import {
  FormControl,
  FormGroup,
  NonNullableFormBuilder,
  Validators,
} from '@angular/forms';
import { provinces } from '../../../../services/provinces';
import { CompUploadComponent } from '../../../../app/comp-upload/comp-upload.component';
import { textbookServer } from '../../../../services/textbook';
import { NzModalModule, NzModalService } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-user-edit',
  templateUrl: './user-create.component.html',
  styleUrls: ['./user-create.component.scss'],
  imports: [
    CommonModule,
    NzSpaceModule,
    CommonCompModule,
    NzTabsModule,
    NzAvatarModule,
    NzDropDownModule,
    NzPopoverModule,
    NzTagModule,
    CompUploadComponent,
    NzModalModule,
    ReactiveFormsModule,
    NzSelectModule,
    NzRadioModule,
  ],
  standalone: true,
})
export class UserCreateComponent implements OnInit {
  validateForm: FormGroup<{
    name: FormControl<string>; //姓名
    username: FormControl<string>; //用户名
    phone: FormControl<string>; //手机号
    email: FormControl<string>; //电子邮箱
    telephone: FormControl<string>; //办公电话
    province: FormControl<string>; //省份
    identity: FormControl<string>; //人员类型
    // idcard: FormControl<string>; //身份证号
    departmentName: FormControl<string>; //所在部门
    postName: FormControl<string>; //职务
    majorSubject: FormControl<string>; //学科
  }> = this.fb.group({
    name: ['', [Validators.required]],
    username: ['', [Validators.required]],
    phone: [''],
    email: ['', [Validators.required]],
    telephone: [''],
    province: [''],
    identity: ['', [Validators.required]],
    // idcard: ['', [Validators.required]],
    departmentName: [''],
    postName: [''],
    majorSubject: [''],
  });
  companyType: string = ''; //单位类型

  provinces: Array<string> = provinces.options; //省份

  unitTypes: Array<any> = [];
  userType: Array<string> = ['工作联系人', '评审专家', '高校联系人', '教师'];
  identityFile: string = ''; //单位联系人认证文件
  department?: Parse.Object; //所属单位
  parentMap: Array<any> = [];
  parentList: Array<any> = []; //单位列表
  inputValue: string = ``;
  isVisible: boolean = false;
  searchValue: string = ''; //搜索部门内容
  constructor(
    public tbookSer: textbookServer,
    private activeRoute: ActivatedRoute,
    private fb: NonNullableFormBuilder,
    private router: Router,
    private message: NzMessageService,
    private modal: NzModalService
  ) {}

  async ngOnInit() {
    if (this.tbookSer.profile.identity != '国家级管理员') {
      this.userType = ['教师'];
      this.getUnitTypes(this.tbookSer.profile.companyType);
      return;
    }
    await this.getUnitTypes();
  }
  async getUnitTypes(name?: string) {
    let query = new Parse.Query('Department');
    query.equalTo('branch', undefined);
    query.equalTo('parent', undefined);
    query.notEqualTo('isDeleted', true);
    name && query.equalTo('name', name);
    query.select('name');
    let r = await query.find();
    r.forEach((item) => {
      this.unitTypes.push({ id: item.id, name: item.get('name') });
    });
  }
  upload(e: any) {
    console.log(e);
    let file = e[0];
    this.identityFile = file;
  }
  //根据所选单位类型获取对应单位
  async provinceChange(id?: string, val?: string) {
    let query = new Parse.Query('Department');
    query.select('name', 'branch', 'parent');
    if (this.tbookSer.profile.identity != '国家级管理员') {
      // query.equalTo('branch', this.tbookSer.profile.companyType);
      query.equalTo('objectId', this.tbookSer.profile?.user.department?.objectId);
    }
    if(this.tbookSer.profile.identity == '国家级管理员' || id){
      query.equalTo('parent', id ? id : null);
    }
    query.limit(100);
    val && query.contains('name', val);
    let r = await query.find();
    this.parentList = r;
  }
  //选择部门
  async showModalDepart() {
    let parent = this.unitTypes.find((item) => item.name == this.companyType);
    if (parent?.id) {
      this.parentMap = await this.formatNode(parent.id);
    }
    this.provinceChange();
    this.isVisible = true;
  }
  async formatNode(id: string): Promise<Array<any>> {
    let arr = [];
    if (id) {
      let query = new Parse.Query('Department');
      query.equalTo('objectId', id);
      query.select('parent', 'name');
      let r = await query.first();
      arr.push({
        title: r?.get('name'),
        id: r?.id,
      });
      if (r?.get('parent')) {
        arr.unshift(...(await this.formatNode(r?.get('parent')?.id)));
      }
    }
    return arr;
  }
  onCheck(e: any) {
    console.log(e);
    this.provinceChange();
  }
  //选择部门
  async onCheckedDepart(e: any) {
    this.department = e;
    if (e?.get('parent')?.id) {
      console.log(e);
      this.department = e;
    } else {
      this.provinceChange(e.id);
    }
    this.parentMap = await this.formatNode(e.id);
  }
  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }
  async handleOk(): Promise<void> {
    if (this.department?.id) {
      this.companyType = this.department.get('branch');
    }
    this.isVisible = false;
  }
  submitForm(): void {
    if (this.validateForm.valid) {
      console.log('submit', this.validateForm.value);
      if (!this.companyType) {
        this.message.error('请选择单位类型');
        return;
      }
      let a = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      if (
        this.validateForm.value.phone &&
        !String(this.validateForm.value.phone).match(a)
      ) {
        this.message.error('请填写正确手机号');
        return;
      }
      let params = this.validateForm.value;
      this.profileSave(params);
    } else {
      this.message.error('请填写必填信息');
      Object.values(this.validateForm.controls).forEach((control) => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
  async profileSave(params: any) {
    this.randomPassword()
    if (!this.department?.id) {
      this.message.error('请选择所属组织部门');
      return;
    }
    try {
      let obj = Parse.Object.extend('_User');
      let user = new obj();
      user.set('username', params.username);
      user.set('name', params?.name);
      user.set('phone', params?.phone.trim());
      user.set('email', params?.email.trim());
      user.set('password', this.password);
      user.set('province', params.province);
      user.set('departmentName', params?.departmentName);
      user.set('accountState', '已认证');
      user.set('department', {
        __type: 'Pointer',
        className: 'Department',
        objectId: this.department?.id,
      });
      user.set('companyName', this.department?.get('name'));
      let u = await user.save();

      let p = Parse.Object.extend('Profile');
      let profile = new p();
      profile.set('user', u?.toPointer());
      profile.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.tbookSer.company,
      });
      profile?.set('telephone', params.telephone);
      profile.set('companyType', this.companyType);
      profile.set('email', params.email);
      profile?.set('postName', params.postName);
      profile.set('identity', params.identity);
      profile.set('identityFile', this.identityFile);
      let res = await profile?.save();
      console.log(res);
      this.modal.success({
        nzTitle: '创建成功',
        nzContent: '',
        nzOnOk: () =>history.back()
      });
    } catch (err: any) {
      console.warn('创建失败', err);
      this.message.error(err?.Error || '创建失败：请检查用户邮箱是否已存在');
      return;
    }
  }

  password: string = '';
  randomPassword() {
    this.password = this.tbookSer.randomPassword()
  }
}
