import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef} from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';

interface QuestionType {
  id: number;
  questionIndex: string;
  questionTitle: string;
  // questionType: string;
  questionAnswer: string;
  questionExplain: string;
  questionOptionA: string;
  questionOptionB: string;
  questionOptionC: string;
  questionOptionD: string;
}

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit, OnDestroy {

  // 储存数据用
  saveKey = 'JM_12';
  // 储存对象
  item;
  // title = '';
  // lens = '';
  // contents = '';
  // questions = [];
  validateForm: FormGroup;
  questionsOfControl: Array<QuestionType> = [];

  constructor(private appRef: ApplicationRef,
              private fb: FormBuilder,
              private nzMessageService: NzMessageService,
              private changeDetectorRef: ChangeDetectorRef) {
    // @ts-ignore
    window.f = this;
  }
  addField(qItem?: QuestionType|Event): void {
    // if (e) {
    //   e.preventDefault();
    // }
    const id = this.questionsOfControl.length > 0 ? this.questionsOfControl[this.questionsOfControl.length - 1].id + 1 : 0;
    const control  = {
      id,
      questionIndex: `${id}`,
      questionTitle: `questionTitle_${id}`,
      // questionType: `questionType_${id}`,
      questionAnswer: `questionAnswer_${id}`,
      questionExplain: `questionExplain_${id}`,
      questionOptionA: `questionOptionA_${id}`,
      questionOptionB: `questionOptionB_${id}`,
      questionOptionC: `questionOptionC_${id}`,
      questionOptionD: `questionOptionD_${id}`,
    };

    const index = this.questionsOfControl.push(control);
    // console.log(this.questionsOfControl[this.questionsOfControl.length - 1]);
    this.validateForm.addControl(
      this.questionsOfControl[index - 1].questionTitle,
      new FormControl(qItem ? qItem['questionTitle'] : null, Validators.required)
    );
    // this.validateForm.addControl(
    //   this.questionsOfControl[index - 1].questionType,
    //   new FormControl(0, Validators.required)
    // );
    this.validateForm.addControl(
      this.questionsOfControl[index - 1].questionAnswer,
      new FormControl(qItem ? qItem['questionAnswer'] : 0, Validators.required)
    );
    this.validateForm.addControl(
      this.questionsOfControl[index - 1].questionExplain,
      new FormControl(qItem ? qItem['questionExplain'] : '', Validators.required)
    );

    this.validateForm.addControl(
      this.questionsOfControl[index - 1].questionOptionA,
      new FormControl(qItem ? qItem['questionOptionA'] : '', Validators.required)
    );
    this.validateForm.addControl(
      this.questionsOfControl[index - 1].questionOptionB,
      new FormControl(qItem ? qItem['questionOptionB'] : '', Validators.required)
    );
    this.validateForm.addControl(
      this.questionsOfControl[index - 1].questionOptionC,
      new FormControl(qItem ? qItem['questionOptionC'] : '', Validators.required)
    );
    this.validateForm.addControl(
      this.questionsOfControl[index - 1].questionOptionD,
      new FormControl(qItem ? qItem['questionOptionD'] : '', Validators.required)
    );

  }

  removeField(i: QuestionType, e: MouseEvent): void {
    e.preventDefault();
    if (this.questionsOfControl.length > 1) {
      const index = this.questionsOfControl.indexOf(i);
      this.questionsOfControl.splice(index, 1);
      console.log(this.questionsOfControl);
      this.validateForm.removeControl(`questionTitle_${i.questionIndex}`);
      this.validateForm.removeControl(`questionAnswer_${i.questionIndex}`);
      this.validateForm.removeControl(`questionExplain_${i.questionIndex}`);
      this.validateForm.removeControl(`questionOptionA_${i.questionIndex}`);
      this.validateForm.removeControl(`questionOptionB_${i.questionIndex}`);
      this.validateForm.removeControl(`questionOptionC_${i.questionIndex}`);
      this.validateForm.removeControl(`questionOptionD_${i.questionIndex}`);

    }
  }
  submitForm(): void {
    console.log('submit');
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.status !== 'VALID') {
      return ;
    }
    const title = this.validateForm.controls['title'].value || 'Read and answer.';
    const lens = this.validateForm.controls['lens'].value;
    const contents = this.validateForm.controls['contents'].value;
    const analysis = this.validateForm.controls['analysis'].value;
    const questions = [];
    const idxCache = [];
    for (const name in this.validateForm.controls) {
      const idxReg = /\d+/.exec(name);
      if (idxReg === null) {
        continue;
      }

      const idx = idxReg[0];
      if (idxCache.includes(idx)) {
        continue;
      }
      idxCache.push(idx);

      const questionTitle = this.validateForm.controls[`questionTitle_${idx}`].value;
      const questionAnswer = this.validateForm.controls[`questionAnswer_${idx}`].value;
      const questionExplain = this.validateForm.controls[`questionExplain_${idx}`].value;
      const questionOptionA = this.validateForm.controls[`questionOptionA_${idx}`].value;
      const questionOptionB = this.validateForm.controls[`questionOptionB_${idx}`].value;
      const questionOptionC = this.validateForm.controls[`questionOptionC_${idx}`].value;
      const questionOptionD = this.validateForm.controls[`questionOptionD_${idx}`].value;
      questions.push({
        questionTitle,
        questionAnswer,
        questionExplain,
        questionOptionA,
        questionOptionB,
        questionOptionC,
        questionOptionD,

      });
    }

    this.item = {
      title,
      lens ,
      contents,
      analysis,
      questions
    };
    this.save();
    this.nzMessageService.success('保存成功');
  }
  ngOnInit() {
    this.validateForm = this.fb.group({
      title: ['Read and answer.', [Validators.required]],
      lens: ['', [Validators.required]],
      analysis: ['', [Validators.required]],
      contents: ['', [Validators.required]],
    });
    this.item = {};

    // 获取存储的数据
    (window as any).courseware.getData((data) => {

      if (data) {
        this.item = data;
      }

      this.init(data);
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();

    }, this.saveKey);

  }
  changeQuestionType(typeName, val) {
    console.log(typeName, val);
  }




  ngOnDestroy() {
  }



  init(data) {
    console.log('init', data);
    this.validateForm = this.fb.group({
      title: [data && data.title ? data.title : 'Read and answer.' , [Validators.required]],
      lens: [data?.lens, [Validators.required]],
      analysis: [data?.analysis, [Validators.required]],
      contents: [data?.contents, [Validators.required]],
    });
    if (data?.questions && Array.isArray(data?.questions)) {
      data.questions.forEach((q, idx) => {
        this.addField(q);
      });
    } else {
      this.addField();
    }

  }


  /**
   * 储存图片数据
   */
  onImageUploadSuccess(e, key) {

      this.item[key] = e.url;
      this.save();
  }

  /**
   * 储存音频数据
   */
  onAudioUploadSuccess(e, key) {

    this.item[key] = e.url;
    this.save();
  }



  /**
   * 储存数据
   */
  save() {
    console.log(this.item);
    (window as any).courseware.setData(this.item, null, this.saveKey);
    this.refresh();
  }

  /**
   * 刷新 渲染页面
   */
  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }

}

