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 {
  FormControl,
  FormGroup,
  NonNullableFormBuilder,
  Validators,
  ValidatorFn,
  AbstractControl,
} from '@angular/forms';
interface opinionType {
  name: string;
  unit: string;
  birth: Date | any;
  nationality: string;
  reviewFile: string | object;
}
import { textbookServer } from '../../../../services/textbook';
@Component({
  selector: 'app-attachment',
  imports: [
    CommonCompModule,
    ReactiveFormsModule,
    NzSelectModule,
    NzRadioModule,
    NzGridModule,
    NzCheckboxModule,
    NzTableModule,
    NzUploadModule,
  ],
  standalone: true,
  templateUrl: './attachment.component.html',
  styleUrls: ['./attachment.component.scss'],
})
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 {};
  };

  validateForm: FormGroup<{
    textbookTypes: FormControl<Array<string> | any>; //教材电子版
    textbookFiles: FormControl<Array<string> | any>; //上传教材文件
    links: FormControl<string>; //教材数字内容链接地址、账号
    selfResults: FormControl<object | any>; //图书编校质量自查结果记录表
    expertOpinion: FormControl<object | any>; //专家审核意见表
    evidence: FormControl<object | any>; //教材使用情况证明材料
    moreMaterial: FormControl<Array<any> | any>; //其他材料
    unitMaterial: FormControl<object | any>; //申报单位承诺意见材料
    accept: FormControl<string>; //填写诚信承诺
  }> = this.fb.group({
    textbookTypes: [''],
    textbookFiles: [
      [
        {
          url: 'https://www.jyvtc.edu.cn/yssj/resource/cms/2022/01/2022010610314324023.pdf',
        },
      ],
      [Validators.required]
    ],
    links: ['', [Validators.required]],
    selfResults: [
      {
        name: '自查表.pdf',
        url: 'https://www.jyvtc.edu.cn/yssj/resource/cms/2022/01/2022010610314324023.pdf',
      },
      [Validators.required]
    ],
    expertOpinion: [
      {
        name: '自查表.pdf',
        url: 'https://www.jyvtc.edu.cn/yssj/resource/cms/2022/01/2022010610314324023.pdf',
      },
      [Validators.required]
    ],
    evidence: [
      {
        name: '材料.pdf',
        url: 'https://www.jyvtc.edu.cn/yssj/resource/cms/2022/01/2022010610314324023.pdf',
      },
      [Validators.required]
    ],
    moreMaterial: [
      [
        {
          name: '材料1.pdf',
          url: 'https://www.jyvtc.edu.cn/yssj/resource/cms/2022/01/2022010610314324023.pdf',
        },
        {
          name: '材料2.pdf',
          url: 'https://www.jyvtc.edu.cn/yssj/resource/cms/2022/01/2022010610314324023.pdf',
        },
      ],
    ],
    unitMaterial: [
      {
        name: '承诺意见表.pdf',
        url: 'https://www.jyvtc.edu.cn/yssj/resource/cms/2022/01/2022010610314324023.pdf',
      },
      [Validators.required]
    ],
    accept: ['', [Validators.required, this.confirmationValidator]],
  });
  checkOptionsOne = [
    { label: '纸质教材', value: '纸质教材', checked: true },
    { label: '电子教材 / 资源', value: '电子教材 / 资源', checked: true },
  ];
  //所有作者政治审查意见
  opinions: Array<opinionType> = [
    {
      name: '', //作者
      unit: '', //单位
      birth: '', //出生年月
      nationality: '', //国籍
      reviewFile: {
        name: '自查表.pdf',
        url: 'https://www.jyvtc.edu.cn/yssj/resource/cms/2022/01/2022010610314324023.pdf',
      }, //作者政治审查表/作者签名
    },
  ];
  //所有作者签名
  authorSign: Array<opinionType> = [
    {
      name: '', //作者
      unit: '', //单位
      birth: '', //出生年月
      nationality: '', //国籍
      reviewFile: {
        name: '审查表.pdf',
        url: 'https://www.jyvtc.edu.cn/yssj/resource/cms/2022/01/2022010610314324023.pdf',
      }, //作者政治审查表/作者签名
    },
  ];
  constructor(
    public tbookSer: textbookServer,
    private fb: NonNullableFormBuilder,
    private msg: NzMessageService,
    private modal: NzModalService
  ) {}
  ngOnInit() {
    if (this.eduTextbook.id) {
      this.validateForm = this.fb.group({
        textbookTypes: [
          this.eduTextbook.get('textbookTypes'),
        ],
        textbookFiles: [
          this.eduTextbook.get('textbookFiles') ||
            this.validateForm.value.textbookFiles,
          [Validators.required]
        ],
        links: [
          this.eduTextbook.get('links')?.join('\n') || '',
          [Validators.required]
        ],
        selfResults: [
          this.eduTextbook.get('selfResults') ||
            this.validateForm.value.selfResults,
          [Validators.required]
        ],
        expertOpinion: [
          this.eduTextbook.get('expertOpinion') ||
            this.validateForm.value.expertOpinion,
          [Validators.required]
        ],
        evidence: [
          this.eduTextbook.get('evidence') || this.validateForm.value.evidence,
          [Validators.required]
        ],
        moreMaterial: [''],
        unitMaterial: [
          this.eduTextbook.get('unitMaterial') ||
            this.validateForm.value.unitMaterial,
          [Validators.required]
        ],
        accept: [
          this.eduTextbook.get('accept') || '',
          [Validators.required, this.confirmationValidator]
        ],
      });
      this.opinions = this.eduTextbook.get('opinions') || this.opinions
      this.authorSign = this.eduTextbook.get('authorSign') || this.authorSign
    }
  }
  async submitForm(event?: string): Promise<void> {
    if (event == 'pre') {
      this.state.emit({ type: 'pre' });
      return;
    }
    console.log(this.validateForm.value);
    let opinionsVrifly = !this.opinions.some((item) =>
      Object.values(item).some((val) => val == '' || val == undefined)
    );
    let authorSignVrifly = !this.authorSign.some((item) =>
      Object.values(item).some((val) => val == '' || val == undefined)
    );
    let params: any = this.validateForm.value;
    if (this.validateForm.valid) {
      console.log(this.validateForm.value);
      if (event == 'complete') {
        if (!opinionsVrifly) {
          this.msg.warning('所有作者政治审查意见填写不完整');
          return;
        }
        if (!authorSignVrifly) {
          this.msg.warning('上传所有作者签名填写不完整');
          return;
        }
        await this.saveEduTextbook(params, true);
        let textBookJson = this.eduTextbook.toJSON()
        let ignoreFiled = ['typeNumber','importantProjectOther','createdAt','updatedAt'] //非必填字段
        console.log(textBookJson);
        let isVrifly = Object.keys(textBookJson).some((item:string)=>{
          if(!ignoreFiled.includes(item) && (textBookJson[item] === '' || textBookJson[item] === undefined || textBookJson[item] === null)){
            console.warn('字段未填写:'+item);
            return true
          }
          return
        })
        if(isVrifly){
          this.msg.warning('存在未填项')
          return
        }
        this.state.emit({ type: 'complete', textBook: this.eduTextbook });
        this.eduTextbook.set('complete', true)
        this.eduTextbook.set('status', '102')
        await this.eduTextbook.save()
        this.msg.success('已填写完成')
      }
    } else {
      if (event == 'save') {
        await this.saveEduTextbook(params, this.validateForm.valid && opinionsVrifly && authorSignVrifly);
        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('请填写完整信息');
    }
    if (event == 'save') {
      await this.saveEduTextbook(params, this.validateForm.valid && opinionsVrifly && authorSignVrifly);
      this.modal.success({
        nzTitle: '您已填写完成',
        nzContent: '<p>已保存并且至空间</p>',
        nzOnOk: () => console.log('Info OK'),
      });
    }
  }
  changeCode() {}
  getCode(e: any) {}
  //添加作者信息
  onPush(type: string, idx: number) {
    switch (type) {
      case 'opinions':
        this.opinions.splice(idx + 1, 0, {
          name: '', //作者
          unit: '', //单位
          birth: '', //出生年月
          nationality: '', //国籍
          reviewFile: '', //作者政治审查表/作者签名
        });
        break;
      case 'authorSign':
        this.authorSign.splice(idx + 1, 0, {
          name: '', //作者
          unit: '', //单位
          birth: '', //出生年月
          nationality: '', //国籍
          reviewFile: '', //作者政治审查表/作者签名
        });
        break;
    }
  }
  //删除作者信息
  onDel(type: string, idx: number) {
    switch (type) {
      case 'opinions':
        if (this.opinions.length <= 1) {
          this.opinions = [
            {
              name: '', //作者
              unit: '', //单位
              birth: '', //出生年月
              nationality: '', //国籍
              reviewFile: '', //作者政治审查表/作者签名
            },
          ];
          return;
        }
        this.opinions.splice(idx, 1);
        break;
      case 'authorSign':
        if (this.authorSign.length <= 1) {
          this.authorSign = [
            {
              name: '', //作者
              unit: '', //单位
              birth: '', //出生年月
              nationality: '', //国籍
              reviewFile: '', //作者政治审查表/作者签名
            },
          ];
          return;
        }
        this.authorSign.splice(idx, 1);
        break;
    }
  }
  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 saveEduTextbook(params: any, isComplete: boolean) {
    console.log(params);
    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.textbookTypes &&
      this.eduTextbook?.set('textbookTypes', params.textbookTypes);
    params.textbookFiles &&
      this.eduTextbook?.set('textbookFiles', params.textbookFiles);
    let links = params.links.split(/[(\r\n)\r\n]+/);
    links && this.eduTextbook?.set('links', links);
    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.moreMaterial &&
      this.eduTextbook?.set('moreMaterial', params.moreMaterial);
    params.accept && this.eduTextbook?.set('accept', params.accept);
    this.opinions && this.eduTextbook?.set('opinions', this.opinions);
    this.authorSign && this.eduTextbook?.set('authorSign', this.authorSign);
    await this.eduTextbook?.save();
    return;
  }
}
