import {Component, Directive, ElementRef, Type, ViewChild} from "@angular/core";
import {FormGroup} from "@angular/forms";
import {BsModalRef} from "ngx-bootstrap/modal";
import {FramePageComponent} from "../page/frame.page";
import {FuncService} from "../../../../core/service/func.service";
import {AjaxService} from "../../../../core/service/ajax.service";
import {FrameService} from "../../../../core/service/frame.service";
import {MsgService} from "../../../../core/service/msg.service";
import {VarService} from "../../../../core/service/var.service";
import {FramePager} from "../../../../core/frame/pager/frame-pager/frame-pager";
import {FrameAjax} from "../../../../core/frame/ajax/frame-ajax/frame-ajax";

/******************************
 * 弹出窗口基础类
 */
@Directive()
export class FrameDetailComponent {
  /*******************
   * 框架辅助，用于获取后台常量、参数等
   */
   FrameService: any;
  /********************
   * Ajax请求辅助类，用于后台请求
   */
   AjaxService: any;
  /********************
   * 常用函数辅助类
   */
   FuncService: any;
  /********************
   * 消息服务辅助类
   */
   MsgService: any;
  /********************
   * 变量辅助类
   */
   VarService: any;

  /************************
   * 当前模式 ,编辑还是新增
   */
   detailMode = 'add';

  /************************
   * 当前表单
   */
  public detailForm: FormGroup;

  /****************
   * 当前窗体句柄，用于关闭等操作
   * @private
   */
   bsModalRef: BsModalRef;

  /************************
   * 当前页面对应实体，初始化时和传递过来参数进行了同步
   */
  currentEntity: any;
  /***********************
   * 传递过来的单一实体
   */
  ResponseEntity: any;
  /*******************
   * 传递拖来的map
   */
  ResponseMap:any;
  /******************
   * 传递过来的数组
   */
  ResponseArray:any;

  /********************
   * 从哪个页面打开的
   */
  framePageComponent: FramePageComponent;
  // 分页组件
  @ViewChild('pager', {static: false}) pager: FramePager;
  // 分页组件
  @ViewChild('ajax', {static: false}) ajax: FrameAjax;
  /***************
   * 自动焦点
   */
  @ViewChild('elAutoFocus', {static: false}) elAutoFocus: ElementRef;

  /***********************
   * 初始化
   */
  constructor(...args) {

    // 初始化静态类
    this.FrameService = FrameService;
    this.AjaxService = AjaxService;
    this.FuncService = FuncService
    this.MsgService = MsgService;
    this.VarService = VarService;

    // 自动设置参数
    for (const s of args) {
      if (s instanceof BsModalRef) {
        this.bsModalRef = s;
      }
    }
    this.currentEntity = {};
    // 根据传递过来的参数来设置变量
    setTimeout(() => {
      this.framePageComponent = this.bsModalRef.content['FramePageComponent'];
      if (this.bsModalRef.content['ResponseEntity']) {
        this.currentEntity = Object.assign({}, this.bsModalRef.content['ResponseEntity']);
        this.detailMode = 'edit';
      }
      // 加载子类的初始化
      this.initDefautEntity();
      // 设置自动焦点
      setTimeout(() => {
        if (this.elAutoFocus)
          this.elAutoFocus.nativeElement.focus();
      }, 0);
    }, 0);
  }


  /*****************
   *  子类覆盖此方法初始化页面参数
   */
   initDefautEntity(): void {

  }

  /***********************
   * 关闭当前窗体
   */
   closeWindow() {
    if (this.bsModalRef.content['closeCallback']) {
      this.bsModalRef.content['closeCallback'].apply(undefined, [this.bsModalRef.content, this.currentEntity]);
    }
    this.bsModalRef.hide();
  }

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

  /*****************
   * 提交表单
   */
   submitForm(url: string, param?: { data?: {}, successMsg?: string, confirmMsg?: string, autoClose?: boolean, RequestWithLoading?: boolean }, callback?: Function) {
    // 是否有自定义检查
    if (!this.beforeSubmitForm()) {
      return;
    }
    // 标记所有组件获得过焦点，用于验证判断
    this.detailForm.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.warningToastr('没有进行任何修改，无需提交服务器操作！');
        return;
      }
    }
    if (!param) param = {};
    // 提交成功后的提示信息
    if (!param.successMsg) param.successMsg = '操作成功！';
    // 是否自动关闭，默认自动关闭当前窗体
    if (!param.autoClose) param.autoClose = true;
    // 是否显示加载条
    if (!param.RequestWithLoading) param.RequestWithLoading = true;
    else param.RequestWithLoading = false;

    const fn = function () {
      AjaxService.request(url, Object.assign({}, this.currentEntity, param.data), (data) => {
        MsgService.successToastr(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.confirmAlert(param.confirmMsg, fn);
    } else {
      fn.apply(undefined);
    }


  }

  /****************
   * 将表单设置为未使用过状态
   */
   untouchedForm(): void {
    this.detailForm.markAsUntouched();
  }

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