import { Component, OnInit, TemplateRef, ViewChild, ElementRef } from '@angular/core';
import { FlexTableComponent } from '../../../shared/common/FlexTable.component';
import * as _ from 'lodash';
import { BsModalService } from 'ngx-bootstrap/modal';
import { FormBuilder, Validators, FormGroup, FormControl } from '@angular/forms';
import { FrameRequest } from '../../../shared/frame/frame-request';
import { AppComponent } from '../../..';
import { CustomValidators } from 'ng2-validation';
import { FrameFunction } from '../../../shared/frame/frame_function';

declare var $: any;

@Component({
  selector: 'app-optrtree',
  templateUrl: './optrtree.component.html',
  styleUrls: ['./optrtree.component.scss']
})
export class OptrtreeComponent 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 = "frame/optr/pageGx.htm";
  DELETE_URL = "frame/optr/delete.htm";
  GET_URL = "frame/optr/findGx.htm";
  ADD_URL = "frame/optr/add.htm";
  EDIT_URL = "frame/optr/editGx.htm";
  CITY_URL = "cf/cfCity/list.htm";
  RESET_URL = "frame/optr/reset.htm";//重置密码
  ENABLE_URL = "frame/optr/enable.htm"; //启用\禁用
  FRAME_ALL_URL = 'frame/optr/allOptr.htm';

  optr: any;
  roleArray = [];
  deptArray = [];
  orgArray = [];
  viewStep: boolean = false;

  constructor(
    public bsModalService: BsModalService,
    fb: FormBuilder) {
    super();
    this.optr = {};
    const password = new FormControl('', Validators.compose([Validators.required, CustomValidators.rangeLength([6, 24]), Validators.pattern("^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$)^.{6,}$")]));
    const certainPassword = new FormControl('', CustomValidators.equalTo(password));

    this.formModel = fb.group({
      'passwordGroup': fb.group({
        'login_name': [null, Validators.compose([Validators.required, CustomValidators.rangeLength([2, 16])])],
        'login_pass': password,
        'confirmPassword': certainPassword
      }),
      'org_type': [],
      'optr_id': [],
      'optr_name': [null, Validators.compose([Validators.required, CustomValidators.rangeLength([2, 32])])],
      'optr_alias': [],
      'optr_sex': [null, null],
      'optr_status': [null, Validators.required],
      'optr_role': [],
      'optr_email': [null, Validators.email],
      'optr_mobile': [null, null],
      'optr_tel': [],
      'optr_addr': [],
      'optr_fax': [],
      'optr_post': [],
      'optr_dept': [null, Validators.required],
      'optr_desc': [],
      'dept_type': [],
      'dlzh': []
      
    });
  }

  ngOnInit() {
    this.initQuery(-1);
  }

  initQuery(org_type? :any) {
    FrameRequest.requestArray(this.FRAME_ALL_URL, {}, (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", org_type);
      this.clickedTreeNode = rootNode;
      this.ptreeNode = rootNode;
      this.treeObj.selectNode(rootNode, true);//将指定ID的节点选中
    });
    FrameRequest.requestMap('frame/optr/edit/initGx.htm', {}, (map) => {
      this.roleArray = map['RoleArray'];
      this.deptArray = map['DeptArray']
    });
  }

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

  searchParam(param) {
    let paramTemp = {};
    if (!this.clickedTreeNode) {
      paramTemp['org_type'] = -1;
    } else {
      this.ptreeNode = this.clickedTreeNode;
      // if(this.clickedTreeNode.isParent){
      delete param['id']
      paramTemp['org_type'] = this.clickedTreeNode.id;
      if (!this.item) {
        this.item = {};
      }
      this.item.org_type = this.clickedTreeNode.id;
      // }else{
      //   delete param['org_type']
      //   paramTemp['id'] = this.clickedTreeNode.id;
      // }
    }

    _.assignIn(param, paramTemp);
  }

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

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

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

  //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);
  }


  // editShowType : modal模态弹出框 only只显示编辑界面 show 同时显示
  async goEdit(template: TemplateRef<any>, editShowType: string, modalcss: string, item?) {
    FrameFunction.UntouchedForm(this.formModel);
    //新增
    if(!item || item.optr_id === undefined) {
        if(!this.preGoEditEvents()) return ;
        this.viewStep = false;
        if(!this.item) {
          this.item = { 'optr_status': 'Active' };
        } else if(this.item.org_type !== undefined && this.item.org_type !== '') {
          this.item.dept_type = this.item.org_type;
          this.findDept(this.item.dept_type);
        }
        this.formModel.reset();
        this.showEdit(template, editShowType, modalcss);
        this.aftGoEditEvent();
      } else {
        this.viewStep = true;
        FrameRequest.requestEntity(this.GET_URL,{optr_id: item.optr_id}, async (entity) => {
          if(! await this.preGoEditEvents(entity)) return ;
          setTimeout(async ()=>{
            this.item = entity;
            this.item.org_type = entity.dept_type;
            this.item.confirmPassword = this.item.login_pass = 'a123456';
            this.findDept(this.item.dept_type);
            this.showEdit(template, editShowType, modalcss);
          },100);
        });
      }
  }

  //通过类别查找部门
  findDept(org_type: any) {
    FrameRequest.requestArray('cf/cfOrganization/list.htm', { org_type: org_type }, (array) => {
      this.orgArray = array;
    });
  }

  async save() {
    if(!this.item.optr_id){
      var regex = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{10,30}');
      if (!regex.test(this.item.login_pass)) {
        AppComponent.alert({ 'title': '提示', 'text': '密码中必须包含字母、数字、特殊字符至少10个字符!' });
        return;
      }
    }
   

    if (!FrameFunction.validForm(this.formModel)) {
      return;
    }
    let url = this.item.optr_id ? this.EDIT_URL: this.ADD_URL;
    if(!await this.preSaveEvent()) return;
    if(_.isUndefined(this.item.optr_id)) delete this.item.optr_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();
    });
  }

  //删除用户
  deleteOptr(optr?: any) {
    if(optr.optr_status === 'Active') {
      AppComponent.alert({title: '提示', text: '启用的用户不能删除！'});
      return ;
    }
    AppComponent.confirm("确定删除吗，删除后不可恢复！",()=>{
      if(optr.optr_id) {
        FrameRequest.request(this.DELETE_URL, {optr_id: optr.optr_id}, () => {
          AppComponent.GobalComponent.successMsg('删除成功'); 
          this.framePager.reload();
          this.initQuery(this.item.org_type); //重新加载导航树
        });
      }
    });
    
  }
  //重置密码
  resetPassword(optr? : any) {
    AppComponent.confirm("确定重置密码吗，重置后不可恢复！",()=>{
      if(optr.optr_id) {
        FrameRequest.request(this.RESET_URL, {optr_id: optr.optr_id}, () => {
          AppComponent.GobalComponent.successMsg('密码重置成功'); 
        });
      }
    });
  }

  //启用和禁用
  enable(optr : any, flag: string) {
    let title =  flag === 'Active' ? '确定启用用户吗？' : '确定禁用用户吗？';
    let text =  flag === 'Active' ? '启用' : '禁用';
    AppComponent.confirm(title ,()=>{
      if(optr.optr_id) {
        FrameRequest.request(this.ENABLE_URL, {optr_id: optr.optr_id, optr_status: flag}, () => {
          AppComponent.GobalComponent.successMsg(text+'成功'); 
          this.framePager.reload();
        });
      }
    });
  }

}
