import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { languages } from '../../../../services/languages.map';
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 { NzUploadModule } from 'ng-zorro-antd/upload';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadChangeParam } from 'ng-zorro-antd/upload';
import { NzModalService } from 'ng-zorro-antd/modal';
import { textbookServer } from '../../../../services/textbook'
import Parse from 'parse';
import {
  FormControl,
  FormGroup,
  NonNullableFormBuilder,
  Validators,
} from '@angular/forms';
@Component({
  selector: 'app-basic',
  imports: [
    CommonCompModule,
    ReactiveFormsModule,
    NzSelectModule,
    NzRadioModule,
    NzUploadModule,
  ],
  standalone: true,
  templateUrl: './basic-in.component.html',
  styleUrls: ['./basic-in.component.scss'],
})
export class BasicInComponent implements OnInit {
  @Input('eduTextbook') eduTextbook: Parse.Object|any;
  @Input('editFrom') editFrom: any;
  @Output() state: EventEmitter<any> = new EventEmitter<any>();
  @Output() save: EventEmitter<any> = new EventEmitter<any>();

  validateForm: FormGroup<{
    title: FormControl<string>; //申报教材名称
    ISBN: FormControl<string>; //国际标准书号
    author: FormControl<string>; //第一主编（作者）
    unit: FormControl<string>; //第一主编（作者）单位
    type: FormControl<string>; //申报类型
    typeNumber: FormControl<number|any>; //全册次数

    majorPoniter: FormControl<string>; //教材应用对象及所诉学科专业类
    lang: FormControl<string>; //教材主要语种类型
    authors: FormControl<string>; //其他主编姓名
    editor: FormControl<string>; //其他编者姓名

    approval: FormControl<boolean>; //是否为重点立项教材
    editionUnit: FormControl<string>; //出版单位
    editionFirst: FormControl<Date>; //初版时间
    carrierShape: FormControl<string>; //载体形式

    editionDate: FormControl<Date>; //出版时间
    editionNumber: FormControl<number>; //出版版次
    printDate: FormControl<Date>; //最新印次时间
    printNumber: FormControl<number>; //最新印次

    printSum: FormControl<number>; //初版以来合计印次

    importantProject: FormControl<string>; //初版以来是否列为重点项目
    importantProjectOther: FormControl<string>; //其他省部级及以上项目

    copyrightImgUrl: FormControl<string>; //版权页截图
    CIPImgUrl: FormControl<string>; //中国版本图书馆CIP查询截图

    // remember: FormControl<boolean>;
  }> = this.fb.group({
    title: ['', [Validators.required]],
    ISBN: ['', [Validators.required]],
    author: ['', [Validators.required]],
    unit: ['', [Validators.required]],
    type: ['', [Validators.required]],
    typeNumber: [''],
    majorPoniter: ['', [Validators.required]],
    lang: ['', [Validators.required]],
    authors: ['', [Validators.required]],
    editor: ['', [Validators.required]],
    approval: [false],
    editionUnit: ['', [Validators.required]],
    editionFirst: [new Date(), [Validators.required]],
    carrierShape: ['', [Validators.required]],
    editionDate: [new Date(), [Validators.required]],
    editionNumber: [0, [Validators.required]],
    printDate: [new Date(), [Validators.required]],
    printNumber: [0, [Validators.required]],
    printSum: [0, [Validators.required]],
    importantProject: ['', [Validators.required]],
    importantProjectOther: [''],
    copyrightImgUrl: ['https://www.jyvtc.edu.cn/yssj/resource/cms/2022/01/2022010610314324023.pdf'],
    CIPImgUrl: ['https://www.jyvtc.edu.cn/yssj/resource/cms/2022/01/2022010610314324023.pdf'],
    // remember: [true],
  });
  //教材应用对象及所诉学科专业类
  selectList: Array<any> = [
    {
      name: '机械与工程',
      code: 'M001',
    },
    {
      name: '软件工程',
      code: 'M002',
    },
    {
      name: '生物工程学',
      code: 'M003',
    },
  ];
  //语言选择
  selectLang: Array<any> = languages.options;
  //载体形式
  carrierOptions: Array<any> = [
    {
      name: '载体一',
      code: 'Z001',
    },
    {
      name: '载体二',
      code: 'Z002',
    },
    {
      name: '载体三',
      code: 'Z003',
    },
  ];
  importantProjectList: Array<any> = [
    {
      title: '“十二五”普通高等教育本科国家级规划教材',
      value: '“十二五”普通高等教育本科国家级规划教材',
    },
    {
      title: '“十二五”以来省级优秀教材',
      value: '“十二五”以来省级优秀教材',
    },
    {
      title: '“十二五”以来省级规划教材',
      value: '“十二五”以来省级规划教材',
    },
    {
      title: '其他省部级及以上项目',
      value: '其他省部级及以上项目',
    },
  ];
  // get importantProjectState(){
  //   return this.importantProjectList.some((item:any)=> item.value == this.validateForm.value.importantProject)
  // }
  constructor(
    public tbookSer: textbookServer,
    private fb: NonNullableFormBuilder,
    private modal: NzModalService,
    private msg: NzMessageService
  ) {
  }

