import {FormGroup} from '@angular/forms';
import {BsModalRef} from 'ngx-bootstrap';
import {FramePageComponent} from './FramePageComponent';
import {ElementRef, ViewChild} from '@angular/core';
import {AjaxService} from '../../../core/ajax/ajax.service';
import {MsgService} from '../../../core/msg/msg.service';
import {DomSanitizer} from '@angular/platform-browser';
import {FrameService} from '../../../core/frame/frame.service';

export class FrameEditComponent {
  // 当前模式
  editModel = 'add';
  frameService: any;
  // 验证表单
  valForm: FormGroup;

  currentEntity :any;
  bsModalRef: BsModalRef;
  ResponseEntity: any;
  ResponseMap: any;
  ResponseArray: any;
  sanitizer = AjaxService.sanitizer;


  // 父窗口
  framePageComponent: FramePageComponent;

  // 自动焦点
  @ViewChild('elAutoFocus', {static: false}) elAutoFocus: ElementRef;

  constructor(...args) {
    this.frameService = FrameService;
    for (const s of args) {
      if (s instanceof BsModalRef) {
        this.bsModalRef = s;
      }
      if (s instanceof DomSanitizer) {
        this.sanitizer = s;
      }
    }
    this.currentEntity = {};
    setTimeout(() => {
      // console.log(this.bsModalRef);
      this.framePageComponent = this.bsModalRef.content['FramePageComponent'];
      if (this.bsModalRef.content['ResponseEntity'] !== undefined) {
        this.currentEntity = Object.assign({}, this.bsModalRef.content['ResponseEntity']);
        this.editModel = 'edit';
      }
      this.initDefautEntity();
    }, 1);

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


  /*************
   * 初始化编辑对象，子类请直接覆盖此方法
   */
  initDefautEntity() {
  }


  // 关闭窗体
  closeWindow() {
    if (this.bsModalRef.content['closeCallback'] !== undefined) {
      this.bsModalRef.content['closeCallback'].call(undefined, this.bsModalRef.content);
    }
    this.bsModalRef.hide();
  }



  /*************
   * 提交表单前可自定义一些赋值，子类请直接覆盖此方法
   */
  beforeSubmitForm() {
    return true;
  }

  // 提交表单
  submitForm(url: string, param?: { data?: {}, successMsg?: string, confirmMsg?: string, autoClose?: boolean, RequestWithLoading?: boolean }, callback?: Function) {
    if(!this.beforeSubmitForm()){
      return;
    }
    this.valForm.markAllAsTouched();
    if (!this.validForm()) {
      return;
    }
    // 判断是否有修改
    if (this.ResponseEntity !== undefined) {
      let hasChange = false;
      for (const s in this.currentEntity) {
        if (this.currentEntity[s] !== this.ResponseEntity[s]) {
          hasChange = true;
          break;
        }
      }
      if (!hasChange) {
        MsgService.warnToaster('没有进行任何修改，无需提交服务器操作！');
        return;
      }
    }

    if (param === undefined) {
      param = {};
    }
    if (param.successMsg === undefined) {
      param.successMsg = '操作成功！';
    }
    if (param.autoClose === undefined) {
      param.autoClose = true;
    }
    if (param.RequestWithLoading === undefined) {
      param.RequestWithLoading = true;
    } else {
      param.RequestWithLoading = false;
    }
    const fn = function () {
      AjaxService.request(url, Object.assign({}, this.currentEntity, param.data), (data) => {
        MsgService.successToaster(param.successMsg);
        // 将表单设置为未触碰
        this.UntouchedForm();
        // 将当前的数据保存到历史中
        this.ResponseEntity = Object.assign({}, this.currentEntity);
        if (callback) {
          callback.apply(this, data);
        }
        if (param.autoClose === true) {
          this.closeWindow();
        }

      }, {RequestWithLoading: param.RequestWithLoading});
    }.bind(this);

    if (param.confirmMsg) {
      MsgService.confirm(param.confirmMsg, fn);
    } else {
      fn.apply(undefined);
    }


  }

  // 将表单设置为未使用过状态
  UntouchedForm() {
    this.valForm.markAsUntouched();
  }

  // 判断表单是否通过了验证
  validForm(): boolean {
    this.valForm.markAllAsTouched();
    return this.valForm.valid;
  }


  ajaxDownload(url: string, param?: any) {
    AjaxService.ajaxDownload(url, param);
  }
}
