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

@Component({
  selector: "app-job-assignment",
  templateUrl: "./job-assignment.component.html",
  styleUrls: ["./job-assignment.component.less"],
})
export class JobAssignmentComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private tool: ToolService
  ) {
    this.route.queryParams.subscribe((res) => {
      this.queryParamsId = res.id;
      this.queryParamsName = res.name;
    });
  }
  @ViewChild("nzTreeComponent", { static: false })
  nzTreeComponent: NzTreeComponent;
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef3", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef3: OverlayScrollbarsComponent;

  ngOnInit() {
    this.currentHospital = this.tool.getCurrentHospital();
    this.getTypeList("first");
    this.getAlldeptType();
  }
  queryParamsId = "";
  queryParamsName = "";
  isAllDisplayDataChecked = false;
  listOfDisplayData: any[] = [];
  checkedType: any = {}; //选中任务类型
  typeList: Array<any> = []; //任务类型
  hospitalList: any[] = []; //院区列表
  currentHospital; //当前院区
  classesId; //当前班次id
  ruleTypes = {}; //各任务类型对应班次所选择的工作分配规则 key:当前任务类型id+''+当前任务类型所选班次id ；value:(1，自由抢单，2指定分组，3科室绑定人员，4科室绑定分组)
  classesGroups = {}; //各任务类型对应班次的分组 key:当前任务类型id+''+当前任务类型所选班次id
  mapOfCheckedId = {}; //各班次的分组列表中选中的分组 key:当前任务类型id+''+当前任务类型所选班次id

  allUserList: any[] = []; //所有用户
  allGroupList: any[] = []; //所有分组
  groupUserList: any[] = []; //所选组内用户
  allBuilding: Array<any>; //所有楼栋
  allDeptType: any[] = []; //所有科室类型

  multipleValue = ["a10", "c12"];

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //是否展示提示框
  replicationModalShow: boolean = false; //是否展示复制方案弹框

  saveLoading: boolean = false; //保存按钮loading状态
  takeLoading: boolean = false; //保存按钮loading状态
  allBtnLoading: boolean = false; //搜索结果批量分配按钮loading状态
  allCancelLoading: boolean = false; //搜索结果批量取消分配按钮loading状态

  clearLoading: boolean = false; //清空选项按钮loading状态
  btnLoading: boolean = false; //选中批量分配按钮loading状态
  cancelLoading: boolean = false; //选中批量取消分配按钮loading状态

  isReplace; //是否替换
  tLoading = false;

  // 复制方案弹窗
  currentTaskType = {}; //传送到弹窗的数据
  replicationSchemeClick(checkedType, item) {
    console.log(checkedType, item);
    this.currentTaskType = {
      taskTypeName: checkedType.taskName, //任务类型名称
      taskTypeId: checkedType.id, //任务类型ID
      classesName: item.name, //班次名称
      classesId: item.id, //班次id
      queryParamsId: this.queryParamsId, //分配方案id
      queryParamsName: this.queryParamsName, //分配方案名称
      bindId: this.ruleTypes[checkedType["id"] + "" + item.id], //绑定方式id
    };
    this.replicationModalShow = true;
  }
  // 关闭复制方案弹窗
  closeModelHs(e) {
    this.replicationModalShow = JSON.parse(e).show;
  }
  // 重新请求相关接口
  reloadModelHs(e) {
    console.log(e);
    if (JSON.parse(e).show) {
      this.getTypeList("current");
      console.log(this.checkedType, this.classesId);
    }
  }
  // 获取任务类型
  loading1 = false;
  getTypeList(first?) {
    let that = this;
    let data = {
      idx: 0,
      sum: 999,
      taskType: {
        schemeId: this.queryParamsId,
        hosIds: this.currentHospital.id + "",
      },
    };
    this.loading1 = true;
    that.mainService
      .getFetchDataList("configuration", "taskType", data)
      .subscribe((data) => {
        this.loading1 = false;
        that.typeList = data.list;
        if (first === "first") {
          that.checkType(that.typeList[0]);
          that.typeList.forEach((e) => {
            e["classesIds"].forEach((el) => {
              that.mapOfCheckedId[e["id"] + "" + el.id] = {};
            });
          });
        } else if (first === "current") {
          // console.log(this.checkedType.id);
          let obj = that.typeList.find(
            (item) => item["id"] == this.checkedType.id
          );
          this.checkType(obj, this.classesId, "no");
        }
      });
  }

  workAllocations = {}; //存储所有班次工作分配id
  // 切换任务类型
  checkType(data, classesId?, isGo?) {
    let that = this;
    that.initCheckedTableInfo1(isGo);
    that.initSearchCondition1();
    that.checkedType = data;
    that.classesId = classesId || that.checkedType["classesIds"][0]["id"];
    that.checkedType["classesIds"].forEach((e) => {
      if (that.checkedType["workAllocation"]) {
        that.checkedType["workAllocation"].forEach((el) => {
          if (el["classId"] == e.id) {
            that.ruleTypes[that.checkedType["id"] + "" + e.id] =
              el.ruleType + "";
            that.workAllocations[that.checkedType["id"] + "" + e.id] =
              el.id + "";
          }
        });
      }
    });
    console.log(that.ruleTypes);
    this.checkClasses(that.classesId, isGo); //默认
    that.getAllBuilding();
    if (isGo) {
      that.search1("");
      that.search2("");
    } else {
      that.search1(1);
      that.search2(1);
    }
    that.getAllUser();
  }
  // 回显当前班次指定分组表格选中情况
  checkMapOfCheckedId() {
    let that = this;
    that.checkedType["classesIds"].forEach((e) => {
      if (that.checkedType["workAllocation"]) {
        that.checkedType["workAllocation"].forEach((el) => {
          if (el["classId"] == e.id) {
            if (el.groups) {
              el.groups.forEach((ele) => {
                that.mapOfCheckedId[el.taskTypeId + "" + el.classId][
                  ele.id + ""
                ] = true;
              });
            }
          }
        });
      }
    });
  }
  //切换班次
  checkClasses(id, isGo?) {
    console.log(this.ruleTypes);
    let typeId = this.ruleTypes[this.checkedType["id"] + "" + id];
    console.log(typeId);
    if (typeId == 3 || typeId == 4) {
      this.copyFlag = true;
    } else {
      this.copyFlag = false;
    }
    let that = this;
    // 当前班次id
    that.classesId = id;
    that.initCheckedTableInfo1(isGo);
    that.initSearchCondition1();
    that.getClassesGroups();
    setTimeout(() => {
      that.checkMapOfCheckedId();
    }, 100);
    if (isGo) {
      that.search1("");
      that.search2("");
    } else {
      that.search1(1);
      that.search2(1);
    }
  }

  // 切换单选框
  currentRadio; //当前选中的
  copyFlag = false; //是否显示“复制方案”
  changeRadio(e, id?) {
    this.currentRadio = e;
    let that = this;
    console.log(e);
    that.initCheckedTableInfo1();
    that.initSearchCondition1();
    if (e == 3) {
      this.copyFlag = true;
      that.search1(1);
    } else if (e == 4) {
      this.copyFlag = true;
      that.search2(1);
    } else {
      this.copyFlag = false;
    }
  }

  // 获取当前班次的指定分组
  getClassesGroupsTimer = null;
  getClassesGroupsLoading = false;
  getClassesGroups() {
    let that = this;
    that.classesGroups[that.checkedType["id"] + "" + that.classesId] = [];
    this.getClassesGroupsLoading = true;
    let data = {
      idx: 0,
      sum: 999,
      group2: {
        scheduleClass: {
          id: that.classesId,
        },
        hospitals: that.checkedType["hosId"]["id"],
      },
    };
    clearTimeout(this.getClassesGroupsTimer);
    this.getClassesGroupsTimer = setTimeout(() => {
      that.mainService
        .getFetchDataList("data", "group2", data)
        .subscribe((data) => {
          this.getClassesGroupsLoading = false;
          that.classesGroups[that.checkedType["id"] + "" + that.classesId] =
            data.list;
        });
    }, 2000);
  }

  // 选中列表中当前分组用户
  refreshStatusGlag = false;
  refreshStatus(): void {
    // this.isAllDisplayDataChecked = this.listOfDisplayData.every(item => this.mapOfCheckedId[item.id]);
    // this.isIndeterminate =
    //   this.listOfDisplayData.some(item => this.mapOfCheckedId[item.id]) && !this.isAllDisplayDataChecked;
    let that = this;
    let i, j;
    for (j = 0; j < that.groupUserList.length; j++) {
      for (i = 0; i < that.allUserList.length; i++) {
        if (that.allUserList[i]["id"] == that.groupUserList[j]["id"]) {
          that.mapOfCheckedId[that.checkedType["id"] + "" + that.classesId][
            that.allUserList[i]["id"]
          ] = true;
          break;
        }
      }
    }

    //有没有选中的分组
    this.refreshStatusGlag = Object.values(
      that.mapOfCheckedId[that.checkedType["id"] + "" + that.classesId]
    ).some((item) => item === true);
  }

  // 保存
  save(type) {
    let that = this;

    that.btnLoading = true;
    let postData = {
      workAllocation: {},
    };

    let workAllDatas = that.checkedType["workAllocation"]
      ? that.checkedType["workAllocation"]
      : [];
    let oldRuleType;
    workAllDatas.forEach((resp) => {
      if (that.classesId == resp.classId) {
        oldRuleType = resp.ruleType;
      }
    });

    if (type == 1) {
      // 自由抢单
      postData = {
        workAllocation: {
          ruleType: 1,
          taskTypeId: that.checkedType["id"],
          classId: that.classesId,
        },
      };

      if (oldRuleType != 1) {
        if (oldRuleType == 2) {
          postData.workAllocation["groups"] = [];
        } else if (oldRuleType == 3) {
          postData.workAllocation["deptUserIds"] = [];
        } else if (oldRuleType == 4) {
          postData.workAllocation["deptGroupIds"] = [];
        }
      }
    } else if (type == 2) {
      // 指定分组
      let groupChecked =
        that.mapOfCheckedId[that.checkedType["id"] + "" + that.classesId];
      let groups = [];
      for (var k in groupChecked) {
        if (groupChecked[k]) {
          groups.push({ id: k });
        }
      }
      postData = {
        workAllocation: {
          ruleType: 2,
          taskTypeId: that.checkedType["id"],
          classId: that.classesId,
          groups: groups,
        },
      };

      if (oldRuleType != 2) {
        if (oldRuleType == 3) {
          postData.workAllocation["deptUserIds"] = [];
        } else if (oldRuleType == 4) {
          postData.workAllocation["deptGroupIds"] = [];
        }
      }
    }

    if (that.workAllocations[that.checkedType["id"] + "" + that.classesId]) {
      postData.workAllocation["id"] =
        that.workAllocations[that.checkedType["id"] + "" + that.classesId];
    }

    console.log(
      that.workAllocations[that.checkedType["id"] + "" + that.classesId]
    );
    if (that.workAllocations[that.checkedType["id"] + "" + that.classesId]) {
      postData.workAllocation["id"] =
        that.workAllocations[that.checkedType["id"] + "" + that.classesId];
    }
    // return;
    console.log(postData);
    postData.workAllocation["schemeId"] = this.queryParamsId;

    that.mainService.coopConfig("Allocate", postData).subscribe((data) => {
      that.btnLoading = false;
      if (data.status == 200) {
        that.showPromptModal("保存", true, "");
        that.checkedType = data.data;
        console.log(that.checkedType);
        that.checkType(that.checkedType, this.classesId);
      } else {
        that.showPromptModal("保存", false, data.msg);
      }
    });
  }

  // 科室绑定人员table表格选择
  pageIndex1: number = 1; //表格当前页码
  pageSize1: number = 10; //表格每页展示条数
  listLength1: number = 100; //表格总数据量
  isAllDisplayDataChecked1 = false; //当前页是否全选
  mapOfCheckedId1 = {}; //已操作过的科室id是否选中:{1:true,2:false}
  deptsByAllocation1 = []; //所有科室列表
  checkedAllDeptInfos1 = []; //已选中科室所有数据(累积多页选中的所有科室)
  checkedmultipleValue1 = []; //已选中科室展示在多选框的数据
  refreshStatus1(): void {
    let bala = [];
    this.isAllDisplayDataChecked1 = this.deptsByAllocation1.every(
      (item) => this.mapOfCheckedId1[item.id]
    );
    bala = this.deptsByAllocation1.filter(
      (item) => this.mapOfCheckedId1[item.id]
    );
    this.checkedAllDeptInfos1 = this.checkedAllDeptInfos1.concat(bala);
    this.checkedAllDeptInfos1 = Array.from(new Set(this.checkedAllDeptInfos1));
    this.checkedAllDeptInfos1 = this.checkedAllDeptInfos1.filter(
      (item) => this.mapOfCheckedId1[item.id]
    );
    let arr = [];
    for (var k in this.mapOfCheckedId1) {
      if (this.mapOfCheckedId1[k]) {
        arr.push(Number(k));
      }
    }
    this.checkedmultipleValue1 = arr;
  }

  // 科室绑定分组table表格选择
  pageIndex2: number = 1; //表格当前页码
  pageSize2: number = 10; //表格每页展示条数
  listLength2: number = 100; //表格总数据量
  isAllDisplayDataChecked2 = false; //当前页是否全选
  mapOfCheckedId2 = {}; //已操作过的科室id是否选中:{1:true,2:false}
  deptsByAllocation2 = []; //所有科室列表
  checkedAllDeptInfos2 = []; //已选中科室所有数据(累积多页选中的所有科室)
  checkedmultipleValue2 = []; //已选中科室展示在多选框的数据
  refreshStatus2(): void {
    let bala = [];
    this.isAllDisplayDataChecked2 = this.deptsByAllocation2.every(
      (item) => this.mapOfCheckedId2[item.id]
    );
    bala = this.deptsByAllocation2.filter(
      (item) => this.mapOfCheckedId2[item.id]
    );
    this.checkedAllDeptInfos2 = this.checkedAllDeptInfos2.concat(bala);
    this.checkedAllDeptInfos2 = Array.from(new Set(this.checkedAllDeptInfos2));
    this.checkedAllDeptInfos2 = this.checkedAllDeptInfos2.filter(
      (item) => this.mapOfCheckedId2[item.id]
    );
    let arr = [];
    for (var k in this.mapOfCheckedId2) {
      if (this.mapOfCheckedId2[k]) {
        arr.push(Number(k));
      }
    }
    this.checkedmultipleValue2 = arr;
  }

  // 选中所有科室-科室绑定人员
  checkAll1(value: boolean): void {
    this.deptsByAllocation1.forEach(
      (item) => (this.mapOfCheckedId1[item.id] = value)
    );
    this.refreshStatus1();
  }
  // 选中所有科室-科室-科室绑定分组
  checkAll2(value: boolean): void {
    this.deptsByAllocation2.forEach(
      (item) => (this.mapOfCheckedId2[item.id] = value)
    );
    this.refreshStatus2();
  }

  // 在多选框中change已选中的科室-科室绑定人员
  changeCheckedDept1(e) {
    let that = this;
    let arr = {};
    e.forEach((e) => {
      for (var k in that.mapOfCheckedId1) {
        if (k == e && that.mapOfCheckedId1[k]) {
          arr[k] = true;
        }
      }
    });
    that.mapOfCheckedId1 = arr;
    that.refreshStatus1();
  }

  // 在多选框中change已选中的科室-科室绑定分组
  changeCheckedDept2(e) {
    let that = this;
    let arr = {};
    e.forEach((e) => {
      for (var k in that.mapOfCheckedId2) {
        if (k == e && that.mapOfCheckedId2[k]) {
          arr[k] = true;
        }
      }
    });
    that.mapOfCheckedId2 = arr;
    that.refreshStatus2();
  }

  //科室绑定人员选中批量分配
  batch1 = false; //绑定人员是否批量分配
  batchPro1() {
    this.replaceFlag = false;
    let that = this;
    that.allotModal1 = true;
    that.batch1 = true;
  }
  //科室绑定分组选中批量分配
  batch2 = false; //绑定分组是否批量分配
  batchPro2() {
    this.replaceFlag = false;
    let that = this;
    that.allotModal2 = true;
    that.batch2 = true;
  }
  // 科室绑定人员选中批量取消分配
  batchUnAllot1() {
    let that = this;
    that.unAllotModal1 = true;
    that.batch1 = true;
  }
  // 科室绑定人员选中批量取消分配
  batchUnAllot2() {
    let that = this;
    that.unAllotModal2 = true;
    that.batch2 = true;
  }

  // 获取科室列表数据
  // listLength1 = 10;//科室列表总数据
  // pageIndex1 = 1;//科室列表当前页码
  // pageSize1 = 10;//科室列表每页展示数量
  getDeptList1() {
    this.tLoading = true;
    let that = this;
    let postData = {
      workAllocation: {
        id: that.workAllocations[that.checkedType["id"] + "" + that.classesId],
        ruleType: that.ruleTypes[that.checkedType["id"] + "" + that.classesId],
      },
      department: {
        building: {},
        hospital: { id: that.checkedType.hosId.id },
        type: {},
      },

      idx: that.pageIndex1 - 1,
      sum: that.pageSize1,
    };
    if (that.building1) {
      postData.department.building["id"] = that.building1;
    }
    if (that.deptName1) {
      postData.department["dept"] = that.deptName1;
    }
    if (that.deptNum1) {
      postData.department["pcode"] = that.deptNum1;
    }
    if (that.deptType1) {
      postData.department.type["id"] = that.deptType1;
    }
    that.mainService
      .coopConfig("getDeptsByAllocation", postData)
      .subscribe((data) => {
        this.tLoading = false;
        that.deptsByAllocation1 = data.list;
        that.listLength1 = data.totalNum;
        this.isAllDisplayDataChecked1 = this.deptsByAllocation1.every(
          (item) => this.mapOfCheckedId1[item.id]
        );
      });
  }

  // 获取分组列表数据
  // listLength2 = 10;//科室列表总数据
  // pageIndex1 = 1;//科室列表当前页码
  // pageSize2 = 10;//科室列表每页展示数量
  getDeptList2() {
    this.tLoading = true;
    let that = this;
    let postData = {
      workAllocation: {
        id: that.workAllocations[that.checkedType["id"] + "" + that.classesId],
        ruleType: that.ruleTypes[that.checkedType["id"] + "" + that.classesId],
      },
      department: {
        building: {},
        hospital: { id: that.checkedType.hosId.id },
        type: {},
      },
      idx: that.pageIndex2 - 1,
      sum: that.pageSize2,
    };
    if (that.building2) {
      postData.department.building["id"] = that.building2;
    }
    if (that.deptName2) {
      postData.department["dept"] = that.deptName2;
    }
    if (that.deptNum2) {
      postData.department["pcode"] = that.deptNum2;
    }
    if (that.deptType2) {
      postData.department.type["id"] = that.deptType2;
    }
    that.mainService
      .coopConfig("getDeptsByAllocation", postData)
      .subscribe((data) => {
        this.tLoading = false;
        that.deptsByAllocation2 = data.list;
        that.listLength2 = data.totalNum;
        this.isAllDisplayDataChecked2 = this.deptsByAllocation2.every(
          (item) => this.mapOfCheckedId2[item.id]
        );
      });
  }

  // 科室绑定人员搜索
  building1; //楼栋
  deptName1; //科室名称
  deptNum1; //科室编码
  deptType1; //科室类型
  search1(type) {
    if (type == 1) {
      this.pageIndex1 = 1;
    }
    this.getDeptList1();
    this.isAllDisplayDataChecked1 = false;
  }

  // 科室绑定分组搜索
  building2; //楼栋
  deptName2; //科室名称
  deptNum2; //科室编码
  deptType2; //科室类型
  search2(type) {
    if (type == 1) {
      this.pageIndex2 = 1;
    }
    this.getDeptList2();
  }

  // 获取所有用户列表
  isLoading = false; //下拉搜索框loading
  pageUserList = [];
  getAllUser(name?) {
    let that = this;
    let data = {
      idx: 0,
      sum: name !== undefined ? 20 : 9999,
      user: {
        name: name !== undefined ? name : "",
        hospital: {
          id: that.checkedType["hosId"]["id"],
        },
      },
    };
    this.timeNum++;
    that.mainService
      .getFetchDataList("data", "user", data)
      .subscribe((data) => {
        if (name === undefined) {
          that.allUserList = data.list;
        } else {
          that.pageUserList = data.list;
        }
        this.timeNum--;
        if (this.timeNum === 0) {
          that.isLoading = false;
        }
      });
  }
  // 打开搜索框
  changeIt(flag) {
    if (flag) {
      this.changeInp("no");
    }
  }
  // 生效
  takeEffect() {
    this.takeLoading = true;
    this.mainService.getCustom("ser", "refreshTaskType").subscribe((data) => {
      this.takeLoading = false;
      if (data.state == 200) {
        this.showPromptModal("生效", true, "您设置的工作分配已生效！");
      } else {
        this.showPromptModal("生效", false, "");
      }
    });
  }
  // 人员模糊搜索节流阀
  // time: any;//输入停止1秒后开始搜索用的定时器
  timeNum = 0;
  changeInp(e) {
    if (!e) {
      return;
    }
    if (e === "no") {
      e = "";
    }
    console.log(this.allotUsers1);
    let that = this;
    // clearTimeout(that.time);

    this.isLoading = true;
    // that.time = setTimeout(() => {
    that.getAllUser(e);
    // }, 2000);
  }
  // 科室绑定人员分配
  allotUsers1 = []; //分配人员选择
  allotModal1 = false; //分配弹窗
  deptData1; //当前执行分配操作的部门数据
  showDataDepts1 = [];
  // 打开分配弹窗
  allot1(data) {
    let that = this;
    that.deptData1 = data;
    that.allotModal1 = true;
    that.allotUsers1 = [];
    if (data.users && data.users.length) {
      this.pageUserList = [...data.users, ...this.pageUserList];
      console.log(this.pageUserList);
      data.users.forEach((res) => {
        that.allotUsers1.push(res.id);
      });
      this.showDataDepts1Click(that.allotUsers1);
    } else {
      this.showDataDepts1 = [];
    }
  }
  loading2 = false;
  showDataDepts1Click(v) {
    let postData = {
      workAllocationId:
        this.workAllocations[this.checkedType["id"] + "" + this.classesId],
      userId: v.join(),
    };
    this.loading2 = true;
    this.mainService.getDeptByUser(postData).subscribe((data) => {
      this.loading2 = false;
      if (data["state"] == 200) {
        this.showDataDepts1 = data["data"];
      }
    });
  }
  // 科室绑定分组分配
  allotGroups2 = []; //分配人员选择
  allotModal2 = false; //分配弹窗
  deptData2; //当前执行分配操作的部门数据
  showDataDepts2 = [];
  // 打开分配弹窗
  allot2(data) {
    let that = this;
    that.deptData2 = data;
    that.allotModal2 = true;
    that.allotGroups2 = [];
    console.log(data);
    if (data.groups && data.groups.length) {
      data.groups.forEach((res) => {
        that.allotGroups2.push(res.id);
      });
      this.showDataDepts2Click(that.allotGroups2);
    } else {
      this.showDataDepts2 = [];
    }
  }
  showDataDepts2Click(v) {
    let postData = {
      workAllocationId:
        this.workAllocations[this.checkedType["id"] + "" + this.classesId],
      groupId: v.join(),
    };
    this.loading2 = true;
    this.mainService.getDeptByGroup(postData).subscribe((data) => {
      this.loading2 = false;
      if (data["state"] == 200) {
        this.showDataDepts2 = data["data"];
      }
    });
  }
  //取消分配-科室绑定人员
  unAllotModal1 = false; //取消分配弹窗
  unAllot1(data?) {
    this.deptData1 = data;
    this.unAllotModal1 = true;
  }
  //取消分配-科室绑定分组
  unAllotModal2 = false; //取消分配弹窗
  unAllot2(data?) {
    this.deptData2 = data;
    this.unAllotModal2 = true;
  }
  // 关闭取消分配弹窗-科室绑定人员
  hideUnAllotModal1() {
    this.unAllotModal1 = false;
  }
  // 关闭取消分配弹窗-科室绑定分组
  hideUnAllotModal2() {
    this.unAllotModal2 = false;
  }
  // 关闭分配弹窗-科室绑定人员
  hideAllotModal1() {
    this.allotModal1 = false;
    this.isReplace = false;
    this.searchCon1 = false;
    this.replaceFlag = true;
  }
  // 关闭分配弹窗-科室绑定分组
  hideAllotModal2() {
    this.allotModal2 = false;
    this.isReplace = false;
    this.searchCon2 = false;
    this.replaceFlag = true;
  }

  // 确认分配-科室绑定人员
  confirm1() {
    let that = this;
    that.btnLoading = true;
    let postData = {
      workAllocation: {
        ruleType: 3,
        taskTypeId: that.checkedType["id"],
        classId: that.classesId,
      },
    };

    if (that.searchCon1) {
      // 搜索结果批量分配
      let string = "";
      string = that.allotUsers1.join(",");
      postData["users"] = string;
      postData["department"] = {
        building: {},
        type: {},
      };
      if (that.building1) {
        postData["department"].building["id"] = that.building1;
      }
      if (that.deptName1) {
        postData["department"]["dept"] = that.deptName1;
      }
      if (that.deptNum1) {
        postData["department"]["qrcode"] = that.deptNum1;
      }
      if (that.deptType1) {
        postData["department"].type["id"] = that.deptType1;
      }
    } else {
      // 不是搜索结果批量分配
      if (that.batch1) {
        // 批量分配
        postData.workAllocation["deptUserIds"] = [];
        that.checkedmultipleValue1.forEach((eee) => {
          postData.workAllocation["deptUserIds"].push({
            deptId: eee,
            userIds: that.allotUsers1,
          });
        });
      } else {
        postData.workAllocation["deptUserIds"] = [];
        postData.workAllocation["deptUserIds"] = [
          { deptId: that.deptData1.id, userIds: that.allotUsers1 },
        ];
      }
    }

    let workAllDatas = that.checkedType["workAllocation"] || [];
    let oldRuleType;
    workAllDatas.forEach((resp) => {
      if (that.classesId == resp.classId) {
        oldRuleType = resp.ruleType;
      }
    });
    if (oldRuleType != 3) {
      if (oldRuleType == 2) {
        postData.workAllocation["groups"] = [];
      } else if (oldRuleType == 4) {
        postData.workAllocation["deptGroupIds"] = [];
      }
    }
    console.log(
      that.workAllocations[that.checkedType["id"] + "" + that.classesId]
    );
    if (that.workAllocations[that.checkedType["id"] + "" + that.classesId]) {
      postData.workAllocation["id"] =
        that.workAllocations[that.checkedType["id"] + "" + that.classesId];
    }
    // return;
    if (!that.searchCon1) {
      postData.workAllocation["schemeId"] = this.queryParamsId;
    }
    if (this.isReplace) {
      postData.workAllocation["isReplace"] = 1;
    }
    that.mainService
      .coopConfig(that.searchCon1 ? "assignByCons" : "Allocate", postData)
      .subscribe((data) => {
        that.allotModal1 = false;
        that.isReplace = false;
        that.btnLoading = false;
        that.searchCon1 = false;
        if (data.status == 200) {
          that.showPromptModal("分配", true, "");
          that.checkedType = data.data;
          that.getDeptList1();
          this.checkType(that.checkedType, this.classesId, "no");
          // that.initCheckedTableInfo1();
        } else {
          that.showPromptModal("分配", false, data.msg);
        }
      });
  }

  // 确认分配-科室绑定分组
  confirm2() {
    let that = this;
    that.btnLoading = true;
    let postData = {
      workAllocation: {
        ruleType: 4,
        taskTypeId: that.checkedType["id"],
        classId: that.classesId,
      },
    };

    if (that.searchCon2) {
      // 搜索结果批量分配
      let string = "";
      string = that.allotGroups2.join(",");
      postData["groups"] = string;
      postData["department"] = {
        building: {},
        type: {},
      };
      if (that.building2) {
        postData["department"].building["id"] = that.building2;
      }
      if (that.deptName2) {
        postData["department"]["dept"] = that.deptName2;
      }
      if (that.deptNum2) {
        postData["department"]["qrcode"] = that.deptNum2;
      }
      if (that.deptType2) {
        postData["department"].type["id"] = that.deptType2;
      }
    } else {
      // 不是搜索结果批量分配
      if (that.batch2) {
        // 批量分配
        postData.workAllocation["deptGroupIds"] = [];
        that.checkedmultipleValue2.forEach((eee) => {
          postData.workAllocation["deptGroupIds"].push({
            deptId: eee,
            groupIds: that.allotGroups2,
          });
        });
      } else {
        postData.workAllocation["deptGroupIds"] = [];
        postData.workAllocation["deptGroupIds"] = [
          { deptId: that.deptData2.id, groupIds: that.allotGroups2 },
        ];
      }
    }

    let workAllDatas = that.checkedType["workAllocation"] || [];
    let oldRuleType;
    workAllDatas.forEach((resp) => {
      if (that.classesId == resp.classId) {
        oldRuleType = resp.ruleType;
      }
    });
    if (oldRuleType != 4) {
      if (oldRuleType == 2) {
        postData.workAllocation["groups"] = [];
      } else if (oldRuleType == 3) {
        postData.workAllocation["deptUserIds"] = [];
      }
    }
    if (that.workAllocations[that.checkedType["id"] + "" + that.classesId]) {
      postData.workAllocation["id"] =
        that.workAllocations[that.checkedType["id"] + "" + that.classesId];
    }
    // return;
    if (!that.searchCon2) {
      postData.workAllocation["schemeId"] = this.queryParamsId;
    }
    if (this.isReplace) {
      postData.workAllocation["isReplace"] = 1;
    }
    that.mainService
      .coopConfig(that.searchCon2 ? "assignByCons" : "Allocate", postData)
      .subscribe((data) => {
        that.allotModal2 = false;
        that.isReplace = false;
        that.btnLoading = false;
        if (data.status == 200) {
          that.showPromptModal("分配", true, "");
          that.checkedType = data.data;
          that.getDeptList2();
          that.initCheckedTableInfo2("no");
          that.searchCon2 = false;
          this.checkType(that.checkedType, this.classesId, "no");
        } else {
          that.showPromptModal("分配", false, data.msg);
        }
      });
  }

  // 确认取消分配-科室绑定人员
  confirmUn1() {
    let that = this;
    that.btnLoading = true;
    let postData;
    if (that.searchCon1) {
      // 搜索结果批量取消分配
      postData = {
        building: {},
        type: {},
      };
      if (that.building1) {
        postData.building["id"] = that.building1;
      }
      if (that.deptName1) {
        postData["dept"] = that.deptName1;
      }
      if (that.deptNum1) {
        postData["qrcode"] = that.deptNum1;
      }
      if (that.deptType1) {
        postData.type["id"] = that.deptType1;
      }
    } else {
      // 批量取消分配
      if (that.batch1) {
        postData = that.checkedmultipleValue1;
      } else {
        postData = [that.deptData1.id];
      }
    }

    // return;
    that.mainService
      .coopTypeConfig(
        that.searchCon1 ? "cancelAssignByCons" : "cancelAssign",
        that.workAllocations[that.checkedType["id"] + "" + that.classesId] +
          "/" +
          that.ruleTypes[that.checkedType["id"] + "" + that.classesId],
        postData
      )
      .subscribe((data) => {
        that.btnLoading = false;
        that.unAllotModal1 = false;
        if (data.status == 200) {
          that.showPromptModal("取消分配", true, "");
          that.checkedType = data.data;
          that.searchCon1 = false;
          that.getDeptList1();
          that.initCheckedTableInfo1("no");
        } else {
          that.showPromptModal("取消分配", false, data.msg);
        }
      });
  }

  // 确认取消分配-科室绑定分组
  confirmUn2() {
    let that = this;
    that.btnLoading = true;
    let postData;
    if (that.searchCon2) {
      // 搜索结果批量取消分配
      postData = {
        building: {},
        type: {},
      };
      if (that.building2) {
        postData.building["id"] = that.building2;
      }
      if (that.deptName2) {
        postData["dept"] = that.deptName2;
      }
      if (that.deptNum2) {
        postData["qrcode"] = that.deptNum2;
      }
      if (that.deptType2) {
        postData.type["id"] = that.deptType2;
      }
    } else {
      // 批量取消分配
      postData = that.batch2 ? that.checkedmultipleValue2 : [that.deptData2.id];
    }

    // return;
    that.mainService
      .coopTypeConfig(
        that.searchCon2 ? "cancelAssignByCons" : "cancelAssign",
        that.workAllocations[that.checkedType["id"] + "" + that.classesId] +
          "/" +
          that.ruleTypes[that.checkedType["id"] + "" + that.classesId],
        postData
      )
      .subscribe((data) => {
        that.unAllotModal2 = false;
        that.btnLoading = false;
        if (data.status == 200) {
          that.showPromptModal("取消分配", true, "");
          that.checkedType = data.data;
          that.searchCon2 = false;
          that.getDeptList2();
          that.initCheckedTableInfo2("no");
        } else {
          that.showPromptModal("取消分配", false, data.msg);
        }
      });
  }

  // 搜索结果批量分配-科室绑定人员
  searchCon1 = false;
  replaceFlag = true;
  resBatchAllot1() {
    let that = this;
    this.replaceFlag = false;
    that.allotModal1 = true;
    that.searchCon1 = true;
  }

  // 搜索结果批量取消分配-科室绑定人员
  resBatchUnAllot1() {
    let that = this;
    that.unAllotModal1 = true;
    that.searchCon1 = true;
  }

  // 清空选项，分配/取消分配完成之后初始化存储的表格数据-科室绑定人员
  initCheckedTableInfo1(isGo?) {
    let that = this;
    that.batch1 = false;
    that.checkedAllDeptInfos1 = [];
    that.mapOfCheckedId1 = {};
    that.checkedmultipleValue1 = [];
    that.isAllDisplayDataChecked1 = false;
    if (!isGo) {
      that.pageIndex1 = 1;
    }
  }

  // 初始化搜索条件-科室绑定人员
  initSearchCondition1() {
    let that = this;
    that.building1 = null;
    that.deptName1 = "";
    that.deptNum1 = "";
    that.deptType1 = null;
  }

  // 搜索结果批量分配-科室绑定人员
  searchCon2 = false;
  resBatchAllot2() {
    this.replaceFlag = false;
    let that = this;
    that.allotModal2 = true;
    that.searchCon2 = true;
  }

  // 搜索结果批量取消分配-科室绑定人员
  resBatchUnAllot2() {
    let that = this;
    that.unAllotModal2 = true;
    that.searchCon2 = true;
  }

  // 清空选项，分配/取消分配完成之后初始化存储的表格数据-科室绑定人员
  initCheckedTableInfo2(isGo?) {
    let that = this;
    that.batch2 = false;
    that.checkedAllDeptInfos2 = [];
    that.mapOfCheckedId2 = {};
    that.checkedmultipleValue2 = [];
    that.isAllDisplayDataChecked2 = false;
    if (!isGo) {
      that.pageIndex2 = 1;
    }
  }

  // 初始化搜索条件-科室绑定人员
  initSearchCondition2() {
    let that = this;
    that.building2 = null;
    that.deptName2 = "";
    that.deptNum2 = "";
    that.deptType2 = null;
  }

  // 展示信息提示框（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.getTypeList();
    }, 100);
  }

  // 获取所有院区
  getAllBuilding() {
    var that = this;
    that.mainService
      .coopData("getBuildingOrFloor", "building", {
        hosId: that.checkedType["hosId"].id,
      })
      .subscribe((data) => {
        that.allBuilding = data.data;
      });
  }

  // 获取所有科室类型
  getAlldeptType() {
    var that = this;
    that.mainService.getDictionary("list", "dept_type").subscribe((data) => {
      that.allDeptType = data;
    });
  }

  // 返回列表
  goToList() {
    this.showDelModal("未保存的设置将会被遗失，是否返回？");
  }
  // 切换
  goToCheck() {
    this.router.navigateByUrl(
      `/main/quickCombination?id=${this.queryParamsId}&name=${this.queryParamsName}`
    );
  }
  // 返回列表
  delModal: boolean = false; //返回列表模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（返回列表）
  confirmDelIsSwitch: boolean; //启用/停用
  showDelModal(tipsMsg1: string) {
    this.delModal = true;
    this.tipsMsg1 = tipsMsg1;
  }
  // 隐藏返回列表框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认返回列表
  confirmDel() {
    this.delModal = false;
    this.router.navigateByUrl("/main/workAssignment");
  }
}
