import {FramePagerComponent} from '../../core/pager/pager.component';
import {ElementRef, ViewChild} from '@angular/core';
import {FormGroup} from '@angular/forms';
import {FrameFunction} from '../../shared/frame/frame_function';
import {AppComponent} from '../../app.component';
import {FrameRequest} from '../../shared/frame/frame-request';

export class FrameAbstractComponent {
  viewStep: string = 'page';
  @ViewChild('page')
  page: FramePagerComponent;
  valForm: FormGroup;
  entity: any;

  @ViewChild('elAutoFocus')
  elAutoFocus: ElementRef;
  constructor( ... args) {
    this.viewStep = 'page';
    this.entity = {};
  }

  UntouchedForm() {
    FrameFunction.UntouchedForm(this.valForm);
  }

  validForm(): boolean {
    return FrameFunction.validForm(this.valForm);
  }

  goViewStep(step: string, entity?: any, url?: string, callback?: Function) {
    let vEntity = Object.assign({}, entity);
    if (vEntity === undefined) {
      vEntity = {};
    }
    if (step === 'add') {
      this.entity = vEntity;
      this.viewStep = step;
    } else {
      // 如果路径不为空，说明需要去服务器重新获取数据
      if (url !== undefined) {
        FrameRequest.request(url, entity, (data) => {
          this.entity = data.entity;
          if (callback) {
            callback.call(this, data);
          }
          this.viewStep = step;
        });
      } else {
        this.entity = vEntity;
        this.viewStep = step;
      }
    };

    setTimeout(() => {
        if (this.elAutoFocus) {
          this.elAutoFocus.nativeElement.focus();
        }
      }, 100);
  }

  submitForm(url: string, msg: string) {
    if (!this.validForm()) {
      return;
    }
    if (msg === undefined ) {
      msg = '操作成功！';
    }

    FrameRequest.requestEntity(`${url}/${this.viewStep}.htm`, this.entity, () => {
      AppComponent.GobalComponent.successMsg(msg);
      this.viewStep = 'page';
      this.page.reload();
    });
  }


  getStepName(): string {
    if (this.viewStep === 'page') {
      return '分页';
    } else if (this.viewStep === 'add') {
      return '新增';
    } else if (this.viewStep === 'edit') {
      return '编辑';
    }
    return this.viewStep;
  }
}
