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'


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

  //填写诚信承诺是否正确
  confirmationValidator: ValidatorFn = (
    control: AbstractControl
  ): { [s: string]: boolean } => {
    if (
      control.value !=
      '本人自愿参加此次申报，已认真填写并检查以上材料，保证内容真实'
    ) {
      return { required: true };
    }
    return {};
  };


  /** 版权页截图*/
  copyrightImgUrl: string = ''
  /** 中国版本图书馆CIP查询截图*/
  CIPImgUrl: string = ''
  /**cip证明材料 {name: '',url: '',} */
  cipProveFile: Array<any> = []
  /**图书编校质量自查结果记录表 */
  selfResults: any = {
    name: '',
    url: '',
  }
  /** 专家审查意见表*/
  expertOpinion: any = {
    name: '',
    url: '',
  }
  /** 教材使用情况证明材料*/
  evidence: any = {
    name: '',
    url: '',
  }
  /**其他材料 {name: '',url: '',} */
  moreMaterial: Array<any> = []

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


  // /**作者政治审核表 {name: '',url: '',} */
  // examine: Array<any> = []


  constructor(
    public tbookSer: textbookServer,
    private msg: NzMessageService,
    private modal: NzModalService,
    private http: HttpClient,
    private router: Router
  ) { }
  ngOnInit() {
    if (this.eduTextbook.id) {
      this.copyrightImgUrl = this.eduTextbook?.get('copyrightImgUrl') || this.copyrightImgUrl
      this.CIPImgUrl = this.eduTextbook?.get('CIPImgUrl') || this.CIPImgUrl
      this.selfResults = this.eduTextbook?.get('selfResults') || this.selfResults
      this.expertOpinion = this.eduTextbook?.get('expertOpinion') || this.expertOpinion
      this.evidence = this.eduTextbook?.get('evidence') || this.evidence
      this.moreMaterial = this.eduTextbook?.get('moreMaterial') || this.moreMaterial
      this.cipProveFile = this.eduTextbook?.get('cipProveFile') || this.cipProveFile
      this.unitMaterial = this.eduTextbook?.get('unitMaterial') || this.unitMaterial
      // this.examine = this.eduTextbook?.get('examine') || this.examine
      this.authorList = this.eduTextbook?.get('authorList')
    }
  }

  /**本页必填是否存在空项 */
  examineNull() {
    let isNull = false
    let msgList = []
    if (this.copyrightImgUrl == '' || !this.copyrightImgUrl) {
      msgList.push('版权页截图')
      isNull = true
    }
    // if (this.CIPImgUrl == '' || !this.CIPImgUrl) {
    //   if (this.cipProveFile?.length > 0) {
    //     let isExist = this.cipProveFile.every(item => item?.url == '' || !item?.url)
    //     if (isExist) {
    //       msgList.push('CIP 相关内容截图')
    //       isNull = true
    //     }
    //   } else {
    //       msgList.push('CIP 查询截图')
    //       isNull = true
    //   }
    // } 
    if (this.CIPImgUrl == '' || !this.CIPImgUrl) {
      msgList.push('CIP查询截图')
      isNull = true
    }
    if (this.cipProveFile?.length > 0) {
      let isExist = this.cipProveFile.every(item => item?.url == '' || !item?.url)
      if (isExist) {
        msgList.push('CIP证明材料')
        isNull = true
      }
    }
    if (this.selfResults.url == '' || !this.selfResults.url) {
      msgList.push('自查结果记录表')
      isNull = true
    }
    if (this.expertOpinion.url == '' || !this.expertOpinion.url) {
      msgList.push('专家审查意见表')
      isNull = true
    }
    if (this.evidence.url == '' || !this.evidence.url) {
      msgList.push('证明材料')
      isNull = true
    }
    if (this.moreMaterial?.length > 0) {
      let isExist = this.moreMaterial.every(item => item?.url == '' || !item?.url)
      if (isExist) {
        msgList.push('其他材料')
        isNull = true
      }
    }
    // if (this.examine?.length <= 0) {
    //   isNull = true
    //   msgList.push('作者政治审核表')
    // } else if (this.examine?.length > 0) {
    //   let isExist = this.examine.every(item => item?.url == '' || !item?.url)
    //   if (isExist) {
    //     msgList.push('作者政治审核表')
    //     isNull = true
    //   }
    // }
    // if (this.unitMaterial.url == '' || !this.unitMaterial.url) {
    //   msgList.push('申报单位承诺意见')
    //   isNull = true
    // }
    // if (isNull) {
    //   this.msg.create('error', `请上传完整 ${msgList.join()}`)
    // }
    return isNull
  }

  /**判断是否存在未填字段 */
  isIgnoreFiledNull() {
    let selectList = this.eduTextbook?.get('characteristic')
    let check = false
    for (let i in selectList) {
      if (selectList[i].label == '通识课' || selectList[i].label == '公共基础课' || selectList[i].label == '专业课') {
        if (selectList[i].checked) {
          check = true
          break;
        }
      }
    }
    if (!check) {
      // this.msg.create('warning', '请返回选择适用课程性质')
      return true
    }

    let eduColumn = eduTextBook.EduTextbook.fields
    let ignoreFiled = [
      'typeNumber', 'code', 'editionNumber', 'importantProjectOther',
      'textbookFiles', 'createdAt', 'updatedAt', 'copyright', 'authorSign',
      'CIP', 'isDeleted', 'opinions', 'printNumber', 'printSum', 'render',
      'importantProject', 'importantProjectOther', 'complete', 'links', 'recommend',
      'printSun', 'discard', 'edition', 'eduProcess', 'authors', 'editor',
      'copyrightImgUrl', 'CIPImgurl', 'selfResults', 'expertOpinion', 'evidence',
      'moreMaterial', 'unitMaterial', 'approvedImgUrl', 'department','CIPImgUrl','cipProveFile',
      'examine'
    ] //非必填字段
    let textBookJson = this.eduTextbook.toJSON()


    let isVrifly = Object.keys(eduColumn).some((item: string) => {
      if (!ignoreFiled.includes(item) && (textBookJson[item] === '' || textBookJson[item] === undefined || textBookJson[item] === null)) {
        console.warn('字段未填写:' + item)
        return true
      }
      return
    })
    /* 检验authorList字段是否留空 */
    let authorListAuth
    console.log(this.authorList);
    authorListAuth = this.authorList.some((obj:any)=>{
      return Object.keys(obj).some((item: string) => !obj[item])
    })
    // console.log(authorListAuth);

    if (isVrifly || authorListAuth) {
      // this.msg.warning('存在未填项')
      return true
    } else {
      return false
    }
  }

  async submitForm(event?: string): Promise<void> {
    let params = {
      copyrightImgUrl: this.copyrightImgUrl,
      CIPImgUrl: this.CIPImgUrl,
      cipProveFile: this.cipProveFile,
      selfResults: this.selfResults,
      expertOpinion: this.expertOpinion,
      evidence: this.evidence,
      moreMaterial: this.moreMaterial,
      // examine: this.examine,
      authorList:this.authorList
      // unitMaterial: this.unitMaterial,
    }
    let isPageNull = this.examineNull()//检查本页空项
    let isIgnoreFiled = this.isIgnoreFiledNull()//检查数据空项
    // console.log(isPageNull, isIgnoreFiled);
    if (event == 'pre') {//上一步
      this.state.emit({ type: 'pre' });
      return;
    }
    await this.saveEduTextbook(params, (!isPageNull && !isIgnoreFiled));
    if (event == 'complete') {
      this.state.emit({ type: 'complete', textBook: this.eduTextbook });
      if (isPageNull || isIgnoreFiled) {
        console.log('教材填写不完整');
      } else {
        this.eduTextbook.set('complete', true)
        this.eduTextbook.set('status', '102')
        await this.eduTextbook.save()
        this.msg.success('已填写完成')
      }
      this.router.navigate(['/nav-author/manage/space'])
    } else if (event == 'save') {
      this.modal.success({
        nzTitle: '保存成功',
        nzContent: '<p>已保存并且至空间</p>',
        nzOnOk: () => console.log('Info OK'),
      });
      return;
    }
  }

  async saveEduTextbook(params: any, isComplete: boolean) {
    console.log(isComplete);
    if (!this.eduTextbook) {
      this.msg.error('请先创建教材');
      return;
    }
    //如果填写未完整，仅保存，状态修改待完善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,
    });
    params.selfResults &&
      this.eduTextbook?.set('selfResults', params.selfResults);
    // params.unitMaterial &&
    //   this.eduTextbook?.set('unitMaterial', params.unitMaterial);
    params.expertOpinion &&
      this.eduTextbook?.set('expertOpinion', params.expertOpinion);
    params.evidence && this.eduTextbook?.set('evidence', params.evidence);
    params.cipProveFile &&
      this.eduTextbook?.set('cipProveFile', params.cipProveFile);
    params.moreMaterial &&
      this.eduTextbook?.set('moreMaterial', params.moreMaterial);
    // params.examine &&
    //   this.eduTextbook?.set('examine', params.examine);
    this.eduTextbook?.set('copyrightImgUrl', params.copyrightImgUrl);
    this.eduTextbook?.set('CIPImgUrl', params.CIPImgUrl);
    this.eduTextbook?.set('authorList', params.authorList);
    await this.eduTextbook?.save();
    return;
  }
  upload(e: any, type: string, index?: any) {
    let file = e[(e?.length - 1) || 0];
    if (type == 'copyrightImgUrl' || type == 'CIPImgUrl') {
      this[type] = file?.url
    } else if (type == 'selfResults' || type == 'expertOpinion' ||
      type == 'evidence' || type == 'unitMaterial') { 
      this[type].url = file?.url
      this[type].name = file?.name
    } else if (type == 'moreMaterial'  || type == 'cipProveFile') {
      this[type] = [...(this[type] || []), { name: file.name, url: file.url }]
    }else if (type == 'signature' || type == 'examine') {
      this.authorList[index][type] = file?.url
    }
    console.log(this.authorList)
  }



  /**获取文件名 */
  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 = `/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)
  }


  /**作者信息 */
  authorList:Array<any>=[]

   //添加作者信息
   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;
    }
  }
}
