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 { NzUploadChangeParam } from 'ng-zorro-antd/upload';
import { NzUploadModule } from 'ng-zorro-antd/upload';
import { NzModalService } from 'ng-zorro-antd/modal';
import Parse from 'parse';
import { CompUploadComponent } from '../../../../app/comp-upload/comp-upload.component';
import { DatePipe } from '@angular/common';
// import {
//   FormControl,
//   FormGroup,
//   NonNullableFormBuilder,
//   Validators,
//   ValidatorFn,
//   AbstractControl,
// } from '@angular/forms';
import { textbookServer } from '../../../../services/textbook';
// import * as eduTextBook from '../../../../services/EduTextbook';
// import { HttpClient } from '@angular/common/http';
// import { Router } from '@angular/router';
// import { FormBuilder } from '@angular/forms';

@Component({
  imports: [
    CommonCompModule,
    ReactiveFormsModule,
    NzSelectModule,
    NzRadioModule,
    NzGridModule,
    NzCheckboxModule,
    NzTableModule,
    NzUploadModule,
    CompUploadComponent,
    DatePipe,
  ],
  standalone: true,
  selector: 'app-faith',
  templateUrl: './faith.component.html',
  styleUrls: ['./faith.component.scss'],
  providers: [DatePipe],
})
export class FaithComponent 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>();

  value: string = '';

  /**上传签名页 */
  authorSignPDF: any = {
    name: '',
    url: '',
  };

  /**申报单位承诺意见 */
  unitMaterial: any = {
    name: '',
    url: '',
  };

  get authStatus():boolean{
    return this.value == '本人自愿参加此次申报，已认真填写并检查以上材料，保证内容真实。'
  }

  constructor(
    public tbookSer: textbookServer,
    private msg: NzMessageService,
    private modal: NzModalService,
    // private http: HttpClient,
    // private router: Router,
    // private formBuilder: FormBuilder,
    // private fb: NonNullableFormBuilder
  ) {}
  ngOnInit() {
    if (this.eduTextbook.id) {
      this.value = this.eduTextbook.get('accept') || '';
      this.authorSignPDF = this.eduTextbook.get('authorSignPDF') || {
        name: '',
        url: '',
      };
      this.unitMaterial = this.eduTextbook.get('unitMaterial') || {
        name: '',
        url: '',
      };
    }
  }

  async submitForm(event?: string): Promise<void> {
    await this.saveEduTextbook();
    if (event == 'pre') {
      //上一步
      this.state.emit({ type: 'pre' });
      return;
    }
    if (event == 'next') {
      //下一步
      this.state.emit({ type: 'next', textBook: this.eduTextbook });
    } else if (event == 'save') {
      this.modal.success({
        nzTitle: '保存成功',
        nzContent: '<p>已保存并且至空间</p>',
        nzOnOk: () => console.log('Info OK'),
      });
      return;
    }
  }

  async saveEduTextbook() {
    if (!this.eduTextbook) {
      this.msg.error('请先创建教材');
      return;
    }

    let isComplete = this.verify()

    this.eduTextbook?.set('user', Parse.User.current()?.toPointer());
    this.eduTextbook?.set('company', {
      __type: 'Pointer',
      className: 'Company',
      objectId: this.tbookSer.company,
    });
    // params.unitMaterial &&
    //   this.eduTextbook?.set('unitMaterial',{text:params.unitMaterial} );
    this.value && this.eduTextbook?.set('accept', this.value);
    this.authorSignPDF && this.eduTextbook?.set('authorSignPDF', this.authorSignPDF);
    this.unitMaterial && this.eduTextbook?.set('unitMaterial', this.unitMaterial);

    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');
    }
    if(isComplete){
      this.eduTextbook.set('complete', true)
    }else{
      this.msg.warning('保存成功，但存在未填写完成项');
    }
    this.eduTextbook?.set('exportPDF', null)//重置导出文件地址
    await this.eduTextbook?.save();
    return;
  }
  verify():boolean{
    if (
      this.value !=
      '本人自愿参加此次申报，已认真填写并检查以上材料，保证内容真实。'
    ) {
      this.msg.error('诚信承诺输入错误，请正确输入（注意标点符号）');
      return false
    }
    if(!this.authorSignPDF?.url || !this.unitMaterial?.url){
      return false
    }
    return true
  }
  upload(e: any, type: string) {
    console.log(e);
    let file = e[e?.length - 1 || 0];
    if (type == 'unitMaterial' || type == 'authorSignPDF') {
      this[type].url = file?.url;
      this[type].name = file?.name;
    }
  }

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

  // downloadFile(fileName: string) {
  //   // let fileName = '十四五”普通高等教育本科国家级规划教材第一次遴选推荐申报表.docx'
  //   const 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);
  //   })
  // }
  // openFile(url: string) {
  //   console.log(url);
  //   window.open(url);
  // }

  // changeAccept() {
  //   console.log(this.value);
  //   let str = '本人自愿参加此次申报，已认真填写并检查以上材料，保证内容真实。';
  //   if (str.indexOf(this.value) == -1) {
  //     this.msg.create('warning', '请正确输入内容');
  //   }
  // }
}
