import { Component, OnInit, ViewChild } from "@angular/core";
import { NzFormatEmitEvent } from "ng-zorro-antd/core";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import { NzTreeComponent } from "ng-zorro-antd/tree";
import { NzMessageService } from "ng-zorro-antd/message";
import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";

@Component({
  selector: "app-jurisdiction-management",
  templateUrl: "./jurisdiction-management.component.html",
  styleUrls: ["./jurisdiction-management.component.less"],
})
export class JurisdictionManagementComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;
  constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private msg: NzMessageService,
    private tool: ToolService
  ) {}
  @ViewChild("nzTreeComponent", { static: false })
  nzTreeComponent: NzTreeComponent;
  ngOnInit() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.getRoleList();
    this.getHosList();
    this.getAllMenu("all");
  }
  hosId;
  isAllDisplayDataChecked = false;
  isIndeterminate = false;
  listOfDisplayData: any[] = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  checkedRole: any = {}; //选中角色
  roleList: any = []; //角色信息
  menuList: any[] = []; //功能权限列表
  hospitalList: any[] = []; //院区列表

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //是否展示提示框

  btnLoading: boolean = false; //确认按钮loading状态
  saveLoading: boolean = false; //确认按钮loading状态

  // 初始化增删改按钮
  coopBtns: any = {};

  // 角色列表
  loading1 = false;
  getRoleList() {
    let postData = {
      idx: 0,
      sum: 1000,
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("user/data", "role", postData)
      .subscribe((data) => {
        this.loading1 = false;
        this.roleList = data.list;
      });
  }
  // 所有院区列表
  loading3 = false;
  hosList = [];
  getHosList() {
    let postData = {
      idx: 0,
      sum: 100,
    };
    this.loading3 = true;
    this.mainService
      .getFetchDataList("data", "hospital", postData)
      .subscribe((data) => {
        this.loading3 = false;
        if (data.status == 200) {
          this.hosList = data.list;
          this.getAllInfo();
        }
      });
  }

  // 获取所有功能权限
  loading2 = false;
  getAllMenu(type) {
    let that = this;
    this.loading2 = true;
    that.mainService.getPermission(type).subscribe((data) => {
      this.loading2 = false;
      that.menuList = data.data;
      if (!that.menuList.length) {
        that.menuList = [];
        return;
      }
      that.showList(that.menuList);
      if (type != "all") {
        that.menuList = [that.transform(that.menuList)];
      }
      that.menuList.forEach((e) => {
        e["expanded"] = true;
      });

      // 是否有编辑权限
      function getResult(nodes) {
        if (!nodes || nodes.length == 0) {
          return;
        }

        nodes.forEach((e) => {
          e.disabled = !that.coopBtns.edit;
          getResult(e["children"]);
        });
      }
      getResult(that.menuList);

      console.log(that.menuList);
    });
  }

  // 获取所有信息权限

  allHospital: Array<object>; //所属院区
  getAllInfo() {
    this.hospitalList = this.allHospital = this.hosList;
    this.hospitalList.forEach((e) => {
      this.checkedHospitals.push({
        label: e["hosName"],
        value: e["id"],
        checked: false,
      });
    });
    this.getAllTypeAndGroup();
  }

  //取出所有菜单ID
  allMenuLength = 0;
  showList(nodes) {
    let that = this;
    if (!nodes || nodes.length == 0) {
      return;
    }
    nodes.forEach((e) => {
      that.allMenuLength++;
      that.showList(e["children"]);
    });
    return that.allMenuLength;
  }

  // 比对两数组不同项
  diff(arr1, arr2) {
    var newArr = [];
    var _arr1 = [];
    var _arr2 = [];
    //获取第一个数组的差异元素 存放到_arr1数组中
    _arr1 = arr1.filter(function (v) {
      if (arr2.indexOf(v) == -1) {
        return v;
      }
    });
    //获取第二个数组的差异元素 存放到_arr2数组中
    _arr2 = arr2.filter(function (v) {
      if (arr1.indexOf(v) == -1) {
        return v;
      }
    });
    //合并两个包含差异元素的数组
    newArr = _arr1.concat(_arr2);
    return newArr;
  }

  // 选中角色
  menuChecked: any = {};
  defaultCheckedMenus = []; //当前角色功能权限
  infos: any[] = []; //当前角色信息权限
  checkRole(data) {
    console.log(data);
    let that = this;
    that.checkedMenusId = [];
    that.menuChecked = {};
    that.menuAllChecked = false;
    that.checkedRole = data;
    //功能权限回显
    let menus = [];
    if (data.menu.length) {
      data.menu.forEach((e) => {
        menus.push(e.id + "");
        that.menuChecked[e.id] = true;
      });
      // // 所有菜单
      // let allMenuObj = that.showList(that.menuList).arr;
      // that.allMenuLength=allMenuObj.length
      if (that.allMenuLength == menus.length) {
        that.menuAllChecked = true;
      }
    } else {
      menus = [];
    }

    // return;
    that.defaultCheckedMenus = menus;

    that.allChecked = false;
    that.groupAllChecked = {};
    that.typeAllChecked = {};
    that.typeChecked = that.checked_type = {};
    that.groupChecked = that.checked_group = {};
    that.checkAllHospitalType = that.checkAllHospitalGroup = false;

    //信息权限回显
    if (!data.infoPermission || !data.infoPermission.hospitals) {
      that.allChecked = false;
      that.checkedHospitals.forEach((el, i) => {
        that.checkedHospitals[i].checked = false;
      });
      that.groupAllChecked = {};
      that.typeAllChecked = {};
      that.typeChecked = that.checked_type = {};
      that.groupChecked = that.checked_group = {};
      that.checkAllHospitalType = that.checkAllHospitalGroup = false;
      that.updateAllChecked();
      return;
    }
    that.checkedHospitals.forEach((el, i) => {
      that.checkedHospitals[i].checked = false;
    });
    let arr = this.hosList.map((item) => {
      return {
        checked: false,
        label: item.hosName,
        value: item.id,
      };
    });
    data.infoPermission.hospitals.forEach((e) => {
      that.checkedHospitals.forEach((el, i) => {
        if (e.id == el.value) {
          arr[i].checked = true;
        }
      });
    });
    that.checkedHospitals = arr;
    that.updateSingleChecked();

    var groups = [],
      types = [];
    // 任务类型
    if (data.infoPermission.taskTypes && data.infoPermission.taskTypes.length) {
      data.infoPermission.taskTypes.forEach((e) => {
        that.typeChecked["" + e.id] = that.checked_type["" + e.id] = true;
      });
      // console.log(that.allHospitalTypesAndGroups)
      that.allHospitalTypesAndGroups.forEach((e, i) => {
        var b = [];
        if (
          data.infoPermission.taskTypes &&
          data.infoPermission.taskTypes.length
        ) {
          e.taskTypes.forEach((t, idxt) => {
            b.push("" + t.id);
          });
          types[i] = b;
        }
      });
      console.log(groups, types);
      that.getTypeAndGroup(function () {
        that.allHospitalTypesAndGroups.forEach((e, i) => {
          if (
            data.infoPermission.taskTypes &&
            data.infoPermission.taskTypes.length
          ) {
            that.logTypeItem(types[i], e.id);
          }
          // if (data.infoPermission.groups && data.infoPermission.groups.length) {
          //   that.logGroupItem(groups[i], e.id)
          // }
        });
        // console.log(that.typeAllChecked, that.groupAllChecked)
      });
    } else {
      that.typeAllChecked = {};
      that.typeChecked = that.checked_type = {};
      that.checkAllHospitalType = false;
      // that.updateAllChecked();
    }
    // 工作组
    if (data.infoPermission.groups && data.infoPermission.groups.length) {
      data.infoPermission.groups.forEach((e) => {
        that.groupChecked["" + e.id] = that.checked_group["" + e.id] = true;
      });
      console.log(that.allHospitalTypesAndGroups);
      that.allHospitalTypesAndGroups.forEach((e, i) => {
        var a = [];
        if (data.infoPermission.groups && data.infoPermission.groups.length) {
          e.groups.forEach((el, idx) => {
            a.push("" + el.id);
          });
          groups[i] = a;
        }
      });
      // console.log(groups, types)
      that.getTypeAndGroup(function () {
        that.allHospitalTypesAndGroups.forEach((e, i) => {
          if (data.infoPermission.groups && data.infoPermission.groups.length) {
            that.logGroupItem(groups[i], e.id);
          }
        });
        // console.log(that.typeAllChecked, that.groupAllChecked)
      });
    } else {
      that.groupAllChecked = {};
      that.groupChecked = that.checked_group = {};
      that.checkAllHospitalGroup = false;
      // that.updateAllChecked();
    }

    // console.log(that.allHospitalTypesAndGroups)
    // that.allHospitalTypesAndGroups.forEach((e, i) => {
    //   var a = [], b = [];
    //   if (data.infoPermission.taskTypes && data.infoPermission.taskTypes.length) {
    //     e.taskTypes.forEach((t, idxt) => {
    //       b.push('' + t.id)
    //     });
    //     types[i] = b
    //   }
    //   if (data.infoPermission.groups && data.infoPermission.groups.length) {
    //     e.groups.forEach((el, idx) => {
    //       a.push('' + el.id)
    //     });
    //     groups[i] = a
    //   }
    // })
    // console.log(groups, types)
    // that.getTypeAndGroup(function () {
    //   that.allHospitalTypesAndGroups.forEach((e, i) => {
    //     if (data.infoPermission.taskTypes && data.infoPermission.taskTypes.length) {
    //       that.logTypeItem(types[i], e.id)
    //     }
    //     if (data.infoPermission.groups && data.infoPermission.groups.length) {
    //       that.logGroupItem(groups[i], e.id)
    //     }
    //   })
    //   console.log(that.typeAllChecked, that.groupAllChecked)
    // })
  }

  // 点击功能权限树上的多选框
  changeMenus: any[] = []; //修改功能权限
  nzEvent(event: NzFormatEmitEvent): void {
    if (!this.checkedRole["id"]) {
      this.defaultCheckedMenus = [];
      this.msg.create("warning", "请选择需要操作的角色类型！");
      return;
    }
    let thisNode = this.nzTreeComponent.getCheckedNodeList();
    this.changeMenus = this.findChecked(thisNode);
    let thisHalfNode = this.nzTreeComponent.getHalfCheckedNodeList();
    // console.log(this.nzTreeComponent.getHalfCheckedNodeList())
    // thisHalfNode.forEach(e => {
    //   this.changeMenus.push(e['key']);
    // })
    console.log(this.changeMenus);
  }

  menuAllChecked: boolean = false; //全选/反选功能权限
  change: boolean = false; //是否修改功能权限
  // 全选/反选
  checkedAllMenu() {
    this.change = true;
    if (!this.checkedRole["id"]) {
      this.defaultCheckedMenus = [];
      this.msg.create("warning", "请选择需要操作的角色类型！");
      return;
    }
    this.menuList.forEach((e) => {
      this.menuChecked[e.id] = this.menuAllChecked;
      this.updateCheckedMenu1(false, e);
    });
  }
  trackByMenu(index, item) {
    return item.id;
  }
  // 点击功能权限树上的多选框
  checkedMenusId = []; //已选中功能权限id
  updateCheckedMenu1(judge, node, pid?, gpid?) {
    //judge:是否是单选（点击全选/反选的时候为false），node:当前操作节点，pid：父节点，gpid：爷爷节点
    this.change = true;
    if (!this.checkedRole["id"]) {
      this.defaultCheckedMenus = [];
      this.msg.create("warning", "请选择需要操作的角色类型！");
      return;
    }
    if (this.menuChecked[node.id] && pid) {
      // 如果有父id，父级为选中状态
      this.menuChecked[pid] = true;
    }
    if (this.menuChecked[node.id] && gpid) {
      // 如果有爷爷id，爷爷id为选中状态
      this.menuChecked[gpid] = true;
    }
    if (node.children && node.children.length) {
      node.children.forEach((e) => {
        this.menuChecked[e.id] = this.menuChecked[node.id];
        this.updateCheckedMenu1(judge, e);
      });
    }
    // 已选中菜单id集合
    let menus = [];
    for (let k in this.menuChecked) {
      if (this.menuChecked[k]) {
        menus.push({ id: k });
      }
    }
    this.checkedMenusId = menus;
    // 判断全选反选应展示的状态
    if (judge) {
      this.menuAllChecked = this.allMenuLength == menus.length;
    }
  }

  // 切换菜单 （1:功能权限，2:信息权限）
  menuType: number = 1;
  checkMenu(type) {
    this.menuType = type;
  }

  // 保存功能权限
  saveMenus() {
    if (!this.checkedRole["id"]) {
      this.defaultCheckedMenus = [];
      this.msg.create("warning", "请选择需要操作的角色类型！");
      return;
    }
    let that = this;
    that.saveLoading = true;

    let data = {
      role: {
        id: that.checkedRole["id"],
        menu: that.checkedMenusId,
        role: that.checkedRole["role"],
        hosId: this.tool.getCurrentHospital().id,
      },
    };
    if (!that.change) {
      that.defaultCheckedMenus.forEach((e) => {
        data.role.menu.push({ id: e });
      });
    }
    console.log(data);
    // console.log(that.defaultCheckedMenus)
    // return;
    that.mainService.coopUserData("addData", "role", data).subscribe((data) => {
      console.log(data);
      that.saveLoading = false;
      if (data.status == 200) {
        that.showPromptModal("设置", true, "");
      } else {
        that.showPromptModal("设置", false, data.msg);
      }
    });
  }

  // 院区全选
  allChecked = false;
  // indeterminate = false;//checkBox不全选状态
  checkedHospitals: any[] = []; //所有院区
  updateAllChecked(e?): void {
    // this.indeterminate = false;
    if (!this.checkedRole["id"]) {
      this.defaultCheckedMenus = [];
      this.msg.create("warning", "请选择需要操作的角色类型！");
      return;
    }
    if (this.allChecked) {
      this.checkedHospitals = this.checkedHospitals.map((item) => {
        return {
          ...item,
          checked: true,
        };
      });
    } else if (!this.allChecked && e) {
      this.checkedHospitals = this.checkedHospitals.map((item) => {
        return {
          ...item,
          checked: false,
        };
      });
    }

    console.log(this.checkedHospitals);
    this.getTypeAndGroup();
  }
  // 院区单选
  updateSingleChecked(): void {
    if (!this.checkedRole["id"]) {
      this.defaultCheckedMenus = [];
      this.msg.create("warning", "请选择需要操作的角色类型！");
      return;
    }
    if (this.checkedHospitals.every((item) => item.checked === false)) {
      this.allChecked = false;
      // this.indeterminate = false;
    } else if (this.checkedHospitals.every((item) => item.checked === true)) {
      this.allChecked = true;
      // this.indeterminate = false;
    } else {
      this.allChecked = false;
      // this.indeterminate = true;
    }
    console.log(this.checkedHospitals);
    this.getTypeAndGroup();
  }

  // 获取已选院区的任务类型和工作组
  typeGroupList: any[] = []; //已选院区任务类型&工作组
  allHospitalTypesAndGroups: any[] = []; //所有院区的工作组和任务类型
  getTypeAndGroup(func?) {
    if (func) {
      func();
      return;
    }
    console.log(this.checkedHospitals);
    let that = this;
    var arr = [];
    that.checkedHospitals.forEach((e) => {
      if (e["checked"]) {
        arr.push(e["value"]);
      }
    });
    this.loading2 = true;
    that.mainService.coopConfig("getTypeAndGroup", arr).subscribe((data) => {
      this.loading2 = false;
      that.typeGroupList = data.hospital;
      console.log(that.typeGroupList);
      // if (func) {
      //   func()
      // }
    });
  }

  // 获取所有院区类型和组信息
  getAllTypeAndGroup() {
    let that = this;
    // 获取所有院区的数据
    var arr = [];
    arr = [];
    that.checkedHospitals.forEach((e) => {
      arr.push(e["value"]);
    });
    that.mainService.coopConfig("getTypeAndGroup", arr).subscribe((data) => {
      that.allHospitalTypesAndGroups = data.hospital;
      console.log(that.allHospitalTypesAndGroups);
    });
  }

  //任务类型
  typeAllChecked = {}; //任务类型各院区全选
  typeChecked = {}; //任务类型单选时各个checkBox值
  checked_type = {}; //全选的时候存储所有院区所有任务类型的checkBox值
  thisGroup_type = []; //点击当前按钮所处院区的组信息
  //单选
  logTypeItem(value: string[], id): void {
    if (!this.checkedRole["id"]) {
      this.defaultCheckedMenus = [];
      this.msg.create("warning", "请选择需要操作的角色类型！");
      return;
    }
    console.log(value, id);
    let that = this;
    //更新当前操作院区数据
    for (var i = 0; i < that.typeGroupList.length; i++) {
      if (that.typeGroupList[i]["id"] == id) {
        that.thisGroup_type = that.typeGroupList[i]["taskTypes"];
      }
    }
    if (value.length != that.thisGroup_type.length) {
      that.typeAllChecked["" + id] = false;
    } else {
      that.typeAllChecked["" + id] = true;
    }
    //同步当前院区的checkBox状态到总任务类型checkBox中
    for (var k in this.typeChecked) {
      this.checked_type[k] = this.typeChecked[k];
    }

    console.log(that.typeAllChecked);
    //判断任务类型中已选院区的选中数量和总院区数量是否相同，若相同，则说明任务类型已全选中checkAllHospitalType=true，反之
    var typeCheckLength = 0;
    for (var m in that.typeAllChecked) {
      if (that.typeAllChecked[m]) {
        typeCheckLength++;
      }
    }
    if (typeCheckLength == that.hospitalList.length) {
      that.checkAllHospitalType = true;
    } else {
      that.checkAllHospitalType = false;
    }
    console.log(typeCheckLength);
  }
  //任务类型院区全选
  updTypeAllChecked(id, allUnCheck?): void {
    if (!this.checkedRole["id"]) {
      this.defaultCheckedMenus = [];
      this.msg.create("warning", "请选择需要操作的角色类型！");
      return;
    }
    let that = this;
    //更新当前操作院区数据
    for (var i = 0; i < that.typeGroupList.length; i++) {
      if (that.typeGroupList[i]["id"] == id) {
        that.thisGroup_type = that.typeGroupList[i]["taskTypes"];
      }
    }

    let changeBox = []; //当前分组所有item
    that.thisGroup_type.forEach((e) => {
      changeBox.push("" + e.id);
    });
    if (that.typeAllChecked["" + id]) {
      changeBox.map((e, item) => {
        that.checked_type[e] = true;
      });
    } else {
      changeBox.map((e, item) => {
        that.checked_type[e] = false;
      });
    }
    if (allUnCheck == "allUnCheck") {
      changeBox.map((e, item) => {
        that.checked_type[e] = false;
      });
    }
    that.typeChecked = that.checked_type;

    console.log(that.typeAllChecked);
    //判断任务类型中已选院区的选中数量和总院区数量是否相同，若相同，则说明任务类型已全选中checkAllHospitalType=true，反之
    var typeCheckLength = 0;
    for (var m in that.typeAllChecked) {
      if (that.typeAllChecked[m]) {
        typeCheckLength++;
      }
    }
    if (typeCheckLength == that.hospitalList.length) {
      that.checkAllHospitalType = true;
    } else {
      that.checkAllHospitalType = false;
    }
    console.log(typeCheckLength);
  }

  //选中所有任务类型
  checkAllHospitalType: boolean = false;
  updateAllHospitalType() {
    if (!this.checkedRole["id"]) {
      this.defaultCheckedMenus = [];
      this.msg.create("warning", "请选择需要操作的角色类型！");
      return;
    }
    let that = this;
    if (that.checkAllHospitalType) {
      that.hospitalList.forEach((e) => {
        // hosId.push(e.id)
        that.typeAllChecked["" + e.id] = true;
        that.updTypeAllChecked(e.id);
      });
    } else {
      console.log("全不选");
      that.hospitalList.forEach((e) => {
        // hosId.push(e.id)
        that.typeAllChecked["" + e.id] = false;
        that.updTypeAllChecked(e.id, "allUnCheck");
      });
    }
  }

  //工作组
  groupAllChecked = {}; //工作组各院区全选
  groupChecked = {}; //工作组单选时各个checkBox值
  checked_group = {}; //全选的时候存储所有院区所有工作组的checkBox值
  thisGroup_group = []; //点击当前按钮所处院区的工作组信息
  //单选
  logGroupItem(value: string[], id): void {
    if (!this.checkedRole["id"]) {
      this.defaultCheckedMenus = [];
      this.msg.create("warning", "请选择需要操作的角色类型！");
      return;
    }
    let that = this;
    //更新当前操作的院区数据
    for (var i = 0; i < that.typeGroupList.length; i++) {
      if (that.typeGroupList[i]["id"] == id) {
        that.thisGroup_group = that.typeGroupList[i]["groups"];
      }
    }
    if (value.length != that.thisGroup_group.length) {
      that.groupAllChecked["" + id] = false;
    } else {
      that.groupAllChecked["" + id] = true;
    }
    //同步当前院区的checkBox状态到总任务类型checkBox中
    for (var k in this.groupChecked) {
      this.checked_group[k] = this.groupChecked[k];
    }

    console.log(that.groupAllChecked);
    //判断任务类型中已选院区的选中数量和总院区数量是否相同，若相同，则说明任务类型已全选中checkAllHospitalType=true，反之
    var groupCheckLength = 0;
    for (var m in that.groupAllChecked) {
      if (that.groupAllChecked[m]) {
        groupCheckLength++;
      }
    }
    if (groupCheckLength == that.hospitalList.length) {
      that.checkAllHospitalGroup = true;
    } else {
      that.checkAllHospitalGroup = false;
    }
  }
  // 工作组院区全选
  updGroupAllChecked(id, allUnCheck?): void {
    if (!this.checkedRole["id"]) {
      this.defaultCheckedMenus = [];
      this.msg.create("warning", "请选择需要操作的角色类型！");
      return;
    }
    // console.log(id);
    let that = this;
    //更新当前操作的院区数据
    for (var i = 0; i < that.typeGroupList.length; i++) {
      if (that.typeGroupList[i]["id"] == id) {
        that.thisGroup_group = that.typeGroupList[i]["groups"];
      }
    }
    let changeBox = []; //当前分组所有item
    that.thisGroup_group.forEach((e) => {
      changeBox.push("" + e.id);
    });
    if (that.groupAllChecked["" + id]) {
      changeBox.map((e, item) => {
        that.checked_group[e] = true;
      });
    } else {
      changeBox.map((e, item) => {
        that.checked_group[e] = false;
      });
    }
    if (allUnCheck == "allUnCheck") {
      changeBox.map((e, item) => {
        that.checked_group[e] = false;
      });
    }
    that.groupChecked = that.checked_group;

    //判断任务类型中已选院区的选中数量和总院区数量是否相同，若相同，则说明任务类型已全选中checkAllHospitalType=true，反之
    var groupCheckLength = 0;
    for (var m in that.groupAllChecked) {
      if (that.groupAllChecked[m]) {
        groupCheckLength++;
      }
    }
    if (groupCheckLength == that.hospitalList.length) {
      that.checkAllHospitalGroup = true;
    } else {
      that.checkAllHospitalGroup = false;
    }
  }

  //选中所有工作组
  checkAllHospitalGroup: boolean = false;
  updateAllHospitalGroup() {
    if (!this.checkedRole["id"]) {
      this.defaultCheckedMenus = [];
      this.msg.create("warning", "请选择需要操作的角色类型！");
      return;
    }
    let that = this;
    if (that.checkAllHospitalGroup) {
      //全选
      that.hospitalList.forEach((e) => {
        that.groupAllChecked["" + e.id] = true;
        that.updGroupAllChecked(e.id);
      });
    } else {
      // 全不选
      that.hospitalList.forEach((e) => {
        that.groupAllChecked["" + e.id] = false;
        that.updGroupAllChecked(e.id, "allUnCheck");
      });
    }
  }

  // 保存信息权限
  saveInfo() {
    if (!this.checkedRole["id"]) {
      this.defaultCheckedMenus = [];
      this.msg.create("warning", "请选择需要操作的角色类型！");
      return;
    }
    let that = this;
    that.saveLoading = true;

    console.log(that.allHospitalTypesAndGroups);

    //删除未选中院区的任务类型和工作组
    //1.获取所有院区的任务类型t
    //1.获取所有院区的工作组g
    let allTypes = [];
    let allGroups = [];
    that.allHospitalTypesAndGroups.forEach((e) => {
      allTypes = allTypes.concat(e.taskTypes);
      allGroups = allGroups.concat(e.groups);
    });
    console.log(allTypes, allGroups);

    //2.获取未选中院区所有的任务类型
    //2.获取未选中院区所有的工作组
    let unHos = []; //未选中院区id
    let unHosInfo = []; //未选中院区的所有信息
    that.checkedHospitals.forEach((el, i) => {
      if (!el.checked) {
        unHos.push(el.value);
        that.groupAllChecked["" + el.value] = false;
        that.typeAllChecked["" + el.value] = false;
      }
    });
    console.log(unHos);
    unHos.forEach((el) => {
      that.allHospitalTypesAndGroups.forEach((e) => {
        if (el == e.id) {
          unHosInfo.push(e);
        }
      });
    });
    console.log(unHosInfo);
    //4.已选中的所有任务类型中push未选中的任务类型（checked：false）
    unHosInfo.forEach((e) => {
      e.taskTypes.forEach((t) => {
        that.checked_type["" + t.id] = false;
        that.typeChecked["" + t.id] = false;
      });
      e.groups.forEach((g) => {
        that.checked_group["" + g.id] = false;
        that.groupChecked["" + g.id] = false;
      });
    });
    console.log(that.checkedHospitals); //操作过的院区
    console.log(that.checked_type); //操作过的任务类型
    console.log(that.checked_group); //操作过的工作组

    that.getTypeAndGroup();

    // 获取并处理所有已选中数据
    let hos = []; //院区
    let types = []; //任务类型
    let groups = []; //工作组
    that.checkedHospitals.forEach((e) => {
      if (e.checked) {
        hos.push({ id: e.value });
      }
    });
    for (var w in that.checked_type) {
      if (that.checked_type[w]) {
        types.push({ id: w });
      }
    }
    for (var e in that.checked_group) {
      if (that.checked_group[e]) {
        groups.push({ id: e });
      }
    }

    console.log(hos, types, groups);
    let postData = {
      role: {
        id: that.checkedRole["id"],
        role: that.checkedRole["role"],
        infoPermission: {
          hospitals: hos,
          taskTypes: types,
          groups: groups,
        },
        hosId: this.tool.getCurrentHospital().id,
      },
    };
    if (
      that.checkedRole["infoPermission"] &&
      that.checkedRole["infoPermission"].id
    ) {
      postData.role.infoPermission["id"] =
        that.checkedRole["infoPermission"].id;
    }
    that.mainService
      .coopUserData("addData", "role", postData)
      .subscribe((data) => {
        console.log(data);
        that.saveLoading = false;
        if (data.status == 200) {
          that.showPromptModal("保存", true, "");
          that.checkedRole = data.data;
          console.log(that.checkedRole);
        } else {
          that.showPromptModal("保存", false, data.msg);
        }
      });
  }

  // 新增/编辑模态框
  coopModal: boolean = false; //模态框是否展示
  coopType: string = ""; //新增/编辑

  showCoopModal(type) {
    this.coopType = type;
    if (type == "edit" && !this.checkedRole.id) {
      this.msg.create("warning", "请选择需要编辑的角色！");
      return;
    }
    this.coopModal = true;
    if (type == "edit") {
      this.validateForm.controls.role.setValue(this.checkedRole["role"]);
      this.validateForm.controls.remark.setValue(
        this.checkedRole["remark"] || ""
      );
    } else if (type == "add") {
      this.validateForm.controls.role.setValue(null);
      this.validateForm.controls.remark.setValue(null);
    }
  }
  // 隐藏分组信息模态框
  hideCoopModal() {
    this.coopModal = false;
  }

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      role: [null, [Validators.required]],
      remark: [null, [Validators.required]],
    });
  }

  // 新增/编辑提交
  validateForm: FormGroup;
  submitForm(): void {
    let that = this;
    that.btnLoading = true;
    for (const i in that.validateForm.controls) {
      that.validateForm.controls[i].markAsDirty();
      that.validateForm.controls[i].updateValueAndValidity();
    }
    console.log(that.validateForm);
    if (that.validateForm.invalid) return;
    let data: any = {
      role: {
        role: that.validateForm.value.role,
        remark: that.validateForm.value.remark,
        flag: 0,
        roletype: 0,
      },
    };
    if (that.coopType == "edit") {
      data.role["id"] = that.checkedRole.id;
    }
    if (that.coopType == "add") {
      data.role.hosId = this.tool.getCurrentHospital().id;
    }
    that.mainService
      .coopUserData(
        that.coopType == "add" ? "addData" : "updData",
        "role",
        data
      )
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideCoopModal();
        that.initForm();
        if (that.coopType == "edit") {
          that.checkedRole.role = data.data.role;
          that.checkedRole.remark = data.data.remark;
        }
        if (data.status == 200) {
          that.showPromptModal(
            that.coopType == "add" ? "新增" : "编辑",
            true,
            ""
          );
        } else {
          that.showPromptModal(
            that.coopType == "add" ? "新增" : "编辑",
            false,
            data.msg
          );
        }
      });
  }

  //删除modal
  delModal: boolean = false;
  showDelModal() {
    if (!this.checkedRole["id"]) {
      this.msg.create("warning", "请选择需要删除的角色！");
      return;
    }
    this.delModal = true;
  }
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    let that = this;
    that.btnLoading = true;
    that.mainService
      .coopData("rmvData", "role", [that.checkedRole["id"]])
      .subscribe((data) => {
        console.log(data);
        that.btnLoading = false;
        that.defaultCheckedMenus = [];
        that.menuChecked = {};
        that.checkedRole = {};
        that.hideDelModal();
        if (data.status == 200) {
          that.showPromptModal("删除", true, "");
        } else {
          that.showPromptModal("删除", false, data.msg);
        }
      });
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
      this.getRoleList();
    }, 100);
  }

  // 树形组建获取已选中项的key
  findChecked(nodes) {
    var res = [];
    function getResult(nodes, res) {
      if (!nodes || nodes.length == 0) {
        return;
      }
      nodes.forEach((e) => {
        if (e["isChecked"] == true) {
          res.push(e["key"]);
        }
        getResult(e["children"], res);
      });
    }
    getResult(nodes, res);
    // console.log(res)
    return res;
  }

  // 处理树数据（parent格式转为children格式）
  transform(nodes): any {
    var treeConverter = {
      result: null, //转化后的结果，是根节点，所有节点都是从根节点长出来的
      attributeName: "id", //节点唯一标识符
      needFind: true, //是否查询节点在result中已经存在，为了优化效率
      transform: function (node) {
        //转化递归函数，参数：一个待插入节点

        if (node.parent != null) {
          //该节点有父节点
          var newNode = this.transform(node.parent); //递归进入，返回值为一个节点，用作父节点，该父节点必然存在于result中，这点由下面的算法可以控制
          if (this.needFind) {
            for (var i = 0; i < newNode.children.length; i++) {
              //查找要插入的node子节点是否在newNode这个父节点中存在
              if (
                newNode.children[i][this.attributeName] ===
                node[this.attributeName]
              ) {
                return newNode.children[i]; //存在的话直接返回newNode父节点内的该子节点,该子节点必然存在于result中，作为返回值它将被用作上级递归的newNode，因此newNode必然存在于result中
              }
            }
          }
          this.needFind = false; //不存在的话，关闭之后递归的循环判断，因为待插入node节点不存在于result中，故而它的子节点一定不存在于result中，不用再循环判断
          delete node.parent; //删除该节点的parent属性，如果有的话
          node.children = []; //因为确认是要新插入的节点，没有children:[]属性，故给该节点增加children:[]属性
          node.disabled = true;
          newNode.children.push(node); //将该node节点push进newNode的子节点数组中
          return node; //return该新插入节点，作为递归返回值给上层，用作newNode父节点，node存在于result中故newNode存在于result中
        } else if (node.parent == null) {
          //该叶节点没有父节点，即为根节点
          delete node.parent; //删除该节点的parent属性，如果有的话
          if (this.result == null) {
            //根节点不存在
            node.children = []; //给该节点增加children:[]属性
            return (this.result = node); //该节点赋给result，并return根节点，作为返回值它将被用作上级递归的newNode，因此newNode必然存在于result中
          } else {
            return this.result; // 直接return根节点，作为返回值它将被用作上级递归的newNode，因此newNode必然存在于result中
          }
        }
      },
      getSingle: function (node, attributeName) {
        //传入单个叶子节点，attributeName作为节点唯一标识符属性，返回单个转化结果
        this.result = null; //重置根节点
        this.needFind = true; //重置开启节点是否已存在判断
        this.attributeName = attributeName == null ? "id" : attributeName; //唯一标识符默认为“id”
        this.transform(JSON.parse(JSON.stringify(node))); //复制出一个新的节点对象作为参数，保证不改变原有数据
        return this.result; //返回根节点
      },
      getWhole: function (nodes, attributeName?) {
        //传入整个叶子节点数组，attributeName作为节点唯一标识符属性，返回整个转化结果
        this.result = null; //重置根节点
        this.attributeName = attributeName == null ? "id" : attributeName; //唯一标识符默认为“id”
        nodes = JSON.parse(JSON.stringify(nodes)); //复制出一个新的节点对象作为参数，保证不改变原有数据
        nodes.forEach((item) => {
          //循环调用转化方法
          this.needFind = true; //重置开启节点是否已存在判断，保证不插入重复节点
          this.transform(item);
        });
        return this.result; //返回根节点
      },
    };
    var result = treeConverter.getWhole(nodes); //调用
    console.log(result);
    return result;
  }
}
