import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {FrameRequest} from '../../../shared/frame/frame-request';
import {AppComponent} from '../../../app.component';
import {FramePagerComponent} from '../../../core/pager/pager.component';
import 'ztree';
declare var $: any;

@Component({
  selector: 'app-role',
  templateUrl: './role.component.html',
  styleUrls: ['./role.component.scss']
})
export class RoleComponent implements OnInit {

  viewStep: any;
  role: any;
  valForm: FormGroup;
  @ViewChild('frameRole')
  frameRole: FramePagerComponent;
  @ViewChild('elRoleName')
  elRoleName: ElementRef;

  setting = {
    data: {
      simpleData: {
        enable: true,
        idKey: 'id',
        pIdKey: 'pid',
        rootPid: 0
      }
    },
    check: {
      enable: true,
      chkStyle: "checkbox",
      chkboxType : { "Y" : "ps", "N" : "ps" }
    },
    key: {
      checked: 'checked'
    }
  };

  zNodes: any;
  nodeData: any;

  constructor(fb: FormBuilder) {
    this.viewStep = 'page';
    this.role = {};
    this.valForm = fb.group({
      'role_name': [null, Validators.required],
      'role_type': [null, Validators.required],
      'role_status': [null, Validators.required],
      'role_desc': [null, null]
    });
  }



  ngOnInit() {
  }

  goViewStep(role, step) {
    this.role = role;
    this.viewStep = step;
    setTimeout(() => {this.elRoleName.nativeElement.focus(); }, 100);
  }

  goResStep(role) {
    this.role = role;
    FrameRequest.requestArray('frame/role/res.htm', {role_id: this.role.role_id}, (array) => {
      this.nodeData = array;
      this.zNodes = $.fn.zTree.init($('#tree'), this.setting, this.nodeData);
      this.viewStep = 'res';
    });
  }

  submitForm(value: any) {
    for (let c in this.valForm.controls) {
      this.valForm.controls[c].markAsTouched();
    }
    if (!this.valForm.valid) {
      return;
    }

    FrameRequest.requestEntity('frame/role/' + this.viewStep + '.htm', this.role, () => {
      AppComponent.GobalComponent.successMsg('角色保存成功！');
      this.role = {};
      this.frameRole.reload();
      this.viewStep = 'page';
    });

  }

  // 保存权限分配
  saveRes() {
    let ids = [];
    for (const res of $.fn.zTree.getZTreeObj('tree').getCheckedNodes(true)) {
      if (res.id > 0  && res.checked === true) {
        ids.push(res.id);
      }
    }
    AppComponent.confirm('确定要进行权限分配吗？', () => {
      FrameRequest.requestEntity('frame/role/grant.htm', {
        role_id: this.role.role_id,
        res_ids : ids
      }, () => {
        AppComponent.GobalComponent.successMsg('为角色【' + this.role.role_name + '】成功分配权限！');
        this.role = {};
        this.frameRole.reload();
        this.viewStep = 'page';
      });
    });

  }
}


