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>();

  /**申报单位承诺意见 */
  unitMaterial: any = {
    name: '',
    url: '',
  };
  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.validateForm = this.fb.group({
      //   // unitMaterial: [this.eduTextbook.get('unitMaterial')?.text||'' , [Validators.maxLength(200)]],
      //   accept: [this.eduTextbook.get('accept') || '', [Validators.required]],
      // });
    }
  }
  value: string = '';

  async submitForm(event?: string): Promise<void> {
    if (
      this.value !=
      '本人自愿参加此次申报，已认真填写并检查以上材料，保证内容真实。'
    ) {
      this.msg.error('诚信承诺输入错误，请正确输入（注意标点符号）');
      // return
    }
    // let params: any = this.validateForm.value;
    // console.log(params)
    let params = { accept: this.value };
    await this.saveEduTextbook(params);

    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(params: any) {
    if (!this.eduTextbook) {
      this.msg.error('请先创建教材');
      return;
    }
    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} );
    params.accept && this.eduTextbook?.set('accept', params.accept);
    if (
      this.eduTextbook.get('status') == '102' &&
      this.value !=
        '本人自愿参加此次申报，已认真填写并检查以上材料，保证内容真实。'
    ) {
      this.eduTextbook?.set('status', '101');
      this.eduTextbook.set('complete', false);
    } else if (!this.eduTextbook.get('status')) {
      this.eduTextbook?.set('status', '101');
    }
    if (
      this.value ==
      '本人自愿参加此次申报，已认真填写并检查以上材料，保证内容真实。'
    ) {
      this.eduTextbook.set('complete', true);
    }
    await this.eduTextbook?.save();
    return;
  }
  // upload(e: any, type: string, index?: any) {
  //   let file = e[(e?.length - 1) || 0];
  //   if(type=='unitMaterial'){
  //     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)
  // }

  // validateForm: FormGroup<{
  //   // unitMaterial: FormControl<string | null>;
  //   accept: FormControl<string | null>;
  // }> = this.formBuilder.group({
  //   // unitMaterial: ['', [Validators.maxLength(200)]],
  //   accept: ['', [Validators.maxLength(100)]]

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