import { Component, OnInit, ViewChild, OnDestroy } from "@angular/core";
import { MainService } from "../../services/main.service";
import { Router } from "@angular/router";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { startOfDay, format, endOfDay } from "date-fns";
import { ToolService } from 'src/app/services/tool.service';

@Component({
  selector: "app-pharmacy2",
  templateUrl: "./pharmacy2.component.html",
  styleUrls: ["./pharmacy2.component.less"],
})
export class Pharmacy2Component implements OnInit, OnDestroy {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef3", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef3: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef4", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef4: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef5", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef5: OverlayScrollbarsComponent;
  constructor(private mainService: MainService, public router: Router, public tool: ToolService) {}
  // 今日药单量
  todayTotal: undefined;
  // 今日已完成
  todayComplete: undefined;
  //待配药数据
  codes = [];
  // 待配药
  printPharmacyList = []; //数据列表
  printPharmacyIdx = 0; //页码
  printPharmacyTotal = 0; //总数
  printPharmacyFlag = false; //是否查看更多
  printPharmacySearchKey = ""; //搜索的内容
  printPharmacyLoad = false; //按钮的loading
  // 配药中列表
  waitPharmacyList = [];
  waitPharmacyIdx = 0;
  waitPharmacyTotal = 0;
  waitPharmacyFlag = false;
  waitPharmacySearchKey = "";
  waitPharmacyLoad = false;
  // 核对中列表
  pharmacyList = [];
  pharmacyIdx = 0;
  pharmacyTotal = 0;
  pharmacyFlag = false;
  pharmacySearchKey = "";
  pharmacyLoad = false;
  // 配送中列表
  distributionList = [];
  distributionIdx = 0;
  distributionTotal = 0;
  distributionFlag = false;
  distributionSearchKey = "";
  distributionLoad = false;
  // 已完成列表
  completedList = [];
  completedIdx = 0;
  completedTotal = 0;
  completedFlag = false;
  completedSearchKey = "";
  completedLoad = false;

  // other
  loginUser: any = localStorage.getItem("user")
    ? JSON.parse(localStorage.getItem("user")).user
    : null; //登录人信息

  logTimer = null; //定时器
  logTime = 0; //自动刷新秒数
  logTimeConst = 60; //自动刷新秒数

  time = new Date().getTime(); // 时间戳
  timer = null; // 时间定时器

  ngOnDestroy() {
    clearTimeout(this.timer);
    clearTimeout(this.logTimer);
  }

