import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { CommonCompModule } from '../../../../../services/common.modules';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { ReactiveFormsModule } from '@angular/forms';
import { NzRadioModule } from 'ng-zorro-antd/radio';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzGridModule } from 'ng-zorro-antd/grid';
import { NzCheckboxModule } from 'ng-zorro-antd/checkbox';
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CompUploadComponent } from '../../../../../app/comp-upload/comp-upload.component';
import {
  FormControl,
  FormGroup,
  NonNullableFormBuilder,
  Validators,
} from '@angular/forms';
import Parse from 'parse';
interface author {
  name: string;
  unit: string;
  birth: Date | any;
  nationality: string;
  job: string;
  title: string;
  mobile: string;
  email: string;
  work: string;
  signature?: string;
  examine?: string;
}
interface achievementType {
  name: string;
  unit: string;
  date: Date | any;
}
@Component({
  selector: 'app-author',
  imports: [
    CommonCompModule,
    ReactiveFormsModule,
    NzSelectModule,
    NzRadioModule,
    NzGridModule,
    NzCheckboxModule,
    NzTableModule,
    CompUploadComponent,
  ],
  standalone: true,
  templateUrl: './author.component.html',
  styleUrls: ['./author.component.scss'],
})
export class AuthorComponent implements OnInit {
  @Input('eduTextbook') eduTextbook: Parse.Object | any;
  @Input('maxWidth') maxWidth: number = 0;
  @Input('eduTextbookVolume') eduTextbookVolume: Parse.Object | any;

  validateForm: FormGroup<{
    authorDetails: FormControl<string>; //第一主编（作者）相关教学经历
  }> = this.fb.group({
    authorDetails: ['', [Validators.required]],
  });
  //作者信息
  authorList: Array<author> = [
    {
      name: '',
      unit: '',
      birth: new Date('December 1, 1975 00:00:00'),
      nationality: '',
      job: '',
      title: '',
      mobile: '',
      email: '',
      work: '',
      // signature: '',
      // examine: '',
    },
  ];
  //相关科学研究项目、成果或论文专著（限5项）
  achievementOptions: Array<achievementType> = [
    {
      name: '',
      unit: '',
      date: '',
    },
  ];
  workOptions = ['主编', '副主编', '其他编者'];

  constructor(
    private fb: NonNullableFormBuilder,
    private modal: NzModalService,
    private msg: NzMessageService
  ) {}

  ngOnInit() {
    let id = this?.eduTextbookVolume?.id || this?.eduTextbookVolume?.objectId;
    if (id) {
      this.getEduTextbookVolume(id);
    }
  }
  async getEduTextbookVolume(id: string) {
    let query = new Parse.Query('EduTextbookVolume');
    query.equalTo('objectId', id);
    let r = await query.first();
    this.eduTextbookVolume = r;
    this.validateForm.get("authorDetails")?.setValue(this.eduTextbookVolume.get('authorDetails'))
    this.authorList =
      this.eduTextbookVolume.get('authorList') || this.authorList;
    this.achievementOptions =
      this.eduTextbookVolume.get('achievementOptions') ||
      this.achievementOptions;
  }
  //添加作者信息
  onPush(type: string, idx: number) {
    switch (type) {
      case 'authorList':
        if (this.authorList?.length >= 6) {
          this.msg.warning('最多添加6条');
          break;
        }
        this.authorList.splice(idx + 1, 0, {
          name: '',
          unit: '',
          birth: new Date('December 1, 1975 00:00:00'),
          nationality: '',
          job: '',
          title: '',
          mobile: '',
          email: '',
          work: '',
          // signature: '',
          // examine: '',
        });
        break;
      case 'achievementOptions':
        if (this.achievementOptions.length >= 5) {
          this.msg.warning('最多添加5条');
          return;
        }
        this.achievementOptions.splice(idx + 1, 0, {
          name: '',
          unit: '',
          date: '',
        });
        break;
    }
  }
  //删除作者信息
  onDel(type: string, idx: number) {
    switch (type) {
      case 'authorList':
        if (this.authorList.length == 1) {
          this.authorList = [
            {
              name: '',
              unit: '',
              birth: new Date('December 1, 1975 00:00:00'),
              nationality: '',
              job: '',
              title: '',
              mobile: '',
              email: '',
              work: '',
              // signature: '',
              // examine: '',
            },
          ];
          return;
        }
        this.authorList.splice(idx, 1);
        break;
      case 'achievementOptions':
        if (this.achievementOptions.length == 1) {
          this.achievementOptions = [
            {
              name: '',
              unit: '',
              date: '',
            },
          ];
          return;
        }
        this.achievementOptions.splice(idx, 1);
        break;
    }
  }

  async submitForm(event?: string): Promise<boolean> {
    let params: any = this.validateForm.value;
    let authorListVrifly = !this.authorList.some((item) =>
      Object.values(item).some((val) => val == '' || val == undefined)
    );
    let achievementOptionsVrifly = !this.achievementOptions.some((item) =>
      Object.values(item).some((val) => val == '' || val == undefined)
    );
    let isComplete =
      this.validateForm.valid && authorListVrifly && achievementOptionsVrifly;
    await this.saveEduTextbookVolume(params, isComplete);
    return isComplete;
  }
  async saveEduTextbookVolume(params: any, isComplete: boolean) {
    this.eduTextbookVolume?.set('user', Parse.User.current()?.toPointer());
    this.eduTextbookVolume?.set('authorList', this.authorList);
    this.eduTextbookVolume?.set('achievementOptions', this.achievementOptions);
    params.authorDetails &&
      this.eduTextbookVolume?.set('authorDetails', params.authorDetails);
    await this.eduTextbookVolume?.save();
  }
}
