import { Component, OnInit, ViewChild } from "@angular/core";
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl,
} from "@angular/forms";
import { ActivatedRoute } from "@angular/router";
import { NzMessageService } from "ng-zorro-antd";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { MainService } from "src/app/services/main.service";
import { ToolService } from "src/app/services/tool.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";

@Component({
  selector: "app-hospital-config",
  templateUrl: "./hospital-config.component.html",
  styleUrls: ["./hospital-config.component.less"],
})
export class HospitalConfigComponent implements OnInit {
  saveLoading = false;
  isHosItsmIncident = false;
  hosId;
  validateForm: FormGroup;
  isLoading: boolean = false;
  searchLoading: boolean = false;
  hospitalConfigList = []; //院区系统配置列表
  roleList = []; //角色列表
  dispatchUserList = []; //派单列表
  taskTypeList = []; //任务类型列表
  allTaskTypeList = []; //任务类型列表
  deptList = []; //科室列表
  deptList2 = []; //科室列表
  groupList = []; //组列表
  onSearchSubject = new Subject(); //搜索防抖
  onSearchInspectionDepartmentScopeSubject = new Subject(); //搜索防抖
  onSearchNucleicAcidPrintingTaskTypeSubject = new Subject(); //搜索防抖
  coopBtns: any = {};
  repairSpecimenStatus = "0"; //是否执行标本验证机制
  repairSpecimenStatusMinute = 0; //验证时间
  repairSpecimenStatusCheckDeptIds = []; //验证检验科范围
  allowNucleicAcidPrinting = "0"; //是否允许核酸打印
  nucleicAcidPrintingTaskType = null; //核酸打印任务类型
  formatterDollar = (value) => Number(value);
  constructor(
    private mainService: MainService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private tool: ToolService,
    private message: NzMessageService
  ) {}
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  ngOnInit() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.onSearchSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getDeptList(this.hosId, v).then((result) => {
        this.searchLoading = false;
        if (result.status == 200) {
          this.deptList = result.list;
        }
      });
    });
    this.onSearchInspectionDepartmentScopeSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getDeptList2(this.hosId, v).then((result) => {
        this.searchLoading = false;
        if (result.status == 200) {
          this.deptList2 = result.list;
        }
      });
    });
    // liao
    this.onSearchNucleicAcidPrintingTaskTypeSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getTaskTypeList(undefined, v).then((result) => {
        this.searchLoading = false;
        if (result.status == 200) {
          this.allTaskTypeList = result.list;
        }
      });
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getInit();
  }
  // 根据科室id查科室
  getDeptById(id) {
    return this.mainService.getFetchData("data", "department", id);
  }
  // 选择是否执行标本验证机制
  changeRepairSpecimenStatus(e) {
    if (e == 1) {
      this.validateForm.addControl(
        "repairSpecimenStatusMinute",
        new FormControl(null, Validators.required)
      );
      this.validateForm.addControl(
        "repairSpecimenStatusCheckDeptIds",
        new FormControl(null, Validators.required)
      );
      //赋值
      this.hospitalConfigList.forEach((config) => {
        if (
          config.key === "repairSpecimenStatusMinute" ||
          config.key === "repairSpecimenStatusCheckDeptIds"
        ) {
          config.show = true;
        }
        if (config.key === "repairSpecimenStatusMinute") {
          this.validateForm.controls[config.key].setValue(Number(config.value));
        } else if (config.key === "repairSpecimenStatusCheckDeptIds") {
          this.validateForm.controls[config.key].setValue(
            config.value ? config.value.split(",").map(Number) : []
          );
        }
      });
    } else {
      this.validateForm.removeControl("repairSpecimenStatusMinute");
      this.validateForm.removeControl("repairSpecimenStatusCheckDeptIds");
      this.hospitalConfigList.forEach((v) => {
        if (
          v.key === "repairSpecimenStatusMinute" ||
          v.key === "repairSpecimenStatusCheckDeptIds"
        ) {
          v.show = false;
        }
      });
    }
  }
  // 选择是否允许核酸打印
  changeAllowNucleicAcidPrinting(e) {
    if (e == 1) {
      this.validateForm.addControl(
        "nucleicAcidPrintingTaskType",
        new FormControl(null, Validators.required)
      );
      //赋值
      this.hospitalConfigList.forEach((config) => {
        if (
          config.key === "nucleicAcidPrintingTaskType"
        ) {
          config.show = true;
        }
        if (config.key === "nucleicAcidPrintingTaskType") {
          this.validateForm.controls[config.key].setValue(
            config.value ? Number(config.value) : null
          );
        }
      });
    } else {
      this.validateForm.removeControl("nucleicAcidPrintingTaskType");
      this.hospitalConfigList.forEach((v) => {
        if (
          v.key === "nucleicAcidPrintingTaskType"
        ) {
          v.show = false;
        }
      });
    }
  }
  //初始化请求数据
  getInit() {
    this.isLoading = true;
    this.getDispatchUserList();
    Promise.all([
      this.getRoleList(),
      this.getDeptList(this.hosId),
      this.getGroupList(this.hosId),
      this.getTaskTypeList([255]),
      this.getClassesList(),
      this.getDeptList2(this.hosId),
      this.getTaskTypeList(),
      this.getSysConfig(),
    ])
      .then((result) => {
        if (result[0].status == 200) {
          this.roleList = result[0].list;
        }
        if (result[1].status == 200) {
          this.deptList = result[1].list;
        }
        if (result[2].status == 200) {
          this.groupList = result[2].list;
        }
        if (result[3].status == 200) {
          this.taskTypeList = result[3].list;
        }
        if (result[4].status == 200) {
          this.classesList = result[4].list;
          this.classesList = this.classesList.map((item) => ({
            label: item.name,
            value: item.id,
            checked: false,
          }));
        }
        if (result[5].status == 200) {
          this.deptList2 = result[5].list;
        }
        if (result[6].status == 200) {
          this.allTaskTypeList = result[6].list;
        }
        if (result[7].status == 200) {
          this.isHosItsmIncident = result[7].list.find(v => v.keyconfig == 'itsmIncident').valueconfig == 1;
        }

        this.getHospitalConfigList(this.hosId).subscribe((res) => {
          if (res.status == 200) {
            this.hospitalConfigList = res.list;
            //创建表单
            let fbGroup = {};
            this.hospitalConfigList.forEach((item) => {
              item.show = true;
              if (
                item.key === "repairSpecimenStatusMinute" ||
                item.key === "repairSpecimenStatusCheckDeptIds"
              ) {
                if (
                  this.hospitalConfigList.filter(
                    (v) => v.key === "repairSpecimenStatus"
                  )[0].value == 1
                ) {
                  item.show = true;
                } else {
                  item.show = false;
                }
              }
              if (
                item.key === "nucleicAcidPrintingTaskType"
              ) {
                if (
                  this.hospitalConfigList.filter(
                    (v) => v.key === "allowNucleicAcidPrinting"
                  )[0].value == 1
                ) {
                  item.show = true;
                } else {
                  item.show = false;
                }
              }
              if (item.key.includes("phone_num_port")) {
                //坐席号码
                fbGroup[item.key] = [null];
                item.required = false;
              } else if (item.key === "rushNoticeShift") {
                //抢单通知班次
                fbGroup[item.key] = [];
                item.required = false;
              } else {
                if (item.show) {
                  fbGroup[item.key] = [null, [Validators.required]];
                  item.required = true;
                }
              }
            });
            this.validateForm = this.fb.group(fbGroup);
            //赋值
            this.hospitalConfigList.forEach((config) => {
              if (config.show) {
                //默认角色,默认组
                if (
                  config.key === "autoCreateUserRoleId" ||
                  config.key === "rebackPatientTypeId" ||
                  config.key === "transDeptTypeId" ||
                  config.key === "autoCreateUserGroupId"
                ) {
                  this.validateForm.controls[config.key].setValue(
                    config.value - 0
                  );
                } else if (config.key === "autoCreateUserDeptId") {
                  //默认科室
                  let flag = this.deptList.some(
                    (item) => item.id == config.value
                  );
                  console.log(this.deptList);
                  if (!flag) {
                    this.getDeptById(config.value).subscribe((item) => {
                      this.isLoading = false;
                      if (item.status == 200) {
                        if (item.data.hospital.id == this.hosId) {
                          console.log(this.deptList);
                          this.deptList.unshift(item.data);
                        }
                      }
                    });
                  } else {
                    this.isLoading = false;
                  }
                  this.validateForm.controls[config.key].setValue(
                    config.value - 0
                  );
                } else if (config.key === "rushNoticeShift") {
                  let arr = config.value ? config.value.split(",") : [];
                  this.classesList.forEach((item) => {
                    item.checked = arr.includes(item.value + "");
                  });
                  this.validateForm.controls[config.key].setValue(
                    this.classesList
                  );
                } else if (config.key === "repairSpecimenStatusCheckDeptIds") {
                  let arr = config.value ? config.value.split(",").map(Number) : [];
                  arr.forEach(v => {
                    let flag = this.deptList2.some(
                      (item) => item.id == v
                    );
                    console.log(this.deptList2);
                    if (!flag) {
                      this.getDeptById(v).subscribe((item) => {
                        this.isLoading = false;
                        if (item.status == 200) {
                          if (item.data.hospital.id == this.hosId) {
                            this.deptList2.unshift(item.data);
                          }
                        }
                      });
                    } else {
                      this.isLoading = false;
                    }
                  })
                  this.validateForm.controls[config.key].setValue(arr);
                } else if (config.key === "nucleicAcidPrintingTaskType") {
                  this.validateForm.controls[config.key].setValue(parseInt(config.value));
                } else {
                  this.validateForm.controls[config.key].setValue(config.value);
                }
              }
            });
          } else {
            this.isLoading = false;
          }
        });
      })
      .catch((err) => {
        this.isLoading = false;
      });
  }
  // 获取当前院区的班次列表
  classesList = [];
  getClassesList() {
    let postData = {
      idx: 0,
      sum: 9999,
      scheduleClass: {
        hospital: { id: this.hosId },
      },
    };
    return this.mainService
      .getFetchDataList("configuration", "scheduleClass", postData)
      .toPromise();
  }
  // 获取系统配置列表
  getHospitalConfigList(hosId) {
    let postData = { idx: 0, sum: 100, hospitalConfig: { hosId, model: 'hsms' } };
    return this.mainService.getFetchDataList(
      "simple/data",
      "hospitalConfig",
      postData
    );
  }
  // 获取角色列表
  getRoleList() {
    let postData = { idx: 0, sum: 100 };
    return this.mainService
      .getFetchDataList("user/data", "role", postData)
      .toPromise();
  }
  // 获取派单列表
  getDispatchUserList() {
    this.mainService.getDictionary("list", "dispatchUserList").subscribe(result => {
      this.dispatchUserList = result || [];
    })
  }
  // 获取任务类型列表(患者其他服务)
  getTaskTypeList(associationTypeIds?,keyword?) {
    let postData: any = {
      idx: 0,
      sum: 999,
      taskType: {
        hosIds: this.hosId,
        taskName: keyword,
        simpleQuery: true,
      },
    };
    if (associationTypeIds) {
      postData.taskType.associationTypeIds = associationTypeIds.toString();
    }
    return this.mainService
      .getFetchDataList("configuration", "taskType", postData)
      .toPromise();
  }
  // 获取系统配置
  getSysConfig() {
    let postData: any = { idx: 0, sum: 99 };
    return this.mainService
      .getFetchDataList("simple/data", "systemConfiguration", postData)
      .toPromise();
  }
  /**
   * 获取科室列表
   * @param hosId 院区id
   * @param dept 模糊搜索
   * @returns
   */
  getDeptList(hosId, dept: any = "") {
    let postData = {
      idx: 0,
      sum: 10,
      department: {
        hospital: { id: hosId },
        dept,
      },
    };
    return this.mainService
      .getFetchDataList("data", "department", postData)
      .toPromise();
  }
  /**
   * 获取检验科室列表
   * @param hosId 院区id
   * @param dept 模糊搜索
   * @returns
   */
  getDeptList2(hosId, dept: any = "") {
    let postData = {
      idx: 0,
      sum: 10,
      department: {
        hospital: { id: hosId },
        dept,
        type: { id: "282" },
      },
    };
    return this.mainService
      .getFetchDataList("data", "department", postData)
      .toPromise();
  }
  /**
   * 获取组列表
   * @param hosId 院区id
   * @returns
   */
  getGroupList(hosId) {
    let postData = { idx: 0, sum: 100, group2: { hospitals: hosId, typeIds: '1,3' } };
    return this.mainService
      .getFetchDataList("data", "group2", postData)
      .toPromise();
  }
  //搜索
  onSearch(e) {
    this.searchLoading = true;
    this.onSearchSubject.next(e);
  }

  //验证检验科室范围
  onSearchInspectionDepartmentScope(e){
    this.searchLoading = true;
    this.onSearchInspectionDepartmentScopeSubject.next(e);
  }

  //核酸打印任务类型
  onSearchNucleicAcidPrintingTaskType(e){
    this.searchLoading = true;
    this.onSearchNucleicAcidPrintingTaskTypeSubject.next(e);
  }

  // 保存
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    let hospitalConfigList = JSON.parse(
      JSON.stringify(this.hospitalConfigList)
    );
    hospitalConfigList.forEach((config) => {
      if (config.show) {
        if (config.key === "rushNoticeShift") {
          config.value = this.validateForm.controls[config.key].value
            .filter((item) => item.checked)
            .map((item) => item.value)
            .toString();
        } else if (config.key === "repairSpecimenStatusCheckDeptIds") {
          config.value =
            this.validateForm.controls[config.key].value.toString();
        } else if (config.key === "nucleicAcidPrintingTaskType") {
          config.value =
            this.validateForm.controls[config.key].value.toString();
        } else {
          config.value = this.validateForm.controls[config.key].value;
        }
      } else {
        config.value = "";
      }
      delete config.required;
    });
    this.saveLoading = true;
    this.mainService.changeHospitalSysConfig(hospitalConfigList).subscribe(
      (result) => {
        this.saveLoading = false;
        if (result["status"] == 200) {
          this.message.create("success", "保存成功");
          this.getInit();
        } else {
          this.message.create("error", "保存失败");
        }
      },
      (error) => {
        this.saveLoading = false;
        this.message.create("error", "保存失败");
      }
    );
  }
}