  ngOnInit() {
    this.runTime();
    // 统计
    this.total();
    // 切换科室
    this.changeKs();
    // 待配药列表
    this.getPharmacyList(this.printPharmacyIdx, 1, this.printPharmacySearchKey);
    // 配药中列表
    this.getPharmacyList(this.waitPharmacyIdx, 2, this.waitPharmacySearchKey);
    // 核对中列表
    this.getPharmacyList(this.pharmacyIdx, 3, this.pharmacySearchKey);
    // 配送中列表
    this.getPharmacyList(this.distributionIdx, 4, this.distributionSearchKey);
    // 已完成列表
    this.getPharmacyList(this.completedIdx, 5, this.completedSearchKey);
    this.initRole();
    // 自动刷新倒计时 start
    this.autoUpdate();
    // 自动刷新倒计时 end
  }
  // 当前时间日期
  runTime() {
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.time = Date.now();
      this.runTime();
    }, 500);
  }
  // 统计
  total() {
    let launch = JSON.parse(localStorage.getItem("user")).user.dept.id;
    let startTime = format(startOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
    let endTime = format(endOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
    let postData = {
      startTime,
      endTime,
      launch,
    };

    this.mainService.getDrugsBagStateCount(postData).subscribe((res: any) => {
      if (res.status == 200) {
        this.todayTotal = res.countMap.todayTotal;
        this.todayComplete = res.countMap.todayComplete;
      }
    });
  }
  // 查看流程信息弹窗
  logPromptModalShow = false; //弹窗开关
  drugsBagId = ""; //查看记录携带drugsBagId
  showLogs(data) {
    clearInterval(this.logTimer);
    this.drugsBagId = data.id;
    this.logPromptModalShow = true;
  }
  // 关闭流程信息弹窗
  closeModelLog(e) {
    this.logPromptModalShow = JSON.parse(e).show;
    this.autoUpdate(false);
  }
  // 自动刷新倒计时
  autoUpdate(flag = true) {
    if (flag) {
      this.logTime = this.logTimeConst;
    }
    clearInterval(this.logTimer);
    this.logTimer = setInterval(() => {
      this.logTime--;
      if (this.logTime === 0) {
        this.logTime = this.logTimeConst;
        // 待配药列表
        this.getPharmacyList(0, 1, this.printPharmacySearchKey);
        // 配药中列表
        this.getPharmacyList(0, 2, this.waitPharmacySearchKey);
        // 核对中列表
        this.getPharmacyList(0, 3, this.pharmacySearchKey);
        // 配送中列表
        this.getPharmacyList(0, 4, this.distributionSearchKey);
        // 已完成列表
        this.getPharmacyList(0, 5, this.completedSearchKey);
      }
    }, 1000);
  }
  // 药房端药房列表查询、搜索
  // 1为pc待打印状态、2为pc配药中、3为pc核对中、4为pc配送中
  // searchKey  为搜索的关键字，没有就不传
  loading1 = false;
  loading2 = false;
  loading3 = false;
  loading4 = false;
  loading5 = false;
  getPharmacyList(idx, type, searchKey) {
    let launch = {
      id: JSON.parse(localStorage.getItem("user")).user.dept.id,
    };
    switch (type) {
      case 1:
        this.loading1 = true;
        break;
      case 2:
        this.loading2 = true;
        break;
      case 3:
        this.loading3 = true;
        break;
      case 4:
        this.loading4 = true;
        break;
      case 5:
        this.loading5 = true;
        break;
    }
    let postData = {
      idx,
      sum: 10,
      drugsBag: { searchState: type, searchKey, launch, platform: 3 },
    };
    this.mainService
      .getFetchDataList("api", "drugsBag", postData)
      .subscribe((result) => {
        switch (type) {
          case 1:
            this.loading1 = false;
            break;
          case 2:
            this.loading2 = false;
            break;
          case 3:
            this.loading3 = false;
            break;
          case 4:
            this.loading4 = false;
            break;
          case 5:
            this.loading5 = false;
            break;
        }
        if (result["status"] == 200) {
          switch (type) {
            case 1:
              // 总数
              this.printPharmacyTotal = result.totalNum;
              // 隐藏按钮的loading
              this.printPharmacyLoad = false;
              // 查看更多，是否显示
              if (result["list"].length < 10) {
                this.printPharmacyFlag = false;
              } else if (result["list"].length === 0 && idx === 0) {
                this.printPharmacyFlag = false;
              } else {
                this.printPharmacyFlag = true;
              }
              // 列表数据合并
              if (idx === 0) {
                this.printPharmacyList = result["list"];
              } else {
                this.printPharmacyList = [
                  ...this.printPharmacyList,
                  ...result["list"],
                ];
              }
              break;
            case 2:
              this.waitPharmacyTotal = result.totalNum;
              this.waitPharmacyLoad = false;
              if (result["list"].length < 10) {
                this.waitPharmacyFlag = false;
              } else if (result["list"].length === 0 && idx === 0) {
                this.waitPharmacyFlag = false;
              } else {
                this.waitPharmacyFlag = true;
              }
              if (idx === 0) {
                this.waitPharmacyList = result["list"];
              } else {
                this.waitPharmacyList = [
                  ...this.waitPharmacyList,
                  ...result["list"],
                ];
              }
              break;
            case 3:
              this.pharmacyTotal = result.totalNum;
              this.pharmacyLoad = false;
              if (result["list"].length < 10) {
                this.pharmacyFlag = false;
              } else if (result["list"].length === 0 && idx === 0) {
                this.pharmacyFlag = false;
              } else {
                this.pharmacyFlag = true;
              }
              if (idx === 0) {
                this.pharmacyList = result["list"];
              } else {
                this.pharmacyList = [...this.pharmacyList, ...result["list"]];
              }
              break;
            case 4:
              this.distributionTotal = result.totalNum;
              this.distributionLoad = false;
              if (result["list"].length < 10) {
                this.distributionFlag = false;
              } else if (result["list"].length === 0 && idx === 0) {
                this.distributionFlag = false;
              } else {
                this.distributionFlag = true;
              }
              if (idx === 0) {
                this.distributionList = result["list"];
              } else {
                this.distributionList = [
                  ...this.distributionList,
                  ...result["list"],
                ];
              }
              break;
            case 5:
              this.completedTotal = result.totalNum;
              this.completedLoad = false;
              if (result["list"].length < 10) {
                this.completedFlag = false;
              } else if (result["list"].length === 0 && idx === 0) {
                this.completedFlag = false;
              } else {
                this.completedFlag = true;
              }
              if (idx === 0) {
                this.completedList = result["list"];
              } else {
                this.completedList = [...this.completedList, ...result["list"]];
              }
              break;
          }
        }
      });
  }
  // 加载更多
  loadMore(type) {
    switch (type) {
      case 1:
        this.printPharmacyIdx++;
        this.printPharmacyLoad = true;
        this.getPharmacyList(
          this.printPharmacyIdx,
          type,
          this.printPharmacySearchKey
        );
        break;
      case 2:
        this.waitPharmacyIdx++;
        this.waitPharmacyLoad = true;
        this.getPharmacyList(
          this.waitPharmacyIdx,
          type,
          this.waitPharmacySearchKey
        );
        break;
      case 3:
        this.pharmacyIdx++;
        this.pharmacyLoad = true;
        this.getPharmacyList(this.pharmacyIdx, type, this.pharmacySearchKey);
        break;
      case 4:
        this.distributionIdx++;
        this.distributionLoad = true;
        this.getPharmacyList(
          this.distributionIdx,
          type,
          this.distributionSearchKey
        );
        break;
      case 5:
        this.completedIdx++;
        this.completedLoad = true;
        this.getPharmacyList(this.completedIdx, type, this.completedSearchKey);
        break;
    }
  }
  // 搜索关键词
  searchKeyHandle(type) {
    switch (type) {
      case 1:
        this.printPharmacyIdx = 0; //页码重置
        this.printPharmacyList = []; //列表重置
        this.getPharmacyList(
          this.printPharmacyIdx,
          type,
          this.printPharmacySearchKey
        );
        break;
      case 2:
        this.waitPharmacyIdx = 0; //页码重置
        this.waitPharmacyList = []; //列表重置
        this.getPharmacyList(
          this.waitPharmacyIdx,
          type,
          this.waitPharmacySearchKey
        );
        break;
      case 3:
        this.pharmacyIdx = 0; //页码重置
        this.pharmacyList = []; //列表重置
        this.getPharmacyList(this.pharmacyIdx, type, this.pharmacySearchKey);
        break;
      case 4:
        this.distributionIdx = 0; //页码重置
        this.distributionList = []; //列表重置
        this.getPharmacyList(
          this.distributionIdx,
          type,
          this.distributionSearchKey
        );
        break;
      case 5:
        this.completedIdx = 0; //页码重置
        this.completedList = []; //列表重置
        this.getPharmacyList(this.completedIdx, type, this.completedSearchKey);
        break;
    }
  }
  // 退出
  logOut(): void {
    // 假退出
    let hospital = this.tool.getCurrentHospital();
    if(hospital){
      this.router.navigate(["login", hospital.id]);
    }else{
      this.router.navigateByUrl("login");
    }
    localStorage.removeItem("user");
    localStorage.removeItem("menu");
    localStorage.removeItem("index");

    // 假退出
    this.mainService.logOut().subscribe((data) => {
      if (data.status == 200) {
        if(hospital){
          this.router.navigate(["login", hospital.id]);
        }else{
          this.router.navigateByUrl("login");
        }
        localStorage.removeItem("user");
        localStorage.removeItem("menu");
        localStorage.removeItem("index");
      }
    });

  }
  //待配药
  print(id?) {
    let arr = [];
    if (typeof id === "number" && id > 0) {
      //单个二维码
      arr.push(id);
    } else {
      //批量二维码
      arr = this.printPharmacyList.map((item) => item.id);
    }
    this.mainService.printRequisition(arr).subscribe((data) => {
      if (data["status"] == 200) {
        this.codes = data["data"];
        setTimeout(function () {
          const printContent = document.getElementById("report");
          const WindowPrt = window.open("", "", "width=700,height=900");
          WindowPrt.document.write(printContent.innerHTML);
          WindowPrt.print();
          WindowPrt.close();
        }, 100);
        // 待打印变为待配药接口
        let loginName = JSON.parse(localStorage.getItem("user")).user.name;
        this.mainService
          .changeToDispensing(arr, loginName)
          .subscribe((data) => {
            if (data["state"] == 200) {
              this.printPharmacyList = [];
              this.waitPharmacyList = [];
              // 待配药列表
              this.getPharmacyList(0, 1, this.printPharmacySearchKey);
              // 配药中列表
              this.getPharmacyList(0, 2, this.waitPharmacySearchKey);
            }
          });
      }
    });
  }

  //补打二维码
  replenishPrint(id?) {
    let arr = [];
    if (typeof id === "number" && id > 0) {
      //单个二维码
      arr.push(id);
    } else {
      //批量二维码
      arr = this.printPharmacyList.map((item) => item.id);
    }
    this.mainService.printRequisition(arr).subscribe((data) => {
      if (data["status"] == 200) {
        this.codes = data["data"];
        setTimeout(function () {
          const printContent = document.getElementById("report");
          const WindowPrt = window.open("", "", "width=700,height=900");
          WindowPrt.document.write(printContent.innerHTML);
          WindowPrt.print();
          WindowPrt.close();
        }, 100);
      }
    });
  }

  // 右侧菜单
  showLastItems: boolean = false;
  // 下拉
  fixedMenuXiala() {
    this.showLastItems = true;
  }

  // 上拉
  fixedMenuShangla() {
    this.showLastItems = false;
  }

  mainRole: boolean = false; //回到系统管理权限
  initRole() {
    // let roles = JSON.parse(localStorage.getItem('user')).user.role;
    let menus = JSON.parse(localStorage.getItem("menu"));
    let that = this;
    console.log("菜单数量" + menus.length);
    if (menus.length >= 2) {
      that.mainRole = true;
      return;
    }
  }

  // 切换右侧菜单Tab
  fixedTab: string = "";
  checkFixedTab(type: string) {
    if (type == "toSystem") {
      this.router.navigateByUrl("main");
    }
    if (this.fixedTab == type) {
      this.fixedTab = "";
    } else {
      this.fixedTab = type;
    }
  }
  //药房端科室切换
  changeShow = true;
  closeTime = 3;
  closeTimeFlag = 0;
  hsPromptModalShow: boolean = true; //科室切换提示框是否展示
  timerCloseTime = null;
  deptDisplay = 1; //护士端是否显示可以别名，1是显示科室名称，2是显示科室别名
  //子传父接收
  closeModelHs(e) {
    this.hsPromptModalShow = JSON.parse(e).show;
    this.changeShow = JSON.parse(e).changeShow;
  }
  //子传父接收
  clearModelHs(e) {
    if (JSON.parse(e).clear === true) {
      clearInterval(this.timerCloseTime);
    }
    this.changeShow = JSON.parse(e).changeShow;
  }
  // 头部切换科室
  changeKsNow() {
    this.hsPromptModalShow = true;
    clearInterval(this.timerCloseTime);
    this.changeShow = false;
  }
  // 切换科室
  changeKs() {
    this.hsPromptModalShow = true;
    // (1)	当用户设置为正数时，用户必须查看此窗体指定秒数。
    // (2)	当用户设置为负数时，用户可点击知道了也可倒计时自动关闭。
    // (3)	如果用户填写0则为无自动关闭和强制查看时间。
    if (this.closeTimeFlag === 0) {
      return;
    }
    this.closeTime = Math.abs(this.closeTimeFlag);
    clearInterval(this.timerCloseTime);
    this.timerCloseTime = setInterval(() => {
      this.closeTime = Math.max(--this.closeTime, 0);
      if (this.closeTime === 0) {
        if (this.closeTimeFlag <= 0) {
          this.hsPromptModalShow = false;
        }
        clearInterval(this.timerCloseTime);
      }
    }, 1000);
  }
}
