import { Component, OnInit, ViewChild } from "@angular/core";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { MainService } from "src/app/services/main.service";
import { ToolService } from "src/app/services/tool.service";
import { format } from 'date-fns';
import { ActivatedRoute } from '@angular/router';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';

@Component({
  selector: "app-medical-waste-storage-record",
  templateUrl: "./medical-waste-storage-record.component.html",
  styleUrls: ["./medical-waste-storage-record.component.less"],
})
export class MedicalWasteStorageRecordComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private mainService: MainService,
    private tool: ToolService,
    private route: ActivatedRoute,
    private fb: FormBuilder,
  ) {}

  searchCriteria = {
    //搜索条件
    name: "",
    dateRange: [],
  };
  hosId;
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量

  // 初始化增删改按钮
  coopBtns: any = {};
  ngOnInit() {
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getHospital();
  }

  onCalendarChangeDate(dateArr){
    console.log(dateArr)
    if(dateArr.length == 2){
      let dateStart = new Date(dateArr[0]);
      let dateEnd = new Date(dateArr[1]);
      dateStart.setHours(0,0,0);
      dateEnd.setHours(23,59,59);
      this.searchCriteria.dateRange = [dateStart,dateEnd];
    }
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del() {
    this.content = `原重量为<strong class="red">${this.coopData.weight}kg</strong>，矫正后重量为<strong class="red">${this.validateForm.value.weight}kg</strong>，您确认修改吗？`;
    this.delModal = true;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;

    let coopData = {...this.coopData, ...{weight: this.validateForm.value.weight}};
    this.mainService.simplePost("addData", "clinicalWaste", coopData)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideModal();
        this.hideDelModal();
        if (data.status == 200) {
          this.showPromptModal("修改", true, "");
        } else {
          this.showPromptModal("修改", false, data.msg);
        }
      });
  }

  // 关闭删除模态框
  hideDelModal() {
    this.delModal = false;
  }
  // 修改重量弹框
  modal: boolean = false;
  coopData:any = {};
  content:string = '';
  showModal(data) {
    this.coopData = data;
    this.modal = true;
    this.initForm();
  }
  hideModal() {
    this.modal = false;
    this.initForm();
  }
  // 初始化form表单
  validateForm: FormGroup; //编辑表单
  initForm() {
    this.validateForm = this.fb.group({
      weight: [0, [Validators.required]],
    });
  }
  // 表单提交
  btnLoading:boolean = false;
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty({ onlySelf: true });
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.del();
  }
  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
    this.getList(1);
  }
  // 重置
  reset() {
    this.searchCriteria = {
      //搜索条件
      name: "",
      dateRange: [],
    };
    this.getList(1);
  }

  // 获取所有院区
  getHospital() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList(1);
  }
  // 查看弹窗
  historyPromptModalShow = false; //标本历史记录弹窗开关
  id = ""; //查看
  viewHistory(data) {
    this.id = data.id;
    this.historyPromptModalShow = true;
  }
  // 关闭弹窗
  closeModelHistory(e) {
    this.historyPromptModalShow = JSON.parse(e).show;
  }

  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let postData: any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      clinicalWasteInto: {
        hosId: this.hosId,
      },
    };
    if (this.searchCriteria.dateRange.length) {
      postData.clinicalWasteInto.startTime =
        format(this.searchCriteria.dateRange[0], "yyyy-MM-dd HH:mm:ss");
      postData.clinicalWasteInto.endTime =
        format(this.searchCriteria.dateRange[1], "yyyy-MM-dd HH:mm:ss");
    }
    if (this.searchCriteria.name) {
      postData.clinicalWasteInto.name = this.searchCriteria.name;
    }
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "clinicalWasteInto", postData)
      .subscribe((data) => {
        this.loading1 = false;
        if (data["status"] == 200) {
          this.listOfData = data["list"];
          this.listLength = data["totalNum"];
        }
      });
  }
}

