import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";
import { MainService } from "../../services/main.service";
import { forkJoin } from "rxjs";
import { NzMessageService } from "ng-zorro-antd";

@Component({
  selector: "app-appraise-detail",
  templateUrl: "./appraise-detail.component.html",
  styleUrls: ["./appraise-detail.component.less"],
})
export class AppraiseDetailComponent implements OnInit {
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private mainService: MainService
  ) {}

  id: number; //工单id
  orderInfo:any = {}; //工单详情信息
  showCoop: boolean = true; //是否展示详情页操作按钮
  loginUser: any = localStorage.getItem("user")
    ? JSON.parse(localStorage.getItem("user")).user
    : null; //登录人信息

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

  urgentLoading: boolean = false; //确认加急按钮loading状态
  recLoading: boolean = false; //撤回并删除按钮loading状态
  btnLoading: boolean = false; //确认按钮loading状态
	allShow: boolean = true; //先全部隐藏
  ngOnInit() {
    this.getInfo();
    this.initForm();
  }

  // 获取工单详情
  maskFlag: any = false;
  getInfo() {
    this.id = +this.route.snapshot.paramMap.get("id");
    if (this.route.snapshot.fragment == "tj") {
      this.checkTab(3);
    }
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .getFetchData("adviceCollection", "badEvaluationHandle", this.id)
      .subscribe((data) => {
        this.orderInfo = data.data;
        let log$ = this.getLog();
        let allHandleType$ = this.getAllHandleType();
        forkJoin(log$, allHandleType$).subscribe((res) => {
          this.message.remove(this.maskFlag);
          this.maskFlag = false;
          // getLog
          this.logList = res[0]["data"];
          // getAllHandleType
          this.allHandleType = res[1];
        });
      });
  }
  // 切换tab栏
  tabType: number = 1; //tab栏
  checkTab(type) {
    this.tabType = type;
  }

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

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

  // 获取所有院区
  allHandleType: any = [];
  getAllHandleType() {
    return this.mainService.getDictionary("list", "bad_evaluation_handle_type",true);
  }

  // 初始化新增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 date = new Date();
    // let time = date.getFullYear() + '-' + ((((date.getMonth() + 1) < 10) ? ('0' + (date.getMonth() + 1)) : (date.getMonth() + 1))) + '-' + ((((date.getDate()) < 10) ? ('0' + (date.getDate())) : (date.getDate())));
    // time = time + ' ' + (date.getHours() < 10 ? ('0' + date.getHours()) : date.getHours()) + ':' + (date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes()) + ':' + (date.getSeconds() < 10 ? ('0' + date.getSeconds()) : date.getSeconds());
    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" },
        mediationUser: { id: that.loginUser.id },
        mediationTime: date,
      },
    };

    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);
  }

  // 格式化时间戳
  date(time) {
    let date = new Date(time);
    let timeStr =
      date.getFullYear() +
      "-" +
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) +
      "-" +
      (date.getDate() < 10 ? "0" + date.getDate() : date.getDate());
    timeStr =
      timeStr +
      " " +
      (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) +
      ":" +
      (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
      ":" +
      (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
    return timeStr;
  }
}
