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-specimen-view2",
  templateUrl: "./specimen-view2.component.html",
  styleUrls: ["./specimen-view2.component.less"],
})
export class SpecimenView2Component 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;
  //待配药数据
  // 待配药
  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, 'delegation', this.printPharmacySearchKey);
    // 已收取（工单信息）列表
    this.getPharmacyList(this.waitPharmacyIdx, 'take', this.waitPharmacySearchKey);
    // 中转标本（标本统计信息）列表
    this.getPharmacyList(this.pharmacyIdx, 'trans', this.pharmacySearchKey);
    // 中转配送中（工单信息）列表
    this.getPharmacyList(this.distributionIdx, 'trans_send', this.distributionSearchKey);
    // 异常标本（标本信息）列表
    this.getPharmacyList(this.completedIdx, 'error', 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;
      }
    });
  }
  // 查看工单详情
  goToOrderDetail(item){
    console.log(item);
    this.router.navigateByUrl(`specimenView2/detailSample/${item.id}`);
  }
  // 查看流程信息弹窗
  logPromptModalShow = false; //弹窗开关
  scode = ""; //查看记录携带
  showLogs(data) {
    clearInterval(this.logTimer);
    this.scode = data.scode;
    this.logPromptModalShow = true;
  }
  // 关闭流程信息弹窗
  closeModelLog(e) {
    this.logPromptModalShow = JSON.parse(e).show;
    this.autoUpdate(false);
  }
  // 查看标本列表弹窗
  spePromptModalShow = false; //弹窗开关
  checkDeptId = ""; //检查科室id
  printDate = ""; //采集日期
  showSpeList(data) {
    clearInterval(this.logTimer);
    this.checkDeptId = data.check_dept_id;
    this.printDate = data.startTime;
    this.spePromptModalShow = true;
  }
  // 关闭标本列表弹窗
  closeModelSpe(e) {
    this.spePromptModalShow = JSON.parse(e).show;
    this.autoUpdate(false);
  }
   // 查看工单列表弹窗
   orderPromptModalShow = false; //弹窗开关
   workId = ""; //配送人员ID
   showOrderList(data) {
     clearInterval(this.logTimer);
     this.workId = data.workerid;
     this.orderPromptModalShow = true;
   }
   // 关闭工单列表弹窗
   closeModelOrder(e) {
     this.orderPromptModalShow = 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, 'delegation', this.printPharmacySearchKey);
        // 已收取（工单信息）列表
        this.getPharmacyList(0, 'take', this.waitPharmacySearchKey);
        // 中转标本（标本统计信息）列表
        this.getPharmacyList(0, 'trans', this.pharmacySearchKey);
        // 中转配送中（工单信息）列表
        this.getPharmacyList(0, 'trans_send', this.distributionSearchKey);
        // 异常标本（标本信息）列表
        this.getPharmacyList(0, 'error', 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 hosId = JSON.parse(localStorage.getItem("user")).user.currentHospital.id;
    switch (type) {
      case 'delegation':
        this.loading1 = true;
        break;
      case 'take':
        this.loading2 = true;
        break;
      case 'trans':
        this.loading3 = true;
        break;
      case 'trans_send':
        this.loading4 = true;
        break;
      case 'error':
        this.loading5 = true;
        break;
    }
    let postData = {
      viewType: type,
      keyWord: searchKey,
      hosId,
    };
    this.mainService
      .specimenView2(postData)
      .subscribe((result) => {
        switch (type) {
          case 'delegation':
            this.loading1 = false;
            break;
          case 'take':
            this.loading2 = false;
            break;
          case 'trans':
            this.loading3 = false;
            break;
          case 'trans_send':
            this.loading4 = false;
            break;
          case 'error':
            this.loading5 = false;
            break;
        }
        if (result["state"] == 200) {
          switch (type) {
            case 'delegation':
              // 总数
              this.printPharmacyTotal = result.totalNum;
              // 隐藏按钮的loading
              this.printPharmacyLoad = false;
              // 查看更多，是否显示
              if (result["data"].length < 10) {
                this.printPharmacyFlag = false;
              } else if (result["data"].length === 0 && idx === 0) {
                this.printPharmacyFlag = false;
              } else {
                this.printPharmacyFlag = true;
              }
              // 列表数据合并
              if (idx === 0) {
                this.printPharmacyList = result["data"];
              } else {
                this.printPharmacyList = [
                  ...this.printPharmacyList,
                  ...result["data"],
                ];
              }
              break;
            case 'take':
              this.waitPharmacyTotal = result.totalNum;
              this.waitPharmacyLoad = false;
              if (result["data"].length < 10) {
                this.waitPharmacyFlag = false;
              } else if (result["data"].length === 0 && idx === 0) {
                this.waitPharmacyFlag = false;
              } else {
                this.waitPharmacyFlag = true;
              }
              if (idx === 0) {
                this.waitPharmacyList = result["data"];
              } else {
                this.waitPharmacyList = [
                  ...this.waitPharmacyList,
                  ...result["data"],
                ];
              }
              break;
            case 'trans':
              this.pharmacyTotal = result.totalNum;
              this.pharmacyLoad = false;
              if (result["data"].length < 10) {
                this.pharmacyFlag = false;
              } else if (result["data"].length === 0 && idx === 0) {
                this.pharmacyFlag = false;
              } else {
                this.pharmacyFlag = true;
              }
              if (idx === 0) {
                this.pharmacyList = result["data"];
              } else {
                this.pharmacyList = [...this.pharmacyList, ...result["data"]];
              }
              break;
            case 'trans_send':
              this.distributionTotal = result.totalNum;
              this.distributionLoad = false;
              if (result["data"].length < 10) {
                this.distributionFlag = false;
              } else if (result["data"].length === 0 && idx === 0) {
                this.distributionFlag = false;
              } else {
                this.distributionFlag = true;
              }
              // 处理数据
              result["data"].forEach(v=>{
                v.deptList = v.deptList?v.deptList.join('，'):'';
              })
              if (idx === 0) {
                this.distributionList = result["data"];
              } else {
                this.distributionList = [
                  ...this.distributionList,
                  ...result["data"],
                ];
              }
              break;
            case 'error':
              this.completedTotal = result.totalNum;
              this.completedLoad = false;
              if (result["data"].length < 10) {
                this.completedFlag = false;
              } else if (result["data"].length === 0 && idx === 0) {
                this.completedFlag = false;
              } else {
                this.completedFlag = true;
              }
              if (idx === 0) {
                this.completedList = result["data"];
              } else {
                this.completedList = [...this.completedList, ...result["data"]];
              }
              break;
          }
        }
      });
  }
  // 加载更多
  loadMore(type) {
    switch (type) {
      case 'delegation':
        this.printPharmacyIdx++;
        this.printPharmacyLoad = true;
        this.getPharmacyList(
          this.printPharmacyIdx,
          type,
          this.printPharmacySearchKey
        );
        break;
      case 'take':
        this.waitPharmacyIdx++;
        this.waitPharmacyLoad = true;
        this.getPharmacyList(
          this.waitPharmacyIdx,
          type,
          this.waitPharmacySearchKey
        );
        break;
      case 'trans':
        this.pharmacyIdx++;
        this.pharmacyLoad = true;
        this.getPharmacyList(this.pharmacyIdx, type, this.pharmacySearchKey);
        break;
      case 'trans_send':
        this.distributionIdx++;
        this.distributionLoad = true;
        this.getPharmacyList(
          this.distributionIdx,
          type,
          this.distributionSearchKey
        );
        break;
      case 'error':
        this.completedIdx++;
        this.completedLoad = true;
        this.getPharmacyList(this.completedIdx, type, this.completedSearchKey);
        break;
    }
  }
  // 搜索关键词
  searchKeyHandle(type) {
    switch (type) {
      case 'delegation':
        this.printPharmacyIdx = 0; //页码重置
        this.printPharmacyList = []; //列表重置
        this.getPharmacyList(
          this.printPharmacyIdx,
          type,
          this.printPharmacySearchKey
        );
        break;
      case 'take':
        this.waitPharmacyIdx = 0; //页码重置
        this.waitPharmacyList = []; //列表重置
        this.getPharmacyList(
          this.waitPharmacyIdx,
          type,
          this.waitPharmacySearchKey
        );
        break;
      case 'trans':
        this.pharmacyIdx = 0; //页码重置
        this.pharmacyList = []; //列表重置
        this.getPharmacyList(this.pharmacyIdx, type, this.pharmacySearchKey);
        break;
      case 'trans_send':
        this.distributionIdx = 0; //页码重置
        this.distributionList = []; //列表重置
        this.getPharmacyList(
          this.distributionIdx,
          type,
          this.distributionSearchKey
        );
        break;
      case 'error':
        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");
      }
    });

  }

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

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

  mainRole: boolean = false; //回到系统管理权限
  initRole() {
    let menus = JSON.parse(localStorage.getItem("menu"));
    console.log("菜单数量" + menus.length);
    if (menus.length >= 2) {
      this.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);
  }
}

