import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { NzMessageService } from "ng-zorro-antd/message";

import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";

@Component({
  selector: "app-inspect-auto",
  templateUrl: "./inspect-auto.component.html",
  styleUrls: ["./inspect-auto.component.less"],
})
export class InspectAutoComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private mainService: MainService,
    private msg: NzMessageService,
    private tool: ToolService
  ) {}
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;
  ngOnInit() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getInspectAutoList();
    this.getInspectType();
    this.getLevelOfCare();
    this.getStateOfAnIllness();
  }
  checkedInspectAuto: any = {}; //选中班次
  inspectAutoList: Array<any> = []; //检查自动建单的班次信息
  hosId: any; //当前选择的院区id

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

  saveLoading: boolean = false; //批量打印按钮loading状态

  // 初始化增删改按钮
  coopBtns: any = {};
  // 取消选中状态
  cancelStatus(arr: any[]) {
    arr.forEach((item) => (item.checked = false));
    return arr;
  }
  // 选择急查或者普查
  changeInspect(flag, type) {
    if (!flag) {
      if (type === "urgencyInspect") {
        //急查
        this.inspectTypeList_u = this.cancelStatus(this.inspectTypeList_u);
        this.levelOfCareList_u = this.cancelStatus(this.levelOfCareList_u);
        this.stateOfAnIllnessList_u = this.cancelStatus(
          this.stateOfAnIllnessList_u
        );
        this.inspectType_u = false;
        this.levelOfCare_u = false;
        this.stateOfAnIllness_u = false;
      } else if (type === "ordinaryInspect") {
        //普查
        this.inspectTypeList_o = this.cancelStatus(this.inspectTypeList_o);
        this.levelOfCareList_o = this.cancelStatus(this.levelOfCareList_o);
        this.stateOfAnIllnessList_o = this.cancelStatus(
          this.stateOfAnIllnessList_o
        );
        this.inspectType_o = false;
        this.levelOfCare_o = false;
        this.stateOfAnIllness_o = false;
      }
    }
  }
  /**
   *
   * @param classId 班次Id
   */
  loading2 = true;
  getRules() {
    let postData = {
      idx: 0,
      sum: 9999,
      autoCreateOrderRule: {
        hosId: this.hosId,
        classesId: this.checkedInspectAuto.id, //班次id
        taskTypeId: this.taskTypeId, //任务类型id
        deleted: false,
      },
    };
    this.loading2 = true;
    this.mainService
      .getFetchDataList("simple/data", "autoCreateOrderRule", postData)
      .subscribe((result) => {
        this.loading2 = false;
        if (result.status == 200) {
          result.list.forEach((item) => {
            if (item.extra1 === "1") {
              //急查
              this.urgencyInspectNo = Boolean(item.autoDispatch);
              this.urgencyInspect = true;
              this.inspectType_u = this.inspectTypeList_u.some((v) => {
                if (v.id == item.typeId) {
                  v.checked = true;
                }
                return v.id == item.typeId;
              });
              this.levelOfCare_u = this.levelOfCareList_u.some((v) => {
                if (v.id == item.typeId2) {
                  v.checked = true;
                }
                return v.id == item.typeId2;
              });
              this.stateOfAnIllness_u = this.stateOfAnIllnessList_u.some(
                (v) => {
                  if (v.id == item.typeId3) {
                    v.checked = true;
                  }
                  return v.id == item.typeId3;
                }
              );
            }
            if (item.extra1 === "0") {
              //普查
              this.ordinaryInspectNo = Boolean(item.autoDispatch);
              this.ordinaryInspect = true;
              this.inspectType_o = this.inspectTypeList_o.some((v) => {
                if (v.id == item.typeId) {
                  v.checked = true;
                }
                return v.id == item.typeId;
              });
              this.levelOfCare_o = this.levelOfCareList_o.some((v) => {
                if (v.id == item.typeId2) {
                  v.checked = true;
                }
                return v.id == item.typeId2;
              });
              this.stateOfAnIllness_o = this.stateOfAnIllnessList_o.some(
                (v) => {
                  if (v.id == item.typeId3) {
                    v.checked = true;
                  }
                  return v.id == item.typeId3;
                }
              );
            }
          });
        }
      });
  }

  // 任务类型下班次列表
  loading1 = false;
  taskTypeId; //当前选中班次的任务类型ID
  taskTypeName; //当前选中班次的任务类型名称
  getInspectAutoList() {
    let data = {
      idx: 0,
      sum: 1,
      taskType: {
        hosIds: this.hosId,
        associationType: { id: 260 },
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("configuration", "taskType", data)
      .subscribe((data1) => {
        this.loading1 = false;
        if (data1.list.length) {
          this.inspectAutoList = data1.list[0].classesIds; //班次信息
          this.taskTypeId = data1.list[0].id;
          this.taskTypeName = data1.list[0].taskName;
          if (Object.keys(this.checkedInspectAuto).length) {
            this.inspectAutoList.forEach((item) => {
              if (item.id == this.checkedInspectAuto.id) {
                this.checkInspectAuto(item);
              }
            });
          } else {
            this.checkInspectAuto(this.inspectAutoList[0]);
          }
        } else {
          this.msg.warning("请配置患者配件业务的任务类型！");
        }
      });
  }
  // 检查类型列表
  inspectTypeList_u = []; //检查类型列表(急查)
  inspectTypeList_o = []; //检查类型列表(普查)
  getInspectType() {
    this.mainService
      .getDictionary("list", "inspect_check_type")
      .subscribe((result) => {
        this.inspectTypeList_u = JSON.parse(JSON.stringify(result));
        this.inspectTypeList_o = JSON.parse(JSON.stringify(result));
      });
  }
  // 护理等级列表
  levelOfCareList_u = []; //班次列表(急查)
  levelOfCareList_o = []; //班次列表(普查)
  getLevelOfCare() {
    this.mainService
      .getDictionary("list", "levelOfCare")
      .subscribe((result) => {
        this.levelOfCareList_u = JSON.parse(JSON.stringify(result));
        this.levelOfCareList_o = JSON.parse(JSON.stringify(result));
      });
  }
  // 病情级别列表
  stateOfAnIllnessList_u = []; //病情级别列表(急查)
  stateOfAnIllnessList_o = []; //病情级别列表(普查)
  getStateOfAnIllness() {
    this.mainService
      .getDictionary("list", "stateOfAnIllness")
      .subscribe((result) => {
        this.stateOfAnIllnessList_u = JSON.parse(JSON.stringify(result));
        this.stateOfAnIllnessList_o = JSON.parse(JSON.stringify(result));
      });
  }
  //选择检查类型
  inspectType_u = false; //是否选择检查类型（急查）
  inspectType_o = false; //是否选择检查类型（普查）
  selectInspectType(ids, type) {
    switch (type) {
      case "urgencyInspect": //急查
        this.inspectType_u = ids.length > 0;
        if (this.inspectType_u) {
          this.inspectTypeList_u = this.cancelStatus(this.inspectTypeList_u);
          ids.forEach((item) => {
            this.inspectTypeList_u.forEach((v) => {
              if (v.id == item) {
                v.checked = true;
              }
            });
          });
        } else {
          this.levelOfCareList_u = this.cancelStatus(this.levelOfCareList_u);
          this.stateOfAnIllnessList_u = this.cancelStatus(
            this.stateOfAnIllnessList_u
          );
          this.inspectType_u = false;
          this.levelOfCare_u = false;
          this.stateOfAnIllness_u = false;
        }
        break;
      case "ordinaryInspect": //普查
        this.inspectType_o = ids.length > 0;
        if (this.inspectType_o) {
          this.inspectTypeList_o = this.cancelStatus(this.inspectTypeList_o);
          ids.forEach((item) => {
            this.inspectTypeList_o.forEach((v) => {
              if (v.id == item) {
                v.checked = true;
              }
            });
          });
        } else {
          this.levelOfCareList_o = this.cancelStatus(this.levelOfCareList_o);
          this.stateOfAnIllnessList_o = this.cancelStatus(
            this.stateOfAnIllnessList_o
          );
          this.inspectType_o = false;
          this.levelOfCare_o = false;
          this.stateOfAnIllness_o = false;
        }
        break;
    }
  }
  //选择护理等级
  levelOfCare_u = false; //是否选择护理等级（急查）
  levelOfCare_o = false; //是否选择护理等级（普查）
  selectLevelOfCare(ids, type) {
    switch (type) {
      case "urgencyInspect": //急查
        this.levelOfCareList_u.forEach((item) => {
          item.checked = false;
        });
        ids.forEach((item) => {
          this.levelOfCareList_u.forEach((v) => {
            if (v.id == item) {
              v.checked = true;
            }
          });
        });
        this.levelOfCare_u = ids.length > 0;
        break;
      case "ordinaryInspect": //普查
        this.levelOfCareList_o.forEach((item) => {
          item.checked = false;
        });
        ids.forEach((item) => {
          this.levelOfCareList_o.forEach((v) => {
            if (v.id == item) {
              v.checked = true;
            }
          });
        });
        this.levelOfCare_o = ids.length > 0;
        break;
    }
  }
  //选择病情级别
  stateOfAnIllness_u = false; //是否选择病情级别（急查）
  stateOfAnIllness_o = false; //是否选择病情级别（普查）
  selectStateOfAnIllness(ids, type) {
    switch (type) {
      case "urgencyInspect": //急查
        this.stateOfAnIllnessList_u.forEach((item) => {
          item.checked = false;
        });
        ids.forEach((item) => {
          this.stateOfAnIllnessList_u.forEach((v) => {
            if (v.id == item) {
              v.checked = true;
            }
          });
        });
        this.stateOfAnIllness_u = ids.length > 0;
        break;
      case "ordinaryInspect": //普查
        this.stateOfAnIllnessList_o.forEach((item) => {
          item.checked = false;
        });
        ids.forEach((item) => {
          this.stateOfAnIllnessList_o.forEach((v) => {
            if (v.id == item) {
              v.checked = true;
            }
          });
        });
        this.stateOfAnIllness_o = ids.length > 0;
        break;
    }
  }
  // 选中班次
  checkInspectAuto(data) {
    this.checkedInspectAuto = data ? data : {};
    this.urgencyInspect = false;
    this.ordinaryInspect = false;
    this.changeInspect(false, "urgencyInspect");
    this.changeInspect(false, "ordinaryInspect");
    this.getRules();
  }
  // 保存
  urgencyInspect = false; //是否选择急查
  urgencyInspectNo = false; //不进行自动派单-急查,1是勾选，0是不勾选
  ordinaryInspect = false; //是否选择普查
  ordinaryInspectNo = false; //不进行自动派单-急查,1是勾选，0是不勾选
  save() {
    // 规则验证 start
    //没有选择急查或普查
    // if (!this.urgencyInspect && !this.ordinaryInspect) {
    //   this.msg.info("没有选择急查或普查，无法保存！");
    //   return;
    // }
    // 选择了急查，没有选择普查
    if (this.urgencyInspect && !this.ordinaryInspect) {
      if (!this.inspectType_u) {
        //没有选择检查类型
        this.msg.info("没有选择急查里的检查类型，无法保存！");
        return;
      } else {
        // 选择了检查类型，没有选择护理等级
        if (!this.levelOfCare_u) {
          this.msg.info("没有选择急查里的护理等级，无法保存！");
          return;
        }
        // 选择了检查类型，没有选择病情级别
        if (!this.stateOfAnIllness_u) {
          this.msg.info("没有选择急查里的病情级别，无法保存！");
          return;
        }
      }
    }
    // 选择了普查，没有选择急查
    if (!this.urgencyInspect && this.ordinaryInspect) {
      if (!this.inspectType_o) {
        //没有选择检查类型
        this.msg.info("没有选择普查里的检查类型，无法保存！");
        return;
      } else {
        // 选择了检查类型，没有选择护理等级
        if (!this.levelOfCare_o) {
          this.msg.info("没有选择普查里的护理等级，无法保存！");
          return;
        }
        // 选择了检查类型，没有选择病情级别
        if (!this.stateOfAnIllness_o) {
          this.msg.info("没有选择普查里的病情级别，无法保存！");
          return;
        }
      }
    }
    // 选择了急查和普查
    if (this.urgencyInspect && this.ordinaryInspect) {
      if (this.urgencyInspect) {
        //选择了急查,没有选择检查类型
        if (!this.inspectType_u) {
          this.msg.info("没有选择急查里的检查类型，无法保存！");
          return;
        } else {
          // 选择了检查类型，没有选择护理等级
          if (!this.levelOfCare_u) {
            this.msg.info("没有选择急查里的护理等级，无法保存！");
            return;
          }
          // 选择了检查类型，没有选择病情级别
          if (!this.stateOfAnIllness_u) {
            this.msg.info("没有选择急查里的病情级别，无法保存！");
            return;
          }
        }
      }
      if (this.ordinaryInspect) {
        //选择了普查,没有选择检查类型
        if (!this.inspectType_o) {
          this.msg.info("没有选择普查里的检查类型，无法保存！");
          return;
        } else {
          // 选择了检查类型，没有选择护理等级
          if (!this.levelOfCare_o) {
            this.msg.info("没有选择普查里的护理等级，无法保存！");
            return;
          }
          // 选择了检查类型，没有选择病情级别
          if (!this.stateOfAnIllness_o) {
            this.msg.info("没有选择普查里的病情级别，无法保存！");
            return;
          }
        }
      }
    }
    // 规则验证 end
    let postData = [];
    // 组装数据 start
    if (!this.urgencyInspect && !this.ordinaryInspect) {
      postData = [
        {
          hosId: this.hosId,
          taskTypeId: this.taskTypeId,
          classesId: this.checkedInspectAuto.id,
          deleted: true,
        },
      ];
    } else {
      // 急查数据
      if (this.urgencyInspect) {
        let inspectTypeList_u = this.inspectTypeList_u
          .filter((item) => item.checked)
          .map((item) => item.id);
        let levelOfCareList_u = this.levelOfCareList_u
          .filter((item) => item.checked)
          .map((item) => item.id);
        let stateOfAnIllnessList_u = this.stateOfAnIllnessList_u
          .filter((item) => item.checked)
          .map((item) => item.id);
        // 三层循环，感觉有些傻，无奈后端非要这么传-后端陈肖让我记录的
        inspectTypeList_u.forEach((item) => {
          levelOfCareList_u.forEach((value) => {
            stateOfAnIllnessList_u.forEach((v) => {
              postData.push({
                classesId: this.checkedInspectAuto.id, //班次id
                taskTypeId: this.taskTypeId, //任务类型id
                extra1: 1, //急查1，普查0
                typeId: item, //检查类型id
                typeId2: value, //护理等级id
                typeId3: v, //病情级别id
                hosId: this.hosId, //院区id
                deleted: false, //删除true，显示false
                autoDispatch: Number(this.urgencyInspectNo), //不进行自动派单是true
              });
            });
          });
        });
      }
      // 普查数据
      if (this.ordinaryInspect) {
        let inspectTypeList_o = this.inspectTypeList_o
          .filter((item) => item.checked)
          .map((item) => item.id);
        let levelOfCareList_o = this.levelOfCareList_o
          .filter((item) => item.checked)
          .map((item) => item.id);
        let stateOfAnIllnessList_o = this.stateOfAnIllnessList_o
          .filter((item) => item.checked)
          .map((item) => item.id);
        // 三层循环，感觉有些傻，无奈后端非要这么传-后端陈肖让我记录的
        inspectTypeList_o.forEach((item) => {
          levelOfCareList_o.forEach((value) => {
            stateOfAnIllnessList_o.forEach((v) => {
              postData.push({
                classesId: this.checkedInspectAuto.id, //班次id
                taskTypeId: this.taskTypeId, //任务类型id
                extra1: 0, //急查1，普查0
                typeId: item, //检查类型id
                typeId2: value, //护理等级id
                typeId3: v, //病情级别id
                hosId: this.hosId, //院区id
                deleted: false, //删除true，显示false
                autoDispatch: Number(this.ordinaryInspectNo), //不进行自动派单是1
              });
            });
          });
        });
      }
    }
    // 组装数据 end
    this.saveLoading = true;
    this.mainService
      .simplePost("addListData", "autoCreateOrderRule", postData)
      .subscribe(
        (data) => {
          this.saveLoading = false;
          if (data.status == 200) {
            this.showPromptModal("保存", true, "");
          } else {
            this.showPromptModal("保存", false, data.msg);
          }
        },
        (err) => {
          this.saveLoading = false;
          this.showPromptModal("保存", false, "");
        }
      );
  }
  // 展示信息提示框（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.getInspectAutoList();
      this.getRules();
    }, 100);
  }
}
