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



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

  // 储存数据用
  saveKey = 'ww_talk';
  // 储存对象
  item;
  validateForm: FormGroup;
  controlArray: Array<{
    // id: number, controlInstance: string
    // row_key: string,
    odd: {
      id: number,
      text: string,
      textInst: string,
      audioInst: string,
      progress: number,
      uploadStatus: string,
      uploading: boolean,
      audioId: number
    },
    even: {
      id: number,
      text: string,
      textInst: string,
      audioInst: string,
      progress: number,
      uploadStatus: string,
      uploading: boolean,
      audioId: number
    }
  }> = [];


  constructor(private appRef: ApplicationRef,
              private fb: FormBuilder,
              private changeDetectorRef: ChangeDetectorRef) {

  }


  ngOnInit() {

    this.item = {
      contentObj: {}
    };

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

      if (data) {
        this.item = data;
      }
      this.controlArray.length = 0;
      this.validateForm = this.fb.group({});
      if (this.item.contentObj.talk && Array.isArray(this.item.contentObj.talk) ) {
        for (let i = 0 ; i < this.item.contentObj.talk[0].length; i++ ) {
          const control = {
            // row_key: `row${i}`,
            odd: {
              id: i * 2,
              text: this.item.contentObj.talk[0][i].text,
              textInst: `text${i * 2 }`,
              audioInst: `audio${i * 2 }`,
              progress: 0,
              uploadStatus: '',
              uploading: false,
              audioId: this.item.contentObj.talk[0][i].audio
            },
            even: {
              id: i * 2 + 1,
              text: this.item.contentObj.talk[1][i].text,
              textInst: `text${i * 2 + 1}`,
              audioInst: `audio${i * 2 + 1}`,
              progress: 0,
              uploadStatus: '',
              uploading: false,
              audioId: this.item.contentObj.talk[1][i].audio
            }
          };
          this.addField(control);
        }
      } else {
        this.addField();
      }

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

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {

  }

  //
  // /**
  //  * 储存图片数据
  //  * @param e
  //  */
  // onImageUploadSuccess(e, key) {
  //
  //     this.item[key] = e.url;
  //     this.save();
  // }
  //
  // /**
  //  * 储存音频数据
  //  * @param e
  //  */
  // onAudioUploadSuccess(e, key) {
  //
  //   this.item[key] = e.url;
  //   this.save();
  // }



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

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

  addField(control?: any, e?: MouseEvent): void {
    if (e) {
      e.preventDefault();
    }
    const sts = this.checkForm();
    if (!sts) {
      return;
    }
    const id =   (this.controlArray.length > 0) ? (this.controlArray[ this.controlArray.length - 1 ].odd.id + 2) : 0;
    if (!control) {
      control = {
        // row_key: `row${id}`,
        odd: {
          id: id * 2,
          text: '',
          textInst: `text${id * 2 }`,
          audioInst: `audio${id * 2 }`,
          progress: 0,
          uploadStatus: '',
          uploading: false,
          audioId: 0
        },
        even: {
          id: id * 2 + 1,
          text: '',
          textInst: `text${id * 2 + 1}`,
          audioInst: `audio${id * 2 + 1}`,
          progress: 0,
          uploadStatus: '',
          uploading: false,
          audioId: 0
        }
      };
    }

    const index = this.controlArray.push(control);
    const row = this.controlArray[ index - 1 ];
    this.validateForm.addControl(
      row.odd.textInst,
      new FormControl(row.odd.text, Validators.required));
    this.validateForm.addControl(
      row.even.textInst,
      new FormControl(row.even.text, Validators.required));
    this.validateForm.addControl(
      row.odd.audioInst,
      new FormControl(row.odd.audioId));
    this.validateForm.addControl(
      row.even.audioInst,
      new FormControl(row.even.audioId));
  }

  removeField(i: any, e: MouseEvent): void {
    e.preventDefault();
    if (this.controlArray.length > 1) {
      const index = this.controlArray.indexOf(i);
      this.controlArray.splice(index, 1);
      // console.log(this.controlArray);
      this.validateForm.removeControl(i.odd.textInst);
      this.validateForm.removeControl(i.even.textInst);
      this.validateForm.removeControl(i.odd.audioInst);
      this.validateForm.removeControl(i.even.audioInst);
      this.saveForm(true);
    }

  }

  getFormControl(name: string): AbstractControl {
    console.log('getFormControl', name);
    return this.validateForm.controls[ name ];
  }
  checkForm(): boolean {
    const txts = Object.keys(this.validateForm.controls)
      .filter(c => c.startsWith('text') )
      .map(c => parseInt(c.replace('text', ''), 10));
    const cl = txts.length; // Object.keys(this.validateForm.controls).length / 2;
    if (cl === 0) {
      return true;
    }
    for (let i = 0 ; i < cl ; i += 2) {

      const k = txts[i];
      const c1 = this.validateForm.controls[`text${k}`];
      const c2 = this.validateForm.controls[`text${k + 1}`];
      if (!c1.value.trim() && !c2.value.trim() ) {
        c1.markAsDirty();
        c1.updateValueAndValidity();
        c1.setErrors({
          required: true
        });

        c2.markAsDirty();
        c2.updateValueAndValidity();
        c2.setErrors({
          required: true
        });
        return false;
      } else {
        c1.clearValidators();
        c2.clearValidators();
        c1.updateValueAndValidity();
        c2.updateValueAndValidity();
      }
    }
    return true;
    // for (const i in this.validateForm.controls) {
    //   console.log(i)
    //   const c = this.validateForm.controls[ i ];
    //   if (c.invalid) {
    //     c.markAsDirty();
    //     c.updateValueAndValidity();
    //     c.setErrors(c.errors);
    //     return false;
    //   }
    // }
    // return true;
  }
  handleAddAudio(info: { type: string, file: UploadFile, event: any }, control): void {
    switch (info.type) {
      case 'start':
        control.uploading = true;
        control.progress = 0;
        control.uploadStatus = 'active';
        break;
      case 'success':
        this.validateForm.controls[control.audioInst].setValue(info.file.response.res_id);
        console.log('info.file.response', info.file.response);
        control.uploading = false;
        control.audioId = info.file.response.res_id;
        // control.audioUploaded.emit(info.file.response);
        control.uploadStatus = '';
        this.saveForm();
        break;
      case 'progress':
        control.progress = parseInt(info.event.percent, 10);
        break;
    }
  }
  saveForm(forceUpdate?: boolean): void {
    if (!forceUpdate) {
      if (!this.validateForm.dirty) {
        return;
      }
      const sts = this.checkForm();
      if (!sts) {
        return;
      }
    }
    const ts = Object.keys(this.validateForm.value).filter(f => f.startsWith('text'));
    const ks = [];
    for (const t of ts) {
      const vk = parseInt(t.replace('text', ''), 10);
      ks.push(vk);
    }

    // const c = Object.keys(this.validateForm.value).length / 2;
    const s1 = [];
    const s2 = [];
    for (const  idx of  ks) {
      if (idx % 2 === 0) {
        s1.push({
          text: this.validateForm.value[`text${idx}`],
          audio: this.validateForm.value[`audio${idx}`]
        });
      } else {
        s2.push({
          text: this.validateForm.value[`text${idx}`],
          audio: this.validateForm.value[`audio${idx}`]
        });
      }
    }
    // console.log(this.validateForm.value, sts);
    this.item.contentObj.talk = [s1, s2];
    // console.log(this.item.contentObj);
    this.save();
  }


}

