import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";
import setSeconds from "date-fns/setSeconds";
import setMinutes from "date-fns/setMinutes";
import setHours from "date-fns/setHours";

import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { NzMessageService } from "ng-zorro-antd";
@Component({
  selector: "app-quick-combination",
  templateUrl: "./quick-combination.component.html",
  styleUrls: ["./quick-combination.component.less"],
})
export class QuickCombinationComponent implements OnInit {
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private router: Router,
    private tool: ToolService
  ) {
    this.route.queryParams.subscribe((res) => {
      this.queryParamsId = res.id;
      this.queryParamsName = res.name;
      this.queryParamsType = res.type;
      if (this.queryParamsType == 2) {
        this.allWorkModel = [
          { id: 1, name: "自由抢单" },
          { id: 3, name: "科室绑定人员" },
          { id: 4, name: "科室绑定分组" },
          { id: 2, name: "绑定分组" },
        ];
      }
    });
  }
  searchCriteria = {
    //搜索条件
    name: "",
    workModel: null,
  };
  allWorkModel = [
    { id: 1, name: "自由抢单" },
    { id: 2, name: "指定分组" },
    { id: 3, name: "科室绑定人员" },
    { id: 4, name: "科室绑定分组" },
  ];
  quickCombinationModel;
  requireGroup = false;
  requireDept = false;
  requireDeptType = false;
  queryParamsId = ""; //方案id
  queryParamsName = ""; //方案名称
  queryParamsType: any = ""; //方案类型,1是综合排班，2是自选排班
  userInfo: any = JSON.parse(localStorage.getItem("user")) || {}; //登录用户信息
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  tableHeight: number; //表格动态高
  modal: boolean = false; //新增/编辑模态框
  personModal: boolean = false; //定时启用设置日期模态框
  groupsModal: boolean = false; //定时启用设置日期模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  validateDateForm: FormGroup; //定时启动设置日期表单
  validatePersonForm: FormGroup; //
  validateGroupForm: FormGroup; //
  coopId: number; //当前操作列id
  timeDefaultValue = setHours(setMinutes(setSeconds(new Date(), 0), 0), 0);

  btnLoading: boolean = false; //提交按钮loading状态
  currentHospital; //当前院区

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

  classList = []; //班次列表
  maskFlag: any = false;
  // -----------------------

  ngOnInit() {
    this.currentHospital = this.tool.getCurrentHospital();
    this.initForm();
    this.getList(1);
    this.getDispatchMethods();
    this.getDispatchTypes();
  }
  // 重置
  reset() {
    this.searchCriteria = {
      //搜索条件
      name: "",
      workModel: null,
    };
    this.getList(1);
  }
  //查询班次列表,flag是下拉框展开状态
  cLoading = false;
  getClassList(flag?, fedit?) {
    if (!flag) {
      return;
    }
    if (fedit) {
      this.maskFlag = this.message.loading("正在加载中..", {
        nzDuration: 0,
      }).messageId;
    }
    let hosIds = this.currentHospital.id;
    let postData = {
      idx: 0,
      sum: 9999,
      scheduleClass: { hospital: { id: hosIds } },
    };
    this.cLoading = true;
    this.mainService
      .getFetchDataList("configuration", "scheduleClass", postData)
      .subscribe((data) => {
        this.cLoading = false;
        if (data.status == 200) {
          this.classList = data.list;
          if (fedit) {
            this.searchTaskList(true, true);
          }
        }
      });
  }
  //选中班次
  currentClassId; //当前班次

  selectClass(id) {
    this.validateForm.controls.quickCombinationType.setValue(null); //任务类型

    this.quickCombinationModel = "";
    this.deptList = [];
    this.groupList = [];
    this.validateForm.controls.quickCombinationDept.setValue(null); //科室
    this.validateForm.controls.quickCombinationGroup.setValue(null); //分组
    this.currentClassId = id;
    this.taskListFlag = true;
  }
  //搜索任务类型列表
  taskList = []; //当前班次下的任务类型列表
  tLoading = false;
  taskListFlag = true; //是否可以选择所有的工作模式
  getTaskList(flag?, keyWords?, fedit?) {
    console.log(
      this.validateForm.value.quickCombinationType,
      this.taskListFlag
    );
    // 关闭下拉框的时候阻止
    if (!flag) {
      return;
    }
    // 之前没有选择任务类型
    if (
      (this.validateForm.value.quickCombinationType === null ||
        this.validateForm.value.quickCombinationType.length === 0) &&
      this.taskListFlag &&
      (fedit ? this.info.classes.id : this.currentClassId)
    ) {
      let postData = {
        classesId: fedit ? this.info.classes.id : this.currentClassId,
      };
      if (keyWords) {
        postData["keyWords"] = keyWords;
      }
      this.tLoading = true;
      this.mainService
        .coopConfig("getTaskTypeByClasses", postData)
        .subscribe((data) => {
          this.tLoading = false;
          if (data.state == 200) {
            console.log(this.currentClassId);
            if (this.currentClassId) {
              this.taskList = data.data;
            } else {
              this.taskList = [];
            }
            if (fedit) {
              let arr = [];
              this.info.taskTypes.forEach((item) => {
                let flag = this.taskList.some((v) => v.id == item.id);
                if (!flag) {
                  arr.push(item);
                }
              });
              this.taskList = [...arr, ...this.taskList];
              console.log(this.taskList);
              this.validateForm.controls.quickCombinationClass.setValue(
                this.info.classes.id + ""
              ); //班次
              this.validateForm.controls.quickCombinationType.setValue(
                this.info.taskTypesId
              ); //任务类型
              if(this.queryParamsType == 1){
                this.quickCombinationModel = this.info.ruleType + "";
              }else if(this.queryParamsType == 2){
                if(this.info.ruleType == 2){
                  this.quickCombinationModel = '6';
                }else if(this.info.ruleType == 4){
                  this.quickCombinationModel = '5';
                }else{
                  this.quickCombinationModel = this.info.ruleType + "";
                }
              }
              this.taskListFlag = false;
              if (!this.copyFlag) {
                if (this.info.ruleType == 2) {
                  this.getGroupList(true, "", true);
                } else if (this.info.ruleType == 3) {
                  if(this.queryParamsType == 1){
                    this.getDeptList(true, "", true);
                  }else{
                    this.getDeptTypeList(true, true);
                  }
                } else if (this.info.ruleType == 4) {
                  this.getDeptList(true, "", true);
                } else {
                  this.message.remove(this.maskFlag);
                  this.maskFlag = false;
                  this.modal = true;
                }
              }
            }
          }
          this.message.remove(this.maskFlag);
          this.maskFlag = false;
          this.modal = true;
        });
    }
  }
  // 选择任务类型
  ids = [];
  selectTaskList(ids, keyWords?, fedit?) {
    console.log(fedit);
    if (ids === null) {
      return;
    }
    console.log(this.currentClassId);
    if (
      this.validateForm.value.quickCombinationType &&
      this.validateForm.value.quickCombinationType.length > 0
    ) {
      let postData = {
        classesId: fedit ? this.info.classes.id : this.currentClassId,
        taskTypeId: ids[0],
        workSchemeId: this.queryParamsId,
      };
      if (keyWords) {
        postData["keyWords"] = keyWords;
      }
      this.ids = ids;
      this.mainService
        .coopConfig("getTaskTypeByFirstType", postData)
        .subscribe((data) => {
          if (data.state == 200) {
            this.taskList = data.data;
            if (fedit) {
              let arr = [];
              this.info.taskTypes.forEach((item) => {
                let flag = this.taskList.some((v) => v.id == item.id);
                if (!flag) {
                  arr.push(item);
                }
              });
              this.taskList = [...arr, ...this.taskList];
              this.validateForm.controls.quickCombinationClass.setValue(
                this.info.classes.id + ""
              ); //班次
              this.validateForm.controls.quickCombinationType.setValue(
                this.info.taskTypesId
              ); //任务类型
              this.quickCombinationModel = this.info.ruleType + "";
              this.taskListFlag = false;
              return;
            }
            if (data.data && data.data.length > 0) {
              let obj = data.data.find(
                (item) => item.ruleType != "0" && item.showFlag == 1
              );
              console.log(obj);
              if (obj) {
                if(this.queryParamsType == 1){
                  this.quickCombinationModel = obj.ruleType + "";
                }else if(this.queryParamsType == 2){
                  if(obj.ruleType == 2){
                    this.quickCombinationModel = '6';
                  }else if(obj.ruleType == 4){
                    this.quickCombinationModel = '5';
                  }else{
                    this.quickCombinationModel = obj.ruleType + "";
                  }
                }
                this.radioIt(1); //选择任务类型
                this.taskListFlag = false;
              } else {
                //都是置灰的或之前没设置过的
                this.taskListFlag = true;
                this.quickCombinationModel = "";
              }
            } else {
              //返回空
              this.taskListFlag = true;
              this.quickCombinationModel = "";
            }
          } else if (data.state == 201) {
            //201则是该班次该任务类型之前没有设置过，所以无法返回带置灰选项的列表
            this.taskListFlag = true;
            if (fedit) {
              this.getTaskList(true, "", true);
            } else {
              this.getTaskList(true);
            }
            this.quickCombinationModel = "";
          }
        });
    } else {
      this.taskListFlag = true;
      if (fedit) {
        this.getTaskList(true, "", true);
      } else {
        this.getTaskList(true);
      }
      this.quickCombinationModel = "";
    }
  }
  // 搜索任务类型列表
  searchTaskList(e, fedit?) {
    console.log(this.validateForm.value.quickCombinationType);
    if (
      this.validateForm.value.quickCombinationType &&
      this.validateForm.value.quickCombinationType.length === 0
    ) {
      if (fedit) {
        this.getTaskList(true, e, fedit);
      } else {
        this.getTaskList(true, e);
      }
    } else {
      if (fedit) {
        this.selectTaskList(this.ids, e, fedit);
      } else {
        this.selectTaskList(this.ids, e);
      }
    }
  }
  searchTaskList1(flag) {
    if (flag) {
      this.searchTaskList("");
    }
  }
  //对应ruleType与quickCombinationModel
  get quickCombinationModelComputed(){
    console.log(this.quickCombinationModel,'---------------------')
    if(this.quickCombinationModel == 5){//科室绑定分组
      return 4;
    }else if(this.quickCombinationModel == 6){//绑定分组
      return 2;
    }else{
      return this.quickCombinationModel;
    }
  }
  // 选中工作模式
  radioIt(flag?) {
    //undefined 打开复制弹窗，1 选择任务类型
    console.log(flag);
    if (!this.add) {
      // 回显储存的值
      console.log(this.info, this.quickCombinationModel);
      if (
        this.info.ruleType == this.quickCombinationModelComputed &&
        (this.quickCombinationModel == 2 || this.quickCombinationModel == 5 || this.quickCombinationModel == 6)
      ) {
        this.groupList = this.info.groups;
        if (!this.copyFlag) {
          if(this.quickCombinationModel == 6){
            this.validateForm.controls.quickCombinationGroup.setValue((this.info.groupsId?this.info.groupsId[0] + '':null));
          }else{
            this.validateForm.controls.quickCombinationGroup.setValue(
              this.info.groupsId
            );
          }
        } else {
          if (!flag) {
            this.validateForm.controls.quickCombinationGroup.setValue(null);
          } else {
            if(this.quickCombinationModel == 6){
              this.validateForm.controls.quickCombinationGroup.setValue((this.info.groupsId?this.info.groupsId[0] + '':null));
            }else{
              this.validateForm.controls.quickCombinationGroup.setValue(
                this.info.groupsId
              );
            }
          }
        }
      }
      if (
        (this.info.ruleType == 3 || this.info.ruleType == 4) &&
        (this.quickCombinationModel == 3 || this.quickCombinationModel == 4)
      ) {
        this.deptList = this.info.departmentDTOS;
        if (!this.copyFlag) {
          this.validateForm.controls.quickCombinationDept.setValue(
            this.info.departmentDTOSId
          );
        } else {
          if (!flag) {
            this.validateForm.controls.quickCombinationDept.setValue(null);
          } else {
            this.validateForm.controls.quickCombinationDept.setValue(
              this.info.departmentDTOSId
            );
          }
        }
      }
    }

    if (this.quickCombinationModel == 1) {
      this.requireGroup = false;
      this.requireDept = false;
      this.requireDeptType = false;
    } else if (this.quickCombinationModel == 2) {
      this.requireGroup = false;
      this.requireDept = false;
      this.requireDeptType = false;
    } else if (this.quickCombinationModel == 3) {
      if (this.queryParamsType == 1) {
        this.requireGroup = false;
        this.requireDept = true;
        this.requireDeptType = false;
      } else if (this.queryParamsType == 2) {
        this.requireGroup = false;
        this.requireDept = false;
        this.requireDeptType = true;
      }
    } else if (this.quickCombinationModel == 4) {
      this.requireGroup = false;
      this.requireDept = true;
      this.requireDeptType = false;
    }else if (this.quickCombinationModel == 5) {
      this.requireGroup = false;
      this.requireDept = false;
      this.requireDeptType = false;
    }else if (this.quickCombinationModel == 6) {
      this.requireGroup = false;
      this.requireDept = false;
      this.requireDeptType = false;
    }
    if (!this.requireGroup) {
      this.validateForm.get("quickCombinationGroup")!.clearValidators();
      this.validateForm.get("quickCombinationGroup")!.markAsPristine();
    } else {
      this.validateForm
        .get("quickCombinationGroup")!
        .setValidators(Validators.required);
      this.validateForm.get("quickCombinationGroup")!.markAsDirty();
    }
    this.validateForm.get("quickCombinationGroup")!.updateValueAndValidity();
    // ------
    if (!this.requireDept) {
      this.validateForm.get("quickCombinationDept")!.clearValidators();
      this.validateForm.get("quickCombinationDept")!.markAsPristine();
    } else {
      this.validateForm
        .get("quickCombinationDept")!
        .setValidators(Validators.required);
      this.validateForm.get("quickCombinationDept")!.markAsDirty();
    }
    this.validateForm.get("quickCombinationDept")!.updateValueAndValidity();
    // ------
    if (!this.requireDeptType) {
      this.validateForm.get("deptTypeIds")!.clearValidators();
      this.validateForm.get("deptTypeIds")!.markAsPristine();
    } else {
      this.validateForm
        .get("deptTypeIds")!
        .setValidators(Validators.required);
      this.validateForm.get("deptTypeIds")!.markAsDirty();
    }
    this.validateForm.get("deptTypeIds")!.updateValueAndValidity();
    // ------
    if (!(this.queryParamsType == 1 && this.quickCombinationModel == 1)) {
      this.validateForm.get("quickCombinationDispatchMethod")!.clearValidators();
      this.validateForm.get("quickCombinationDispatchMethod")!.markAsPristine();
    } else {
      this.validateForm.get("quickCombinationDispatchMethod")!.setValidators(Validators.required);
      this.validateForm.get("quickCombinationDispatchMethod")!.markAsDirty();
    }
    this.validateForm.get("quickCombinationDispatchMethod")!.updateValueAndValidity();
    if(this.add){
      this.validateForm.controls.quickCombinationDispatchMethod.setValue(null);
    }else{
      this.validateForm.controls.quickCombinationDispatchMethod.setValue(this.info.dispatchMethod ? this.info.dispatchMethod.value : null);
    }
    // ------
    if (!(this.queryParamsType == 1 && this.quickCombinationModel == 1 && this.validateForm.value.quickCombinationDispatchMethod == 2)) {
      this.validateForm.get("quickCombinationDispatchType")!.clearValidators();
      this.validateForm.get("quickCombinationDispatchType")!.markAsPristine();
    } else {
      this.validateForm.get("quickCombinationDispatchType")!.setValidators(Validators.required);
      this.validateForm.get("quickCombinationDispatchType")!.markAsDirty();
    }
    this.validateForm.get("quickCombinationDispatchType")!.updateValueAndValidity();
    if(this.add){
      this.validateForm.controls.quickCombinationDispatchType.setValue(null);
    }else{
      this.validateForm.controls.quickCombinationDispatchType.setValue(this.info.dispatchType ? this.info.dispatchType.value : null);
    }
    // ------
    if (!(this.queryParamsType == 1 && this.quickCombinationModel == 1 && this.validateForm.value.quickCombinationDispatchMethod == 2 && this.validateForm.value.quickCombinationDispatchType == 1)) {
      this.validateForm.get("quickCombinationDispatchWeight")!.clearValidators();
      this.validateForm.get("quickCombinationDispatchWeight")!.markAsPristine();
    } else {
      this.validateForm.get("quickCombinationDispatchWeight")!.setValidators(Validators.required);
      this.validateForm.get("quickCombinationDispatchWeight")!.markAsDirty();
    }
    this.validateForm.get("quickCombinationDispatchWeight")!.updateValueAndValidity();
    if(this.add){
      this.validateForm.controls.quickCombinationDispatchWeight.setValue(null);
    }else{
      this.validateForm.controls.quickCombinationDispatchWeight.setValue(this.info.maxWeight);
    }
		if(this.add){
		  this.validateForm.controls.sendOrderRemind.setValue(null);
		}else{
		  this.validateForm.controls.sendOrderRemind.setValue(this.info.sendOrderRemind != undefined ? this.info.sendOrderRemind +"" : null);
		}
  }
  //获取派单方式
  dispatchMethods:any[] = [];
  getDispatchMethods() {
    this.mainService.getDictionary("list", "dispatchMethod").subscribe((data) => {
      this.dispatchMethods = data;
    });
  }
  //获取派单类型
  dispatchTypes:any[] = [];
  getDispatchTypes() {
    this.mainService.getDictionary("list", "dispatchType").subscribe((data) => {
      this.dispatchTypes = data;
    });
  }
  // 选择派单方式
  radioDispatchMethod(){
    if (!(this.queryParamsType == 1 && this.quickCombinationModel == 1 && this.validateForm.value.quickCombinationDispatchMethod == 2)) {
      this.validateForm.get("quickCombinationDispatchType")!.clearValidators();
      this.validateForm.get("quickCombinationDispatchType")!.markAsPristine();
    } else {
      this.validateForm.get("quickCombinationDispatchType")!.setValidators(Validators.required);
      this.validateForm.get("quickCombinationDispatchType")!.markAsDirty();
    }
    this.validateForm.get("quickCombinationDispatchType")!.updateValueAndValidity();
    this.validateForm.controls.quickCombinationDispatchType.setValue(null);
  }
  // 选择自动派单类型
  radioDispatchType(){
    if (!(this.queryParamsType == 1 && this.quickCombinationModel == 1 && this.validateForm.value.quickCombinationDispatchMethod == 2 && this.validateForm.value.quickCombinationDispatchType == 1)) {
      this.validateForm.get("quickCombinationDispatchWeight")!.clearValidators();
      this.validateForm.get("quickCombinationDispatchWeight")!.markAsPristine();
    } else {
      this.validateForm.get("quickCombinationDispatchWeight")!.setValidators(Validators.required);
      this.validateForm.get("quickCombinationDispatchWeight")!.markAsDirty();
    }
    this.validateForm.get("quickCombinationDispatchWeight")!.updateValueAndValidity();
    this.validateForm.controls.quickCombinationDispatchWeight.setValue(null);
  }

  //获取科室类型列表
  deptTypeList:any[] = [];
  getDeptTypeList(flag?, fedit?) {
    if (!flag) {
      return;
    }
    this.dLoading = true;
    this.mainService
      .getDictionary("list", "dept_type")
      .subscribe((data) => {
        this.dLoading = false;
        this.deptTypeList = data;
        if (fedit) {
          switch (this.info.ruleType) {
            case 1:
              break;
            case 2:
              break;
            case 3:
              if(this.queryParamsType == 2){
                console.log(this.info);
                let deptTypeList = this.info.deptTypeList || [];
                this.validateForm.controls.deptTypeIds.setValue(deptTypeList.map(v => v.id.toString()));
              }
              break;
            case 4:
              break;
          }
        }
      });
  }

  deptList = []; //科室列表
  dLoading = false;
  dNum = 0;
  //获取科室列表
  getDeptList(flag?, search = "", fedit?) {
    if (!flag) {
      return;
    }
    let hosIds = this.currentHospital.id;
    let postData = {
      idx: 0,
      sum: 20,
      department: { cascadeHosId: hosIds, dept: search },
    };
    this.dLoading = true;
    this.dNum++;
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((data) => {
        this.dNum--;
        if (this.dNum === 0) {
          this.dLoading = false;
        }
        if (data.status == 200) {
          this.deptList = data.list;
          if (fedit) {
            switch (this.info.ruleType) {
              case 1:
                this.validateForm.controls.quickCombinationDept.setValue(null);
                break;
              case 2:
                this.validateForm.controls.quickCombinationDept.setValue(null);
                break;
              case 3:
                let arr = [];
                let arrr = [];
                this.info.departmentDTOS.forEach((item) => {
                  arr.push(item.id + "");
                });
                this.info.departmentDTOS.forEach((item) => {
                  let flag = this.deptList.some((v) => v.id == item.id);
                  if (!flag) {
                    arrr.push(item);
                  }
                });
                this.deptList = [...arrr, ...this.deptList];
                this.validateForm.controls.quickCombinationDept.setValue(arr);
                break;
              case 4:
                if(this.queryParamsType == 1){
                  let arr1 = [];
                  let arr11 = [];
                  this.info.departmentDTOS.forEach((item) => {
                    arr1.push(item.id + "");
                  });
                  this.info.departmentDTOS.forEach((item) => {
                    let flag = this.deptList.some((v) => v.id == item.id);
                    if (!flag) {
                      arr11.push(item);
                    }
                  });
                  this.deptList = [...arr11, ...this.deptList];
                  this.validateForm.controls.quickCombinationDept.setValue(arr1);
                }else if(this.queryParamsType == 2){
                  this.validateForm.controls.quickCombinationDept.setValue(null);
                }
                break;
            }
          }
        }
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.modal = true;
      });
  }
  // 搜索科室列表
  searchDeptList(e) {
    this.getDeptList(true, e);
  }
  // 选择科室
  selectDeptList(ids) {
    console.log(ids);
    if (!this.add) {
      console.log(this.info.departmentDTOSId);
      this.info.departmentDTOSId = ids;
    }
  }
  groupList = []; //分组列表
  gLoading = false;
  gNum = 0;
  //获取分组列表
  getGroupList(flag?, search = "", fedit?) {
    if (!flag) {
      return;
    }
    let hosIds = this.currentHospital.id;
    let postData:any = {
      idx: 0,
      sum: 20,
      group2: {
        groupName: search,
        scheduleClass: {
          id: fedit ? this.info.classes.id : this.currentClassId,
        },
        hospitals: hosIds,
      },
    };
    console.log(this.queryParamsType,this.quickCombinationModel);
    if(this.queryParamsType == 2 && (this.quickCombinationModel == 5 || this.quickCombinationModel == 6)){
      postData.group2.type = 2;
    }else{
      postData.group2.type = 1;
    }
    this.gLoading = true;
    this.gNum++;
    this.mainService
      .getFetchDataList("data", "group2", postData)
      .subscribe((data) => {
        this.gNum--;
        if (this.gNum === 0) {
          this.gLoading = false;
        }
        if (data.status == 200) {
          this.groupList = data.list;
          console.log(fedit, this.info);
          if (fedit) {
            switch (this.info.ruleType) {
              case 1:
                this.validateForm.controls.quickCombinationGroup.setValue(null);
                break;
              case 2:
                let arr = [];
                let arrr = [];
                this.info.groups.forEach((item) => {
                  let flag = this.groupList.some((v) => v.id == item.id);
                  arr.push(item.id + "");
                  console.log(flag);
                  if (!flag) {
                    arrr.push(item);
                  }
                });
                this.groupList = [...arrr, ...this.groupList];
                console.log(this.groupList, arrr, arr);
                if(this.queryParamsType == 1){
                  this.validateForm.controls.quickCombinationGroup.setValue(arr);
                }else if(this.queryParamsType == 2){
                  this.validateForm.controls.quickCombinationGroup.setValue(arr[0] + '');
                }
                break;
              case 3:
                this.validateForm.controls.quickCombinationGroup.setValue(null);
                break;
              case 4:
                if(this.queryParamsType == 1){
                  this.validateForm.controls.quickCombinationGroup.setValue(null);
                }else if(this.queryParamsType == 2){
                  let arr = [];
                  let arrr = [];
                  this.info.groups.forEach((item) => {
                    let flag = this.groupList.some((v) => v.id == item.id);
                    arr.push(item.id + "");
                    console.log(flag);
                    if (!flag) {
                      arrr.push(item);
                    }
                  });
                  this.groupList = [...arrr, ...this.groupList];
                  console.log(this.groupList, arrr, arr);
                  this.validateForm.controls.quickCombinationGroup.setValue(arr);
                }
                break;
            }
          }
        }
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.modal = true;
      });
  }
  // 搜索分组列表
  searchGroupList(e) {
    this.getGroupList(true, e);
  }
  // 选择分组
  selectGroupList(ids) {
    if (!this.add) {
      this.info.groupsId = ids !== null ? ids : [];
    }
  }
  // 切换
  goToOther() {
    this.router.navigateByUrl(
      `/main/jobAssignment?id=${this.queryParamsId}&name=${this.queryParamsName}`
    );
  }

  personList = []; //分配人员列表
  pLoading = false;
  pNum = 0;
  //获取分配人员列表
  getPersonList(flag?, search = "", edit?, info?) {
    if (!flag) {
      return;
    }
    let postData = {
      idx: 0,
      sum: 20,
      user: {
        simpleQuery:true,
        usertype: { id: 106 },
        name: search,
        hospital: {
          id: this.currentHospital.id,
        },
      },
    };
    this.pLoading = true;
    this.pNum++;
    if (edit) {
      this.maskFlag = this.message.loading("正在加载中..", {
        nzDuration: 0,
      }).messageId;
    }
    this.mainService
      .getFetchDataList("data", "user", postData)
      .subscribe((data) => {
        this.pNum--;
        if (this.pNum === 0) {
          this.pLoading = false;
          if (edit) {
            this.message.remove(this.maskFlag);
            this.maskFlag = false;
            this.personModal = true;
          }
        }
        if (data.status == 200) {
          this.personList = data.list;
          if (edit) {
            let arr = [];
            let arrIds = [];
            info.users.forEach((item) => {
              let flag = this.personList.some((v) => v.id == item.id);
              if (!flag) {
                arr.push(item);
              }
              arrIds.push(item.id + "");
            });
            this.personList = [...arr, ...this.personList];
            this.validatePersonForm.controls.quickCombinationPerson.setValue(
              arrIds[0]
            ); //人员
          }
        }
      });
  }
  // 搜索分配人员列表
  searchPersonList(e) {
    this.getPersonList(true, e);
  }
  groupsList = []; //分组列表
  gpLoading = false;
  gpNum = 0;
  //获取分配分组列表
  getGroupsList(flag?, search = "", edit?, info?) {
    if (!flag) {
      return;
    }
    let hosIds = this.currentHospital.id;
    let postData = {
      idx: 0,
      sum: 20,
      group2: {
        groupName: search,
        scheduleClass: {
          id: this.gpClassId,
        },
        hospitals: hosIds,
        type:1
      },
    };
    this.gpLoading = true;
    if (edit) {
      this.maskFlag = this.message.loading("正在加载中..", {
        nzDuration: 0,
      }).messageId;
    }
    this.gpNum++;
    this.mainService
      .getFetchDataList("data", "group2", postData)
      .subscribe((data) => {
        this.gpNum--;
        if (this.gpNum === 0) {
          this.gpLoading = false;
          if (edit) {
            this.message.remove(this.maskFlag);
            this.maskFlag = false;
            this.groupsModal = true;
          }
        }
        if (data.status == 200) {
          this.groupsList = data.list;
          if (edit) {
            console.log(info);
            let arr = [];
            let arrIds = [];
            info.groups.forEach((item) => {
              let flag = this.groupsList.some((v) => v.id == item.id);
              if (!flag) {
                arr.push(item);
              }
              arrIds.push(item.id + "");
            });
            this.groupsList = [...arr, ...this.groupsList];
            this.validateGroupForm.controls.quickCombinationGroups.setValue(
              arrIds
            ); //分组
          }
        }
      });
  }
  // 搜索分配人员列表
  searchGroupsList(e) {
    this.getGroupsList(true, e);
  }

  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      workAllocationQuickConfig: {
        workSchemeId: this.queryParamsId,
        hosId: this.currentHospital.id,
      },
      idx: this.pageIndex - 1,
      sum: this.pageSize,
    };
    if (this.searchCriteria.name) {
      data["workAllocationQuickConfig"]["configName"] =
        this.searchCriteria.name;
    }
    if (this.searchCriteria.workModel) {
      data["workAllocationQuickConfig"]["ruleType"] =
        this.searchCriteria.workModel;
    }
    this.loading1 = true;
    this.mainService
      .getFetchDataList("configuration", "workAllocationQuickConfig", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          let arr = ["自由抢单", "指定分组", "科室绑定人员", "科室绑定分组"];
          let _arr = ["自由抢单", "绑定分组", "科室绑定人员", "科室绑定分组"];
          this.listOfData = data.list;
          data.list.forEach((item) => {
            let arr1 = [];
            let arr2 = [];
            let arr3 = [];
            let arr4 = [];
            let arr5 = [];
            let arr6 = [];
            let arr7 = [];
            if(this.queryParamsType == 1){
              item.ruleTypeName = arr[item.ruleType - 1];
            }else if(this.queryParamsType == 2){
              item.ruleTypeName = _arr[item.ruleType - 1];
            }
            item.taskTypes.forEach((v) => {
              arr1.push(v.taskName);
              arr2.push(v.id + "");
            });
            if (item.users) {
              item.users.forEach((v) => {
                arr3.push(v.name);
                arr6.push(v.id);
              });
            } else if (item.groups) {
              item.groups.forEach((v) => {
                arr3.push(v.groupName);
                arr4.push(v.id + "");
              });
            } else {
              arr3 = ["-"];
            }
            if (item.departmentDTOS) {
              item.departmentDTOS.forEach((v) => {
                arr5.push(v.id + "");
                arr7.push(v.dept);
              });
            } else {
              arr7 = ["-"];
            }
            item.taskTypesName = arr1;
            item.taskTypesId = arr2;
            item.allName = arr3;
            item.groupsId = arr4;
            item.departmentDTOSId = arr5;
            item.usersId = arr6;
            item.departmentDTOSName = arr7;
          });
          this.listLength = data.totalNum;
        }
      });
  }

  // 新增/编辑弹框
  addModal() {
    this.add = true; //新增
    this.modal = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.copyFlag = false;
    this.initForm();
  }
  // 新增/编辑弹框
  ruleTypeCoopId;
  addPersonModal(e, data) {
    e.stopPropagation();
    this.coopId = data.id;
    this.ruleTypeCoopId = data.ruleType;
    this.initPersonForm();
    this.getPersonList(true, "", "edit", data);
  }
  //关闭
  hidePersonModal() {
    this.personModal = false;
    this.initPersonForm();
  }
  // 分配分组弹框
  gpClassId;
  addGroupsModal(e, data) {
    e.stopPropagation();
    console.log(data);
    this.gpClassId = data.classes.id;
    this.coopId = data.id;
    this.ruleTypeCoopId = data.ruleType;
    this.initGroupsForm();
    this.getGroupsList(true, "", "edit", data);
  }
  //关闭
  hideGroupsModal() {
    this.groupsModal = false;
    this.initGroupsForm();
  }
  // 初始化新增form表单
  initForm() {
    this.taskList = [];
    this.currentClassId = "";
    this.quickCombinationModel = "";
    this.taskListFlag = true;
    this.validateForm = this.fb.group({
      quickCombinationName: [null, [Validators.required]],
      quickCombinationClass: [null, [Validators.required]],
      quickCombinationType: [null, [Validators.required]],
      quickCombinationModel: [null, [Validators.required]],
      quickCombinationDept: this.requireGroup ? [null, [Validators.required]] : [null],
      quickCombinationGroup: this.requireDept ? [null, [Validators.required]] : [null],
      deptTypeIds: this.requireDeptType ? [null, [Validators.required]] : [null],
      quickCombinationDispatchMethod: [null],
      quickCombinationDispatchType: [null],
      quickCombinationDispatchWeight: [null],
			sendOrderRemind: ['0', [Validators.required]],
    });
  }
  // 初始化新增form表单
  initPersonForm() {
    this.validatePersonForm = this.fb.group({
      quickCombinationPerson: [null, [Validators.required]],
    });
  }
  // 初始化新增form表单
  initGroupsForm() {
    this.validateGroupForm = this.fb.group({
      quickCombinationGroups: [null, [Validators.required]],
    });
  }
  //生效
  takeEffect() {
    let postData = { workSchemeId: this.queryParamsId };
    this.tLoading = true;
    this.showPromptModal("生效", false, "", true);
    this.mainService
      .coopConfig(
        this.queryParamsType == 1 ? "takeEffect" : "optionalTakeEffect",
        postData
      )
      .subscribe((data) => {
        if (data.state == 200) {
          this.ifSuccess = true;
          this.promptInfo = "";
          this.showLoading = false;
        } else if (data.state == 201 || data.state == 203) {
          this.promptInfo = data.msg;
          this.showLoading = false;
        } else {
          this.promptInfo = "";
          this.showLoading = false;
        }
      });
  }
  // 新增/编辑表单提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    console.log(this.validateForm);
    this.btnLoading = true;

    if (this.validateForm.invalid) {
      this.btnLoading = false;
      return;
    }
    let data = {};
    let taskTypesIds = this.validateForm.value.quickCombinationType.map(
      (item) => {
        return {
          id: item,
        };
      }
    );
    data = {
      workAllocationQuickConfig: {
        hosId: this.currentHospital.id,
        configName: this.validateForm.value.quickCombinationName,
        classes: {
          id: this.validateForm.value.quickCombinationClass,
        },
        taskTypes: taskTypesIds,
        ruleType: this.quickCombinationModelComputed,
        workSchemeId: this.queryParamsId,
        dispatchMethod: this.dispatchMethods.find(v => v.value == this.validateForm.value.quickCombinationDispatchMethod),
        dispatchType: this.validateForm.value.quickCombinationDispatchMethod == 2 ? (this.dispatchTypes.find(v => v.value == this.validateForm.value.quickCombinationDispatchType)) : undefined,
        maxWeight: (this.validateForm.value.quickCombinationDispatchMethod == 2 && this.validateForm.value.quickCombinationDispatchType == 1) ? this.validateForm.value.quickCombinationDispatchWeight : undefined,
				sendOrderRemind: this.validateForm.value.sendOrderRemind
			},
    };
    console.log(this.validateForm.value.deptTypeIds);
    //添加科室类型字段
    if (this.validateForm.value.deptTypeIds && this.quickCombinationModel == 3 && this.queryParamsType == 2) {
      data["workAllocationQuickConfig"]["deptTypeIds"] = this.validateForm.value.deptTypeIds.toString();
    }
    //添加科室字段,绑定人字段
    if (
      this.validateForm.value.quickCombinationDept &&
      this.quickCombinationModel == 3 &&
      this.queryParamsType == 1
    ) {
      let departmentDTOS = this.validateForm.value.quickCombinationDept.map(
        (item) => {
          return {
            id: item,
          };
        }
      );
      let usersId = [];
      if (!this.add) {
        usersId = this.info.usersId.map((item) => {
          return {
            id: item,
          };
        });
      }
      data["workAllocationQuickConfig"]["departmentDTOS"] = departmentDTOS;
      if (!this.add) {
        if (this.info.ruleType != this.quickCombinationModel || this.copyFlag) {
          data["workAllocationQuickConfig"]["users"] = null;
        } else {
          data["workAllocationQuickConfig"]["users"] = usersId;
        }
      }
    }
    //添加科室字段,绑定组字段
    if (
      this.validateForm.value.quickCombinationDept &&
      this.quickCombinationModel == 4
    ) {
      let departmentDTOS = this.validateForm.value.quickCombinationDept.map(
        (item) => {
          return {
            id: item,
          };
        }
      );
      let groupsId = [];
      if (!this.add) {
        groupsId = this.info.groupsId.map((item) => {
          return {
            id: item,
          };
        });
      }
      data["workAllocationQuickConfig"]["departmentDTOS"] = departmentDTOS;
      if (!this.add) {
        if (this.info.ruleType != this.quickCombinationModel || this.copyFlag) {
          data["workAllocationQuickConfig"]["groups"] = null;
        } else {
          data["workAllocationQuickConfig"]["groups"] = groupsId;
        }
      }
    }
    //指定分组,添加分组字段
    console.log(this.validateForm.value.quickCombinationGroup);
    if (
      this.validateForm.value.quickCombinationGroup &&
      (this.quickCombinationModel == 2 || this.quickCombinationModel == 5 || this.quickCombinationModel == 6)
    ) {
      if(this.quickCombinationModel == 5){
        let groups = this.validateForm.value.quickCombinationGroup.map((item) => {
          return {
            id: item,
          };
        });
        if (groups.length > 0) {
          if (this.copyFlag) {
            data["workAllocationQuickConfig"]["groups"] = null;
          } else {
            data["workAllocationQuickConfig"]["groups"] = groups;
          }
        } else {
          data["workAllocationQuickConfig"]["groups"] = null;
        }
      }else if(this.quickCombinationModel == 6){
        if(this.validateForm.value.quickCombinationGroup){
          let groups = [{id:this.validateForm.value.quickCombinationGroup}];
          if (this.copyFlag) {
            data["workAllocationQuickConfig"]["groups"] = null;
          } else {
            data["workAllocationQuickConfig"]["groups"] = groups;
          }
        }else{
          data["workAllocationQuickConfig"]["groups"] = null;
        }
      }
    }
    if (!this.add && !this.copyFlag) {
      //编辑
      data["workAllocationQuickConfig"]["id"] = this.info.id;
    }
    this.mainService
      .coopTypeConfig(
        this.add || (!this.add && this.copyFlag) ? "addData" : "updData",
        "workAllocationQuickConfig",
        data
      )
      .subscribe((result) => {
        this.btnLoading = false;
        if (result.status == 200) {
          console.log(this.copyFlag);
          if (this.add) {
            this.showPromptModal("新增", true, "");
            this.listLength++;
          } else if (this.copyFlag) {
            this.showPromptModal("复制", true, "");
            this.listLength++;
          } else if (!this.copyFlag) {
            //编辑
            this.showPromptModal("编辑", true, "");
          }
        } else {
          let msg = "";
          if (this.add) {
            msg = "新增";
          } else if (!this.copyFlag) {
            msg = "修改";
          } else if (this.copyFlag) {
            msg = "复制";
          }
          this.showPromptModal(msg, false, result.msg);
        }
        this.hideAddModal();
        this.initForm();
      });
  }
  // 分配人员提交
  submitPersonForm(): void {
    this.btnLoading = true;
    for (const i in this.validatePersonForm.controls) {
      this.validatePersonForm.controls[i].markAsDirty();
      this.validatePersonForm.controls[i].updateValueAndValidity();
    }
    if (this.validatePersonForm.invalid) {
      this.btnLoading = false;
      return;
    }
    let usersIds = [];
    if (this.validatePersonForm.value.quickCombinationPerson) {
      // usersIds = this.validatePersonForm.value.quickCombinationPerson.map(
      //   (item) => {
      //     return { id: item };
      //   }
      // );
      usersIds.push({ id: this.validatePersonForm.value.quickCombinationPerson });
    }
    let data = {
      workAllocationQuickConfig: {
        hosId: this.currentHospital.id,
        id: this.coopId,
        users: usersIds,
        ruleType: this.ruleTypeCoopId,
      },
    };
    this.mainService
      .coopTypeConfig("updData", "workAllocationQuickConfig", data)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hidePersonModal();
        this.initPersonForm();
        if (data.status == 200) {
          this.showPromptModal("分配人员", true, "");
        } else {
          this.showPromptModal("分配人员", false, data.msg);
        }
      });
  }
  // 分配分组提交
  submitGroupsForm(): void {
    this.btnLoading = true;
    for (const i in this.validateGroupForm.controls) {
      this.validateGroupForm.controls[i].markAsDirty();
      this.validateGroupForm.controls[i].updateValueAndValidity();
    }
    if (this.validateGroupForm.invalid) {
      this.btnLoading = false;
      return;
    }
    let groupIds = [];
    if (this.validateGroupForm.value.quickCombinationGroups) {
      groupIds = this.validateGroupForm.value.quickCombinationGroups.map(
        (item) => {
          return { id: item };
        }
      );
    }
    let data = {
      workAllocationQuickConfig: {
        hosId: this.currentHospital.id,
        id: this.coopId,
        groups: groupIds,
        ruleType: this.ruleTypeCoopId,
      },
    };
    this.mainService
      .coopTypeConfig("updData", "workAllocationQuickConfig", data)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideGroupsModal();
        this.initGroupsForm();
        if (data.status == 200) {
          this.showPromptModal("分配分组", true, "");
        } else {
          this.showPromptModal("分配分组", false, data.msg);
        }
      });
  }
  // 复制
  copyFlag = false;
  copy(e, data) {
    e.stopPropagation();
    console.log(data);
    this.add = false;
    this.copyFlag = true;
    this.coopId = data.id;
    this.info = data;
    this.ids = data.taskTypesId;
    this.currentClassId = data.classes.id;
    this.getClassList(true, true);
  }
  // 编辑
  info; //编辑时候保存的信息
  edit(e, data) {
    e.stopPropagation();
    console.log(data);
    this.add = false;
    this.coopId = data.id;
    this.info = data;
    this.validateForm.controls.quickCombinationName.setValue(data.configName); //快捷组合名称
    this.ids = data.taskTypesId;
    this.currentClassId = data.classes.id;
    this.getClassList(true, true);
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  // promptModalUrl = '';
  showPromptModal(con, success, promptInfo?, loading?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    if (loading !== undefined) {
      this.showLoading = loading;
    } else {
      this.showLoading = false;
      this.getList(0);
    }
    // this.promptModalUrl = url;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
  }
  // 选中表格中快捷建单
  isAllDisplayDataChecked = false; //当前页是否全选
  mapOfCheckedId = {};
  checkedDepIds = []; //已选中快捷建单id
  refreshStatus(): void {
    this.isAllDisplayDataChecked = this.listOfData.every(
      (item) => this.mapOfCheckedId[item.id]
    );
    let arr = [];
    for (var k in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[k]) {
        arr.push(Number(k));
      }
    }
    this.checkedDepIds = arr;
    console.log(this.checkedDepIds, this.isAllDisplayDataChecked);
  }
  // 整行选中或不选中
  selectedListData(id) {
    this.mapOfCheckedId[id] = !this.mapOfCheckedId[id];
    this.refreshStatus();
  }
  // 全选
  checkAll(value: boolean): void {
    this.listOfData.forEach((item) => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  // 删除轮巡计划
  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  confirmDelIsSwitch: boolean; //启用/停用
  showDelModal(
    e,
    id: any,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
    isSwitch?: boolean
  ) {
    e.stopPropagation();
    this.confirmDelIsSwitch = isSwitch;
    this.confirmDelType = type;
    this.delModal = true;
    this.coopId = id;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      let arrData = [];
      if (Array.isArray(this.coopId)) {
        arrData = this.coopId;
      } else {
        arrData = [this.coopId];
      }
      this.mainService
        .coopTypeConfig("rmvData", "workAllocationQuickConfig", arrData)
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            if (
              this.listOfData.length == 1 &&
              this.pageIndex == Math.ceil(this.listLength / this.pageSize)
            ) {
              this.listLength--;
              if (this.listLength === 0) {
                this.pageIndex = 1;
              } else {
                this.pageIndex = Math.ceil(this.listLength / this.pageSize);
              }
            }
            this.showPromptModal(this.tipsMsg2, true, "");
            this.isAllDisplayDataChecked = false;
            this.checkedDepIds = [];
            this.mapOfCheckedId = {};
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }
  // ----------返回拦截------------
  tipModal = false;
  // tipMsg1 = '是否确定离开该界面，如果未点击生效，数据可能会遗失？';
  // 隐藏模态框
  hideTipModal() {
    this.tipModal = false;
  }
  // 返回
  goToWorkAssignment() {
    this.tipModal = true;
  }
  // 模态框确认
  confirmTip() {
    this.tipModal = false;
    this.router.navigateByUrl(`/main/workAssignment`);
  }
}
