import { Component, OnInit, OnDestroy, ViewChild } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import {
  FormBuilder,
  Validators,
  FormGroup,
  FormControl,
} from "@angular/forms";
import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { NzMessageService } from "ng-zorro-antd";
import { forkJoin } from "rxjs";
import { ToolService } from "../../services/tool.service";
import { startOfDay, endOfDay, format, startOfMinute, addMinutes } from 'date-fns';
@Component({
  selector: "app-order-detail",
  templateUrl: "./order-detail.component.html",
  styleUrls: ["./order-detail.component.less"],
})
export class OrderDetailComponent implements OnInit {
  @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;
  @ViewChild("osComponentRef6", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef6: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef7", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef7: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef8", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef8: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef9", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef9: OverlayScrollbarsComponent;
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private mainService: MainService,
		private tool: ToolService,
  ) {}
  maskFlag: any = false;
  id: number; //工单id
  orderInfo: any; //工单详情信息
  endDepts = ""; //工单详情目标科室
  showCoop: boolean = true; //是否展示详情页操作按钮
	imgUrl:any = location.origin + '/file'; //图片路径前缀
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //是否展示提示框

  urgentLoading: boolean = false; //确认加急按钮loading状态
  recLoading: boolean = false; //撤回并删除按钮loading状态
  btnLoading: boolean = false; //确认按钮loading状态
  amplificationShow = true;
	hosId:any = this.tool.getCurrentHospital().id; //当前院区
	
  ngOnInit() {
    this.tabType = this.route.snapshot.params.type || 1;
		this.getInspectAndPatientTransportConfigTasktype()
    this.initForm();
  }
  ngOnDestroy() {}

  // 放大
  amplification(){
    this.amplificationShow = !this.amplificationShow;
  }
	
  //获取检查页面任务类型
  getInspectAndPatientTransportConfigTasktype() {
    let postData = {
      idx: 0,
      sum: 10,
      taskType: {
        simpleQuery: true,
        hosId: {
          id: this.hosId
        },
        associationType: {
          key:"association_types",
          value: 'inspect'
        }
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskType", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          let tasktype:any = result.list[0] || {};
          this.getInspectAndPatientTransportConfig(tasktype);
        }
      });
  }
  // 获取检查页面信息配置
	configObj:any;
  getInspectAndPatientTransportConfig(tasktype) {
    let postData = {
      idx: 0,
      sum: 10,
      taskTypeConfig: {
        taskTypeDTO: {
          hosId: {
            id: this.hosId
          },
          associationType: tasktype.associationType
        }
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskTypeConfig", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.configObj = result.list[0] || {};
					this.getInfo();
        }
      });
  }
	
  // 获取工单详情
  middleDept = []; //中间科室数组
  getInfo() {
    this.id = +this.route.snapshot.paramMap.get("id");
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .getFetchData("api", "workOrder", this.id)
      .subscribe((data) => {
				let obj = data.data
				if(obj.checkList){
					obj.checkList.forEach(i =>{
						i.newTime = format(new Date(i.yyTime), 'MM-dd HH:mm')
						if(i.endCheckTime){
							i.newTime2 = format(new Date(i.endCheckTime), 'HH:mm')
							i.yyEndTime = i.newTime + '--' + i.newTime2
						}else{
							i.yyEndTime = i.newTime
						}
					})
				}
        this.orderInfo = obj;
        if (data.data.middleDept) {
          this.middleDept = data.data.middleDept.map((item) => item.dept);
        } else {
          this.middleDept = [];
        }
        this.endDepts = data.data.endDepts.map((item) => item.dept).join();
        let log$ = this.getLog();
        let record$ = this.getWorkOrderRecord();
        forkJoin(log$, record$).subscribe((res) => {
          this.message.remove(this.maskFlag);
          this.maskFlag = false;
          // getLog
          this.logList = res[0]["data"];
          // getWorkOrderRecord
          if (res[1]["status"] == 200) {
            this.workOrderRecord = res[1]["data"];
          }
        });
      });
  }
  // 预览图片
  imgs = [];
  isPreview = false;
  previewImageHandler(data,index) {
		// this.imgs = data.map((v) => location.origin + '/file' + v.relativeFilePath)
		// console.log(9999,this.imgs)
		// this.isPreview = true;
    this.isPreview = false;
    this.mainService.getPreviewImage(data.bindType,data.bindId).subscribe((result:any)=>{
      if (result.status == 200) {
				this.imgs = [location.origin + '/file' + result.data[index].relativeFilePath]
				// console.log(898988,result)
        // this.imgs = result.data.map((v) => location.origin + '/file' + v.relativeFilePath);
        this.isPreview = true;
      } else {
        this.imgs = [];
      }
    })
  }
  // 获取历史记录
  workOrderRecord: any = [];
  getWorkOrderRecord() {
    return this.mainService.getWorkOrderRecord({ gdid: this.id });
  }
  // 切换tab栏
  tabType: number = 1; //tab栏
  checkTab(type) {
    this.tabType = type;
  }

  // 关闭弹框
  close() {
    history.go(-1);
  }

  // 查看业务数据
  businessDataModalShow = false; //业务数据弹窗开关
  businessDataModalType = ''; //业务数据类型
  orderId = ""; //查看业务数据携带
	taskTypeValue:any;
	orderHosId:any;
  viewDetail(data, type) {
		console.log(4444,data, type)
    this.orderId = data.id;
		this.orderHosId = data.hosId;
		this.taskTypeValue = data.taskType.associationType.value;
    this.businessDataModalType = type;
    this.businessDataModalShow = true;
  }
  // 关闭业务数据弹窗
  closeModelBlood(e) {
    this.businessDataModalShow = JSON.parse(e).show;
  }

  // 获取工单历史记录
  logList = []; //工单历史记录
  getLog() {
    return this.mainService.getWorkOrderLog(this.id);
  }

  // 初始化新增form表单
  validateForm: FormGroup; //新增/编辑表单
  initForm() {
    this.validateForm = this.fb.group({
      reason: [null, [Validators.required]],
      process: [null, [Validators.required]],
      handleType: [null, [Validators.required]],
      improve: [null, [Validators.required]],
    });
  }

  // 新增表单提交
  submitForm(): void {
    var that = this;
    for (const i in that.validateForm.controls) {
      that.validateForm.controls[i].markAsDirty();
      that.validateForm.controls[i].updateValueAndValidity();
    }
    if (that.validateForm.invalid) return;
    that.btnLoading = true;
    let postData = {
      badEvaluationHandle: {
        id: that.id,
        reasonAndEventProcess: that.validateForm.value.reason,
        mediationProcess: that.validateForm.value.process,
        handleType: { id: that.validateForm.value.handleType },
        advice: that.validateForm.value.improve,
        handleStatus: { key: "bad_evaluation_handle_status", value: "2" },
      },
    };

    that.mainService
      .postCustom("adviceCollection", "updData/badEvaluationHandle", postData)
      .subscribe((data) => {
        that.btnLoading = false;
        if (data.status == 200) {
          that.showPromptModal("调解", true, "");
          that.getInfo();
          // that.initForm();
        } else {
          that.showPromptModal("调解", false, data.msg);
        }
      });
  }

  // 展示信息提示框（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);
  }
}
