import {Component, OnInit, ViewChild} from '@angular/core';
import {FrameDetailComponent} from "../../core/detail/frame.detail";
import {ITreeOptions, TreeComponent} from "@circlon/angular-tree-component";
import {AjaxService} from "../../../../core/service/ajax.service";
import {BsModalRef} from "ngx-bootstrap/modal";
import {MsgService} from "../../../../core/service/msg.service";

@Component({
  selector: 'app-frame-role-res',
  templateUrl: './frame-role-res.component.html',
  styleUrls: ['./frame-role-res.component.scss']
})
export class FrameRoleResComponent extends FrameDetailComponent implements OnInit {
  @ViewChild('tree', {static: false}) tree: TreeComponent;

  nodes: any;
  rootRes: any;

  customTemplateStringOptions: ITreeOptions = {
    displayField: 'res_name',
    useCheckbox: true,
    isExpandedField: 'expanded',
    idField: 'res_id',
    // hasChildrenField: 'childArray',
    // nodeHeight: 23,
    allowDragoverStyling: true,
    levelPadding: 20,
    // useVirtualScroll: true,
    animateExpand: true,
    scrollOnActivate: true,
    animateSpeed: 30,
    animateAcceleration: 1.2
    // scrollContainer: document.documentElement // HTML
  };

  constructor(bsModalRef: BsModalRef) {
    super(bsModalRef);
  }

  ngOnInit() {
    const res = {'res_id': 0, 'res_name': '顶级资源', 'res_level': 0};
    this.findChildRes(this.ResponseArray, res);
    this.rootRes = res;
    this.nodes = [res];
    setTimeout(() => {
      this.tree.treeModel.doForAll((node) => {
        if (node.data.role_id) {
          node.setIsSelected(true);
        } else {
          node.setIsSelected(false);
        }
      });
    }, 1);
  }

  findChildRes(resArray, res) {
    const array = [];
    for (const v of resArray) {

      v.checked = true;
      if (v['res_id'] !== res['res_id'] && v['res_pid'] === res['res_id']) {
        this.findChildRes(resArray, v);
        array.push(v);
        res.children = array;
      }
    }
    if (res.children === undefined || res.children.length === 0) {
      res.hasChildren = false;
      res.expanded = false;
    } else {
      res.hasChildren = true;
      res.expanded = true;
    }
  }

  saveRes() {
    const array = [];
    const values = this.tree.treeModel.selectedLeafNodeIds;
    for (const s in values) {
      if (values[s]) {
        array.push(s);
      }
    }

    let msg = `没有为角色【${this.ResponseEntity.role_name}】赋予任何权限，确定将所有权限从该角色中移除吗？`;
    if (array.length > 0) {
      msg = `确定为角色【${this.ResponseEntity.role_name}】赋予【${array.length}】条权限吗？`;
    }
    MsgService.confirmAlert(msg, () => {
      AjaxService.request('frame/role/res/grant.htm', {role_id: this.ResponseEntity.role_id, res_ids: array}, () => {
        MsgService.successToastr(`为角色【${this.ResponseEntity.role_name}】赋权完成，需重新登录生效！`);
        this.closeWindow();
      }, {RequestWithLoading: true});
    });


  }

}
