import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { MainService } from "../../services/main.service";
import { forkJoin } from "rxjs";
import { NzMessageService } from "ng-zorro-antd";
import { ToolService } from "src/app/services/tool.service";
import { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';

@Component({
  selector: "app-detail-ordinary",
  templateUrl: "./detail-ordinary.component.html",
  styleUrls: ["./detail-ordinary.component.less"],
})
export class DetailOrdinaryComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private message: NzMessageService,
    private route: ActivatedRoute,
    private router: Router,
    private tool: ToolService,
    private mainService: MainService
  ) {}

  id: number; //工单id
  orderInfo: any; //工单详情信息
  endDepts = ""; //工单详情目标科室
  showCoop: boolean = true; //是否展示详情页操作按钮

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

  urgentLoading: boolean = false; //确认加急按钮loading状态
  recLoading: boolean = false; //撤回并删除按钮loading状态
  btnLoading: boolean = false; //确认按钮loading状态
  maskFlag: any = false;
  deptDisplay; //护士端是否显示可以别名，1是显示科室名称，2是显示科室别名
  amplificationShow = true;
  ngOnInit() {
    this.tool.getDeptDisplay().subscribe((result) => {
      if (result.status == 200) {
        this.deptDisplay = result.list[0].valueconfig;
      }
    });
    if (this.route.snapshot.parent.parent.routeConfig.path == "nurse") {
      this.showCoop = false;
    }
    this.id = +this.route.snapshot.paramMap.get("id");
    let log$ = this.getLog();
    let detail$ = this.getDetail();
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    forkJoin(log$, detail$).subscribe((res) => {
      this.message.remove(this.maskFlag);
      this.maskFlag = false;
      // getLog
      this.logList = res[0]["data"];
      // getDetail
      this.orderInfo = res[1]["data"];
      this.endDepts = res[1]["data"].endDepts
        .map((item) =>
          !this.showCoop && this.deptDisplay == 2 ? item.deptalias : item.dept
        )
        .join();
    });
  }

  // 查看业务数据
  bloodModalShow = false; //业务数据弹窗开关
  orderId = ""; //查看业务数据携带
  businessDataModalType = ''; //业务数据类型
	orderHosId:any; //创建工单院区id
  viewDetail(data, type) {
    this.orderId = data.id;
		this.orderHosId = data.hosId;
    this.businessDataModalType = type;
    this.bloodModalShow = true;
  }
  // 关闭业务数据弹窗
  closeModelBlood(e) {
    this.bloodModalShow = JSON.parse(e).show;
  }

  // 放大
  amplification(){
    this.amplificationShow = !this.amplificationShow;
  }

  // 获取工单详情
  getDetail() {
    return this.mainService.getFetchData("api", "workOrder", this.id);
  }

  // 确认加急
  urgent() {
    let that = this;
    that.urgentLoading = true;
    let postData = {
      urgentDetails: {
        workerOrder: this.orderInfo["id"],
        checkStatus: {
          id: 330,
        },
        urgentReason: this.orderInfo["urgentDetails"].urgentReason,
        id: this.orderInfo["urgentDetails"].id,
      },
    };
    that.mainService.coopWorkerOrder("urge", postData).subscribe((data) => {
      that.urgentLoading = false;
      if (data.status == 200) {
        that.showPromptModal("加急", true, "");
      } else {
        that.showPromptModal("加急", false, data.msg);
      }
    });
  }
  // 获取工单历史记录
  logList = []; //工单历史记录
  getLog() {
    return this.mainService.getWorkOrderLog(this.id);
  }

  // 派单
  allotWorker() {
    this.router.navigateByUrl(
      "dispatchingDesk/allotWorker/" +
        this.id +
        "/" +
        this.orderInfo["gdState"]["id"]
    );
  }

  // 撤回
  recallOrderShow: boolean = false;
  openRecallModal(): void {
    this.recallOrderShow = true;
  }
  // 确认撤回
  confirmRec() {
    let that = this;
    that.btnLoading = true;
    let postData = {
      workOrder: {
        id: that.id,
      },
    };
    that.mainService
      .coopWorkerOrder("excuteWorkOrder/recall", postData)
      .subscribe((data) => {
        that.btnLoading = false;
        that.closeRecallOrderModal();
        if (data.status == 200) {
          that.showPromptModal("撤回", true, "");
        } else {
          that.showPromptModal("撤回", false, data.msg);
        }
      });
  }
  // 撤回并删除
  recAndDel() {
    let that = this;
    that.recLoading = true;
    that.mainService.delOrder(that.id).subscribe((data) => {
      console.log(data);
      that.recLoading = false;
      that.closeDelOrderModal();
      if (data.status == 200) {
        that.showPromptModal("删除", true, "");
      } else {
        that.showPromptModal("删除", false, data.msg);
      }
    });
  }
  // 关闭撤回弹框
  closeRecallOrderModal() {
    this.recallOrderShow = false;
  }

  // 关闭弹框
  close() {
    // this.router.navigateByUrl('dispatchingDesk');
    history.go(-1);
  }

  // 删除
  // 打开模态框
  delOrderShow: boolean = false;
  openDelModal() {
    this.delOrderShow = true;
  }
  // 确认删除
  confirmDel() {
    let that = this;
    that.btnLoading = true;
    that.mainService.delOrder(that.id).subscribe((data) => {
      that.btnLoading = false;
      that.closeDelOrderModal();
      if (data.status == 200) {
        that.showPromptModal("删除", true, "");
      } else {
        that.showPromptModal("删除", false, data.msg);
      }
    });
  }

  // 关闭模态框
  closeDelOrderModal() {
    this.delOrderShow = 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;
    }, 100);
  }

  // 格式化时分秒
  // （时间小于一分钟则显示秒，时间大于一分钟则显示分钟数，如超出一小时则显示小时和分钟。）time单位:秒
  formatTime(time) {
    let timeStr = "";
    if (time >= 0 && time < 60) {
      // 秒
      timeStr = time + "秒";
    } else if (time >= 60 && time < 3600) {
      // 分钟
      timeStr = Math.floor(time / 60) + "分钟";
    } else if (time >= 3600) {
      // 时 + 分
      let h = "";
      let m = "";
      h = Math.floor(time / 3600) + "小时";
      m = time % 3600 >= 60 ? Math.floor((time % 3600) / 60) + "分钟" : "";
      timeStr = h + m;
    }
    return timeStr;
  }

  // 计算历史记录耗时
  filterTime(step) {
    // step = [{ difTime: 2 }, { difTime: 6 }]
    let num = 0;
    step.forEach((e) => {
      num += e.difTime;
    });
    return this.formatTime(num / 1000);
  }
}

