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 course {
  date: Date|any,
  wordage: number|any,
  num: number|any,
  sumNum:number|any,
  accolade:string
}

@Component({
  selector: 'app-textbook-content',
  imports: [
    CommonCompModule,
    ReactiveFormsModule,
    NzSelectModule,
    NzRadioModule,
    NzGridModule,
    NzCheckboxModule,
    NzTableModule,
  ],
  standalone: true,
  templateUrl: './textbook-content.component.html',
  styleUrls: ['./textbook-content.component.scss'],
})
export class TextbookContentComponent  implements OnInit {
  @Input('eduTextbook') eduTextbook: any;
  @Input('maxWidth') maxWidth: number = 0;
  @Output() state: EventEmitter<any> = new EventEmitter<any>();
  @Output() save: EventEmitter<any> = new EventEmitter<any>();
  validateForm: FormGroup<{
    innovateExplain: FormControl<string>; //申报教材特色及创新
    influence: FormControl<string>; //申报教材应用情况及社会影响力
  }> = this.fb.group({
    innovateExplain: ['', [Validators.required]],
    influence: ['', [Validators.required]],
  });
  //申报教材建设历程
  courses: Array<course> = [
    {
      date: '',//出版时间
      wordage: '',//字数
      num: '',//重印次数
      sumNum:'',//本版总印数
      accolade:''//获奖励情况
    },
  ];
  constructor(
    public tbookSer: textbookServer,
    private fb: NonNullableFormBuilder,
    private modal: NzModalService,
    private msg: NzMessageService
  ) { }

  ngOnInit() {
    if (this.eduTextbook.id) {
      this.validateForm = this.fb.group({
        innovateExplain: [this.eduTextbook.get('innovateExplain'), [Validators.required]],
        influence: [this.eduTextbook.get('influence'), [Validators.required]],
      });
      console.log(this.validateForm.value);
      this.courses = this.eduTextbook.get('courses') || this.courses
    }
  }
  async submitForm(event?: string): Promise<void> {
    if (event == 'pre') {
      this.state.emit({ type: 'pre' });
      return
    }
    console.log(this.validateForm.value);
    let coursesVrifly = !this.courses.some(item=>Object.values(item).some(val=> val == '' || val == undefined))
    if (this.validateForm.valid) {
      let params: any = this.validateForm.value;
      if (event == 'next') {
        if(!coursesVrifly){
          this.msg.warning('申报教材建设历程填写不完整')
          return
        }
        await this.saveEduTextbook(params, true);
        this.state.emit({ type: 'next', textBook: this.eduTextbook });
      }
    } else {
      if (event == 'save') {
        let params: any = this.validateForm.value;
        await this.saveEduTextbook(params, (this.validateForm.valid && coursesVrifly));
        this.modal.success({
          nzTitle: '保存成功',
          nzContent: '<p>已保存并且至空间</p>',
          nzOnOk: () => console.log('Info OK'),
        });
        return;
      }
      if (event == 'next') {
      let params: any = this.validateForm.value;
      await this.saveEduTextbook(params, false);
        this.state.emit({ type: 'next', textBook: this.eduTextbook });
      }
      // 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 && coursesVrifly));
      this.modal.success({
        nzTitle: '保存成功',
        nzContent: '<p>已保存并且至空间</p>',
        nzOnOk: () => console.log('Info OK'),
      });
    }
  }
  changeCode() {}
  getCode(e: any) {}
  //添加作者信息
  onPush(idx: number) {
    this.courses.splice(idx+1, 0, {
      date: '',
      wordage: '',
      num: '',
      sumNum:'',
      accolade:''
    });
  }
  //删除作者信息
  onDel(idx: number) {
    if(this.courses?.length==1)return
    this.courses.splice(idx, 1);
  }

  async saveEduTextbook(params: any, isComplete: boolean) {
    console.log(params);
    if (!this.eduTextbook) {
      this.msg.error('请先创建教材');
      return;
    }
    //如果填写未完整，仅保存，状态修改待完善101
    if (this.eduTextbook.get('status') == '102' && !isComplete) {
      this.eduTextbook?.set('status', '101');
      this.eduTextbook.set('complete', false)
    } 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,
    });
    params.innovateExplain && this.eduTextbook?.set('innovateExplain', params.innovateExplain);
    params.influence && this.eduTextbook?.set('influence', params.influence);
    this.eduTextbook?.set('courses', this.courses);
    await this.eduTextbook?.save();
    return;
  }
}