  ngOnInit() {
    console.log(this.eduTextbook);
    this.validateForm = this.fb.group({
      title: [this.eduTextbook?.get('title') || '', [Validators.required]],
      ISBN: [this.eduTextbook?.get('ISBN') || '', [Validators.required]],
      author: [this.eduTextbook?.get('author') || '', [Validators.required]],
      unit: [this.eduTextbook?.get('unit') || '', [Validators.required]],
      type: [this.eduTextbook?.get('type') || '', [Validators.required]],
      typeNumber: [this.eduTextbook?.get('typeNumber') || '', [Validators.required]],
  
      majorPoniter: [this.eduTextbook?.get('majorPoniter') || '', [Validators.required]],
      lang: [this.eduTextbook?.get('lang') || '', [Validators.required]],
      authors: [this.eduTextbook?.get('authors') || '', [Validators.required]],
      editor: [this.eduTextbook?.get('editor') || '', [Validators.required]],
      approval: [this.eduTextbook?.get('approval') || false, [Validators.required]],
      editionUnit: [this.eduTextbook?.get('editionUnit') || '', [Validators.required]],
      editionFirst: [this.eduTextbook?.get('editionFirst') || new Date(), [Validators.required]],
      carrierShape: [this.eduTextbook?.get('carrierShape') || '', [Validators.required]],
      editionDate: [this.eduTextbook?.get('editionDate') || new Date(), [Validators.required]],
      editionNumber: [this.eduTextbook?.get('editionNumber') || 0, [Validators.required]],
      printDate: [this.eduTextbook?.get('printDate') || new Date(), [Validators.required]],
      printNumber: [this.eduTextbook?.get('printNumber') || 0, [Validators.required]],
      printSum: [this.eduTextbook?.get('printSum') || 0, [Validators.required]],
      importantProject: [this.eduTextbook?.get('importantProject') || '', [Validators.required]],
      importantProjectOther: [this.eduTextbook?.get('importantProjectOther') || '', [Validators.required]],
      copyrightImgUrl: [this.eduTextbook?.get('copyrightImgUrl') || 'https://www.jyvtc.edu.cn/yssj/resource/cms/2022/01/2022010610314324023.pdf', [Validators.required]],
      CIPImgUrl: [this.eduTextbook?.get('CIPImgUrl') || 'https://www.jyvtc.edu.cn/yssj/resource/cms/2022/01/2022010610314324023.pdf', [Validators.required]],
      // remember: [true],
    });
  }
  //校验其他省部级及以上项目是否需填
  onChangeRadio(){
    if (this.validateForm.value.importantProject != '其他省部级及以上项目') {
      this.validateForm.controls.importantProjectOther.clearValidators();
      this.validateForm.controls.importantProjectOther.markAsPristine();
    } else {
      this.validateForm.controls.importantProjectOther.setValidators(Validators.required);
      this.validateForm.controls.importantProjectOther.markAsDirty();
    }
    this.validateForm.controls.importantProjectOther.updateValueAndValidity();
  }
  //校验全册册数是否需填
  requiredTypeNumber(e:boolean){
    if (e) {
      this.validateForm.controls.typeNumber.clearValidators();
      this.validateForm.controls.typeNumber.markAsPristine();
    } else {
      this.validateForm.controls.typeNumber.setValidators(Validators.required);
      this.validateForm.controls.typeNumber.markAsDirty();
    }
    this.validateForm.controls.typeNumber.updateValueAndValidity();
  }

  handleChange(info: NzUploadChangeParam): void {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      this.msg.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      this.msg.error(`${info.file.name} file upload failed.`);
    }
  }

  async submitForm(event?: string): Promise<void> {
    console.log(this.validateForm.value);
    if (this.validateForm.valid) {
      // console.log(this.validateForm.value);
      // let {
      //   title,
      //   ISBN,
      //   author,
      //   unit,
      //   type,
      //   typeNumber,
      //   majorPoniter,
      //   lang,
      //   authors,
      //   editor,
      //   approval,
      //   editionUnit,
      //   editionFirst,
      //   carrierShape,
      //   editionDate,
      //   editionNumber,
      //   printDate,
      //   printNumber,
      //   printSum,
      //   importantProject,
      //   importantProjectOther,
      //   copyrightImgUrl,
      //   CIPImgUrl,
      // } = this.validateForm.value
      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 == '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('请填写完整的内容')
      return
    }
    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')
      });
    }
  }

  async saveEduTextbook(params: any, isComplete:boolean){
    console.log(params);
    if(!this.eduTextbook){
      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,
    });
    this.eduTextbook?.set('title', params.title);
    this.eduTextbook?.set('ISBN', params.ISBN);
    this.eduTextbook?.set('author', params.author);
    this.eduTextbook?.set('unit', params.unit);
    this.eduTextbook?.set('type', params.type);
    this.eduTextbook?.set('typeNumber', params.typeNumber);
    this.eduTextbook?.set('majorPoniter', params.majorPoniter);
    this.eduTextbook?.set('lang', params.lang);
    this.eduTextbook?.set('authors', params.authors);
    this.eduTextbook?.set('editor', params.editor);
    this.eduTextbook?.set('approval', params.approval);
    this.eduTextbook?.set('editionUnit', params.editionUnit);
    this.eduTextbook?.set('editionFirst', params.editionFirst);
    this.eduTextbook?.set('carrierShape', params.carrierShape);
    this.eduTextbook?.set('editionDate', params.editionDate);
    this.eduTextbook?.set('editionNumber', params.editionNumber);
    this.eduTextbook?.set('printDate', params.printDate);
    this.eduTextbook?.set('printNumber', params.printNumber);
    this.eduTextbook?.set('printSum', params.printSum);
    this.eduTextbook?.set('importantProject', params.importantProject);
    this.eduTextbook?.set('importantProjectOther', params.importantProjectOther);
    this.eduTextbook?.set('copyrightImgUrl', params.copyrightImgUrl);
    this.eduTextbook?.set('CIPImgUrl', params.CIPImgUrl);
    await this.eduTextbook?.save();
    return
  }
}
