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 Parse from 'parse';
import {
  FormControl,
  FormGroup,
  NonNullableFormBuilder,
  Validators,
} from '@angular/forms';
import { textbookServer } from '../../../../services/textbook';
interface author {
  name: string;
  unit: string;
  birth: Date | any;
  nationality: string;
  job: string;
  title: string;
  mobile: string;
  email: string;
  work: string;
}
interface achievementType {
  name: string;
  unit: string;
  date: Date | any;
}
@Component({
  selector: 'app-textbook-pertain',
  imports: [
    CommonCompModule,
    ReactiveFormsModule,
    NzSelectModule,
    NzRadioModule,
    NzGridModule,
    NzCheckboxModule,
    NzTableModule,
  ],
  standalone: true,
  templateUrl: './textbook-pertain.component.html',
  styleUrls: ['./textbook-pertain.component.scss'],
})
export class TextbookPertainComponent implements OnInit {
  @Input('eduTextbook') eduTextbook: Parse.Object|any;

  @Input('maxWidth') maxWidth: number = 0;
  @Output() state: EventEmitter<any> = new EventEmitter<any>();
  @Output() save: EventEmitter<any> = new EventEmitter<any>();
  validateForm: FormGroup<{
    major: FormControl<string>; //适用专业代码及名称
    period: FormControl<number | any>; //课程学时
    lessons: FormControl<string>; //适用课程
    characteristic: FormControl<Array<any> | any>; //适用课程性质
    // authorList: FormControl<Array<any> | any>; //作者信息
    authorDetails: FormControl<string>; //第一主编（作者）相关教学经历
    // achievement: FormControl<Array<any> | any>; //相关科学研究项目、成果或论文专著（限5项）
  }> = this.fb.group({
    major: ['', [Validators.required]],
    period: ['', [Validators.required]],
    lessons: ['', [Validators.required]],
    characteristic: ['', [Validators.required]],
    // authorList: ['', [Validators.required]],
    authorDetails: ['', [Validators.required]],
    // achievement: ['', [Validators.required]],
  });
  //适用专业代码及名称
  selectList: Array<any> = [
    {
      name: '机械与工程',
      code: 'M001',
    },
    {
      name: '软件工程',
      code: 'M002',
    },
    {
      name: '生物工程学',
      code: 'M003',
    },
  ];
  //适用课程性质
  checkOptionsOne = [
    { label: '必修课', value: '必修课' },
    { label: '选修课', value: '选修课' },
    { label: '通识课', value: '通识课' },
    { label: '公共基础课', value: '公共基础课' },
    { label: '专业课', value: '专业课' },
    { label: '思想作者理论课', value: '思想作者理论课' },
    { label: '实验课', value: '实验课' },
  ];
  // checkOptionsTwo = [
  //   { label: '通识课', value: '通识课' },
  //   { label: '公共基础课', value: '公共基础课' },
  //   { label: '专业课', value: '专业课' },
  // ];
  // checkOptionsThree = [
  //   { label: '思想作者理论课', value: '思想作者理论课' },
  //   { label: '实验课', value: '实验课' },
  // ];
  //作者信息
  authorList: Array<author> = [
    {
      name: '',
      unit: '',
      birth: '',
      nationality: '',
      job: '',
      title: '',
      mobile: '',
      email: '',
      work: '',
    },
  ];
  //相关科学研究项目、成果或论文专著（限5项）
  achievementOptions: Array<achievementType> = [
    {
      name: '',
      unit: '',
      date: '',
    },
  ];
  workOptions = ['主编', '作者', '副主编', '写者'];
  constructor(
    public tbookSer: textbookServer,
    private fb: NonNullableFormBuilder,
    private modal: NzModalService,
    private msg: NzMessageService
  ) {}

  ngOnInit() {
    console.log(this.eduTextbook);
    if(this.eduTextbook.id){
      this.checkOptionsOne = this.eduTextbook.get('characteristic') || this.checkOptionsOne
      let major = this.selectList.find(item=> item.code == this.eduTextbook.get('major')?.code)
      let lessons = this.eduTextbook.get('lessons')?.join(';')
      this.validateForm = this.fb.group({
        major: [major?.code || '', [Validators.required]],
        period: [this.eduTextbook.get('period') || '', [Validators.required]],
        lessons: [lessons || '', [Validators.required]],
        characteristic: [this.eduTextbook.get('characteristic') || '', [Validators.required]],
        authorDetails: [this.eduTextbook.get('authorDetails') || '', [Validators.required]],
      });
    }

  }
  async submitForm(event?: string):Promise<void>{
    console.log(this.validateForm.value);
    if (this.validateForm.valid) {
      let params = this.validateForm.value
      if (event == 'next') {
        await this.saveEduTextbook(params, this.validateForm.valid)
        this.state.emit({type:'next',textBook:this.eduTextbook});
      }
    } else {
      if(event == 'pre'){
        this.state.emit({type:'pre'});
      }
      else if(event == 'save'){
        let params = this.validateForm.value
        await this.saveEduTextbook(params, this.validateForm.valid)
        this.modal.success({
          nzTitle: '保存成功',
          nzContent: '<p>已保存并且至空间</p>',
          nzOnOk: () => console.log('Info OK')
        });
        return
      }
      Object.values(this.validateForm.controls).forEach((control) => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
      this.msg.warning('请填写完整信息');
    }
    if(event == 'save'){
      let params = this.validateForm.value
      await this.saveEduTextbook(params, this.validateForm.valid)
      this.modal.success({
        nzTitle: '保存成功',
        nzContent: '<p>已保存并且至空间</p>',
        nzOnOk: () => console.log('Info OK')
      });
    }
  }
  changeCode() {}
  getCode(e: any) {}

  //添加作者信息
  onPush(type: string, idx: number) {
    switch (type) {
      case 'authorList':
        this.authorList.splice(idx+1, 0, {
          name: '',
          unit: '',
          birth: '',
          nationality: '',
          job: '',
          title: '',
          mobile: '',
          email: '',
          work: '',
        });
        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: '',
              nationality: '',
              job: '',
              title: '',
              mobile: '',
              email: '',
              work: '',
            },
          ];
          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 saveEduTextbook(params: any, isComplete:boolean){
    console.log(params);
    if(!this.eduTextbook){
      this.msg.error('请先创建教材')
      return
      // let obj = Parse.Object.extend('EduTextbook');
      // this.eduTextbook = new obj();
    }
    //如果填写未完整，仅保存，状态修改待完善101
    if(this.eduTextbook.get('status') == '102' && !isComplete){
      this.eduTextbook?.set('status', '101');
    }else if(!this.eduTextbook.get('status')){
      this.eduTextbook?.set('status', '101');
    }
    this.eduTextbook?.set('user', Parse.User.current()?.toPointer());
    this.eduTextbook?.set('company', {
      __type: 'Pointer',
      className: 'Company',
      objectId: this.tbookSer.company,
    });
    let major = this.selectList.find(item=> item.code == params.major)
    let lessons = params.lessons.split(';')
    this.eduTextbook?.set('major', major);
    params.period && this.eduTextbook?.set('period', params.period);
    params.period && this.eduTextbook?.set('lessons', lessons);
    this.eduTextbook?.set('characteristic', params.characteristic);
    this.eduTextbook?.set('authorDetails', params.authorDetails);

    await this.eduTextbook?.save();
    return
  }
}
