import {Component, ElementRef, OnInit, ViewChild, TemplateRef, Input, EventEmitter, Output} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {CustomValidators} from 'ng2-validation';
import {FramePagerComponent} from '../../core/pager/pager.component';
import {FrameRequest} from '../../shared/frame/frame-request';
import {FrameFunction} from '../../shared/frame/frame_function';
import {AppComponent} from '../../app.component';

import { BsModalService } from "ngx-bootstrap/modal/bs-modal.service";

import * as _ from 'lodash';

declare var $: any;
const SHOW_EDIT_TYPE = {
  "MODAL":"modal",
  "ONLY":"only",
  "SHOW":"show",
};

@Component({
  selector: 'flex-table',
  templateUrl: './FlexTable.component.html'
})


export class FlexTableComponent implements OnInit {
  public query = {}
  
  @ViewChild('framePager')
  framePager:FramePagerComponent;

  @Output() 
  init = new EventEmitter()

  item: any;
  public formModel: FormGroup
  
  // @ViewChild('tpl')
  // tpl: TemplateRef<any>
  
  //子组建自定义模板
  // editFormTemplate: TemplateRef<any>


  public editShowType = null;
  bsModalWin: any

  QUERY_URL= "";
  DELETE_URL= "";
  GET_URL= "";
  ADD_URL= "";
  EDIT_URL= "";


  public constructor(
    public bsModalService ?: BsModalService,
  ) {

  }

  ngOnInit() {

  }
  ngAfterViewInit() {
    this.init.emit(this);
  }

  //查询前置事件: 处理请求参数
  search(param){
    let searchCondition = this.query;
   
    for (const key in searchCondition) {
      if (searchCondition.hasOwnProperty(key)) {
        const element = searchCondition[key];
         //解决flexSelect 重置查询参数后值为null的问题
        if(element == null) searchCondition[key] = "";
      }
    }
    //参数合并
    _.assignIn(param,searchCondition);
  }

  reset(){
      for (let key in this.query) {
        console.log(key);
        
        if (this.query.hasOwnProperty(key)) {
          this.query[key] = "";
        }
      } 
  }

  async shouModalWin(editFormTemplateModal, modalcss?) {
    if(! await this.preShowModalWin()) return;
    let css = modalcss ? modalcss : "modal-lg";
    this.bsModalWin = this.bsModalService.show(editFormTemplateModal, { class: css });
  }

  showEdit(template: TemplateRef<any>, editShowType ,modalcss){
    if(editShowType == SHOW_EDIT_TYPE.MODAL) {
      this.shouModalWin(template,modalcss);
    }else{
      this.editShowType = editShowType;
    }
  }


  // editShowType : modal模态弹出框 only只显示编辑界面 show 同时显示
 async goEdit(template: TemplateRef<any>,editShowType = SHOW_EDIT_TYPE.MODAL,modalcss:string,item?){
   
  FrameFunction.UntouchedForm(this.formModel);
   //新增
   if(!item || item.id === undefined) {
      if(! await this.preGoEditEvent()) return ;
      if(!this.item) {
        this.item = {};
      } 
      this.formModel.reset();
      this.showEdit(template, editShowType, modalcss);
      this.aftGoEditEvent();
    } else {
      FrameRequest.requestEntity(this.GET_URL,{id: item.id}, async (entity) => {
        if(! await this.preGoEditEvent(entity)) return ;
        this.showEdit(template, editShowType, modalcss);
        setTimeout(async ()=>{
          this.item = entity;
          this.aftGoEditEvent();
        },100)
      });
    }
  }
 
 async delete(item?){
    if(! await this.preDeleteEvent()) return;
    //批量操作
    if(!item){
      let checkedArray = this.framePager.getCheckedArray();
      if(checkedArray.length === 0){
        AppComponent.alert({title:"信息提示",text:"请选择数据!"})
        return;
      }
    }
    AppComponent.confirm("确定删除",()=>{
      let checkedArray = [];
      item ? checkedArray[0] = item.id: 
             checkedArray = this.framePager.getCheckedArray((item)=>item.id)
      
      // if(checkedArray.length === 0){
      //   AppComponent.alert({title:"信息提示",text:"请选择数据!"})
      //   return;
      // }
      FrameRequest.requestMap(this.DELETE_URL, {ids:checkedArray.join()}, () => {
        AppComponent.GobalComponent.successMsg('数据删除成功');
        this.aftDeleteEvent();
        this.framePager.reload();
      });
    })


  }

 async save() {
    if (!FrameFunction.validForm(this.formModel)) {
      return;
    }
    let url = this.item.id ? this.EDIT_URL: this.ADD_URL;
    if(!await this.preSaveEvent()) return;
    if(_.isUndefined(this.item.id)) delete this.item.id;
    //循环判断元素是否undefined
    for (const key in this.item) {
      if(this.item[key] === undefined) {
        this.item[key] = "";
      }
    }
    FrameRequest.requestEntity(url, this.item, async () => {
      AppComponent.GobalComponent.successMsg('信息保存成功');
      this.aftSaveEvent();
      this.framePager.reload();
      if(this.bsModalWin)this.bsModalWin.hide();
      this.resetPage();
    });
  }

  resetPage(){
    this.item = null;
    this.editShowType = null
  }

  hideModal(){
    if(this.bsModalWin) this.bsModalWin.hide();
    this.resetPage();
  }

  async preShowModalWin(){
    return true
  }
  //参数处理
  async preGoEditEvent(entity?){
    // var p = new Promise(function(resolve, reject){
    //     resolve(true);
    // });
    return true;
  }
  //参数处理
  async aftGoEditEvent(entity?){
    
  }
  async preDeleteEvent(){
    return true
  }
  async aftDeleteEvent(){

  }
  async preSaveEvent(){
    return true;
  }
  async aftSaveEvent(){

  }


}
