import { FlexTableComponent } from './../../../../shared/common/FlexTable.component';
import { Component, OnInit, ViewChild } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal/bs-modal.service';
import { FrameRequest } from '../../../../shared/frame/frame-request';
import 'ztree';
import * as _ from 'lodash';
import { Validators, FormBuilder } from '@angular/forms';
import { CustomValidators } from 'ng2-validation';
import { AppComponent } from '../../../../app.component';
declare var $: any;

@Component({
  selector: 'app-pl-subject',
  templateUrl: './pl-subject.component.html',
  styleUrls: ['./pl-subject.component.scss']
})

export class PlSubjectComponent extends FlexTableComponent implements OnInit {

  setting = {
    data: {
      simpleData: {
        enable: true,
        idKey: 'id',
        pIdKey: 'pid',
        rootPid: -1
      }
    },
    check: {
      enable: false,
      chkStyle: "checkbox",
      chkboxType : { "Y" : "ps", "N" : "ps" }
    },
    key: {
      checked: 'checked'
    },
    callback: {
      onClick: this.onClickTreeNode
    }
  };

  zNodes: any;
  nodeData: any;
  treeObj: any;
  checkAllTreeToggleFlag = true;
  expandAllTreeToggleFlag = true;

  clickTreePId
  subjectList = []
  ptreeNode
  clickedTreeNode

  QUERY_URL= "pl/plSubject/page.htm";
  DELETE_URL= "pl/plSubject/delete.htm";
  GET_URL= "pl/plSubject/get.htm";
  ADD_URL= "pl/plSubject/add.htm";
  EDIT_URL= "pl/plSubject/edit.htm";

  constructor(
    public bsModalService: BsModalService,
    fb: FormBuilder
  ) { 
    super();
    this.formModel = fb.group({
      'id': [null],
      'pid': [null],
      'subject_code': [null, Validators.compose([Validators.required, CustomValidators.rangeLength([1, 6]), Validators.pattern("^[a-zA-Z0-9]+$")])],
      'subject_name': [null, Validators.compose([Validators.required, CustomValidators.rangeLength([1, 30])])],
      'remark': [null, CustomValidators.rangeLength([0, 200])],
    });
  }
   
  ngOnInit() {
    this.initQuery(0);
  }

  initQuery(pid: any){
    FrameRequest.requestArray('pl/plSubject/all.htm', {}, (array) => {
      this.nodeData = array;
      this.zNodes = $.fn.zTree.init($('#tree'), this.setting, this.nodeData);
      this.treeObj = $.fn.zTree.getZTreeObj("tree");
      window['pl_subject_this'] = this;
      //默认展开
      this.treeObj.expandAll(true)
      let rootNode = this.treeObj.getNodeByParam("id",pid );
      this.clickedTreeNode = rootNode;
      this.ptreeNode = rootNode;
      this.treeObj.selectNode(rootNode,true);//将指定ID的节点选中
    });
  }

  ngOnDestory(){
    delete window['pl_subject_this'];
  }

  searchParam(param){
    let paramTemp = {};
    if(!this.clickedTreeNode){
      paramTemp['pid'] = 0;
    }else{
      this.ptreeNode = this.clickedTreeNode;
      if(this.clickedTreeNode.isParent){
        delete param['id']
        paramTemp['pid'] = this.clickedTreeNode.id;
      }else{
        delete param['pid']
        paramTemp['id'] = this.clickedTreeNode.id;
      }
    }

    // if(_.isNumber(this.clickTreePId))
    _.assignIn(param,paramTemp);
  }

  //参数处理
  async preGoEditEvent(item){
    if(!this.clickedTreeNode){
      AppComponent.alert({text:"请选择父科目!"})
      return false;
    }
    let _item = item ? item : this.item = {remark:''};
    if(!_item['pid']) 
      _item['pid'] = this.clickedTreeNode.id;
    if(!_item['id']) 
     _item['id'] = "";
    return true;
  }

  async aftSaveEvent(){
    this.initQuery(this.item.pid);
  }

  async delete(item?){
    this.item = 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)
      
      FrameRequest.requestMap(this.DELETE_URL, {ids:checkedArray.join()}, () => {
        AppComponent.GobalComponent.successMsg('数据删除成功');
        this.aftDeleteEvent();
        this.framePager.reload();
      });
    })


  }


  async aftDeleteEvent(){
    this.initQuery(this.item.pid);
  }

  //ZTREE 事件
  onClickTreeNode(event, treeId, treeNode){
    let _pthis = window['pl_subject_this'];
    _pthis.clickedTreeNode = treeNode;
    _pthis.framePager.reload();
  }

  //全选切换
  public checkAllTreeToggle(){
    this.treeObj.checkAllNodes(this.checkAllTreeToggleFlag = !this.checkAllTreeToggleFlag);
  }

  //展开切换
  public expandAllTreeToggle(){
    this.treeObj.expandAll(this.expandAllTreeToggleFlag = !this.expandAllTreeToggleFlag);
  }


}
