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,
  ValidatorFn,
  AbstractControl,
  Validators,
} from '@angular/forms';
import { textbookServer } from '../../../../services/textbook';
import { CompUploadComponent } from '../../../../app/comp-upload/comp-upload.component';
import * as major from '../../../../services/majors.map'
import { HttpClient } from '@angular/common/http';

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-textbook-pertain',
  imports: [
    CommonCompModule,
    ReactiveFormsModule,
    NzSelectModule,
    NzRadioModule,
    NzGridModule,
    NzCheckboxModule,
    NzTableModule,
    CompUploadComponent,
  ],
  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>();
  //填写诚信承诺是否正确
  confirmationValidator: ValidatorFn = (
    control: AbstractControl
  ): { [s: string]: boolean } => {
    if (
      control.value !=
      '本人自愿参加此次申报，已认真填写并检查以上材料，保证内容真实'
    ) {
      return { required: true };
    }
    return {};
  };
  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项）
    accept: FormControl<string>; //填写诚信承诺

  }> = this.fb.group({
    major: ['', [Validators.required]],
    period: ['', [Validators.required]],
    lessons: ['', [Validators.required]],
    characteristic: ['', [Validators.required]],
    // authorList: ['', [Validators.required]],
    authorDetails: ['', [Validators.required]],
    // achievement: ['', [Validators.required]],
    accept: ['', [Validators.required, this.confirmationValidator]],
  });




  //适用专业代码及名称
  selectList = major.majors.options

  //适用课程性质

  checkOptionsOne = [
    { label: '必修课', value: '必修课',checked:false },
    { label: '选修课', value: '选修课',checked:false },
  ];
  checkOptionsTwo = [
    { label: '通识课', value: '通识课' ,checked:false},
    { label: '公共基础课', value: '公共基础课' ,checked:false},
    { label: '专业课', value: '专业课' ,checked:false},
  ];
  checkOptionsThree = [
    { label: '思想政治理论课', value: '思想政治理论课',checked:false},
    { label: '实验课', value: '实验课',checked:false },
  ];
  checkTwo: any = null
  changeRadio(){
    for(let i in this.checkOptionsTwo){
      if(this.checkOptionsTwo[i].label==this.checkTwo){
        this.checkOptionsTwo[i].checked=true
      }else{
        this.checkOptionsTwo[i].checked=false
      }
    }
  }

  //作者信息
  authorList: Array<author> = [
    {
      name: '',
      unit: '',
      birth: '',
      nationality: '',
      job: '',
      title: '',
      mobile: '',
      email: '',
      work: '',
      signature: '',
      examine: '',
    },
  ];
  //相关科学研究项目、成果或论文专著（限5项）
  achievementOptions: Array<achievementType> = [
    {
      name: '',
      unit: '',
      date: '',
    },
  ];
  workOptions = ['主编', '副主编', '其他编者'];
  /**诚信承诺 */
  accept: string = ''
  constructor(
    public tbookSer: textbookServer,
    private fb: NonNullableFormBuilder,
    private modal: NzModalService,
    private msg: NzMessageService,
    private http: HttpClient
  ) { }

  ngOnInit() {
    console.log(this.eduTextbook);
    if (this.eduTextbook.id) {
      let list = this.eduTextbook.get('characteristic')||[]
       if(list.length>0){
        let one = []
        let three=[]
        for(let i in list){
          if(list[i].label=='必修课'||list[i].label=='选修课'){
            one.push(list[i])
          }else if(list[i].label=='思想政治理论课'||list[i].label=='实验课'){
            three.push(list[i])
          }else if(list[i].checked){
            this.checkTwo=list[i].label
            let index = this.checkOptionsTwo.findIndex(item=>item.value==list[i].label)
            this.checkOptionsTwo[index].checked=true
          }
        }
       this.checkOptionsOne=one
       this.checkOptionsThree=three
      }

      // 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,Validators.maxLength(500)],
        ],
        accept: [
          this.eduTextbook.get('accept') || '',
          [Validators.required, this.confirmationValidator]
        ],
      });
      this.authorList = this.eduTextbook.get('authorList') || this.authorList
      this.achievementOptions = this.eduTextbook.get('achievementOptions') || this.achievementOptions
    }
  }
  async submitForm(event?: string): Promise<void> {
    if (event == 'pre') {
      this.state.emit({ type: 'pre' });
      return
    }
    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))

    if (this.validateForm.valid) {
      let params: any = this.validateForm.value;
      if (event == 'next') {
        if (!authorListVrifly) {
          this.msg.warning('作者信息填写不完整')
          return
        } else if (!achievementOptionsVrifly) {
          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 && authorListVrifly && achievementOptionsVrifly));
        this.modal.success({
          nzTitle: '保存成功',
          nzContent: '<p>已保存并且至空间</p>',
          nzOnOk: () => console.log('Info OK'),
        });
        return;
      }
      if (event == 'next') {
        // if(!authorListVrifly){
        //   this.msg.warning('作者信息填写不完整')
        //   return
        // }else if(!achievementOptionsVrifly){
        //   this.msg.warning('相关科学研究项目、成果或论文专著填写不完整')
        //   return
        // }
        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 && authorListVrifly && achievementOptionsVrifly));
      this.modal.success({
        nzTitle: '保存成功',
        nzContent: '<p>已保存并且至空间</p>',
        nzOnOk: () => console.log('Info OK'),
      });
    }
  }
  changeCode() { }
  getCode(e: any) { }
  upload(e: any, type: string, index: number) {
    console.log(e);
    let file = e[0];
    if (type == 'signature' || type == 'examine') {
      this.authorList[index][type] = file?.url
    }
  }
  //添加作者信息
  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: '',
          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: '',
              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 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');
      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,
    });
    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);
    lessons && this.eduTextbook?.set('lessons', lessons);
    // params.characteristic && this.eduTextbook?.set('characteristic', params.characteristic);
    this.eduTextbook?.set('characteristic', [...this.checkOptionsOne,...this.checkOptionsTwo,...this.checkOptionsThree])
    params.authorDetails && this.eduTextbook?.set('authorDetails', params.authorDetails);
    this.eduTextbook?.set('authorList', this.authorList);
    this.eduTextbook?.set('achievementOptions', this.achievementOptions);
    params.accept && this.eduTextbook?.set('accept', params.accept);
    await this.eduTextbook?.save();
    return;
  }
  // http://hep-textbook.oss-cn-beijing.aliyuncs.com/66988340e4964b67e5c0d7b4/2024-7-19/1721355300725-%E5%A4%9A%E8%82%89.jpg

  /**获取文件名 */
  getFileName(url: string) {
    if (!url) return ''
    let str = url?.split('/')[5]
    let index = str?.indexOf('-')
    let result = decodeURIComponent(str?.substring(index + 1))

    return result || '未知文件名'
  }
  
  openFile(url:string){
    console.log(url);
    window.open(url)
  }
  downloadFile(){
    let fileName = '十四五”普通高等教育本科国家级规划教材第一次遴选推荐申报表.docx'
    let fileUrl = `../../../../../public/file/${fileName}`;
    this.http.get(fileUrl, { responseType: 'blob' }).subscribe((blob) => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    })
    let fileName02 = '教材编写人员政治审查表.docx'
    let fileUrl02 = `../../../../../public/file/${fileName02}`;
    this.http.get(fileUrl02, { responseType: 'blob' }).subscribe((blob) => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName02;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    })
  }
  }
