import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";

import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { NzMessageService } from "ng-zorro-antd";

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

  listOfData: any[] = []; //表格数据

  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  hosId: any; //院区（搜索）
  storageUnits: Array<any> = []; //所有储存单位
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

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

  btnLoading: boolean = false; //提交按钮loading状态

  ngOnInit() {
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.getStorageUnit();
    this.getUnit();
  }

  // 初始化增删改按钮
  coopBtns: any = {};
  // 表格数据
  loading1 = false;
  getList() {
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      clinicalWasteType: {
        hosId: this.hosId,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "clinicalWasteType", data)
      .subscribe((data) => {
        this.loading1 = false;
        this.listOfData = data.list;
        this.listLength = data.totalNum;
      });
  }

  // 获取所有储存单位
  getStorageUnit() {
    this.mainService.getDictionary("list", "storage_unit").subscribe((data) => {
      this.storageUnits = data;
      this.getAllHospital();
    });
  }

  // 获取相应的院区
  getAllHospital() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList();
  }

  // 获取生成方案
  units: Array<any> = [];
  getUnit() {
    var that = this;
    that.mainService.getDictionary("list", "unit").subscribe((data) => {
      that.units = data;
    });
  }

  // 新增弹框
  showModal() {
    this.add = true;
    this.initForm();
    this.modal = true;
  }
  hideModal() {
    this.modal = false;
    this.initForm();
  }

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      typeName: [null, [Validators.required]],
      inventoryDays: [0, [Validators.required]],
      unitPrice: [0, [Validators.required]],
      unit: [null, [Validators.required]],
      storageUnit: [null, [Validators.required]],
    });
  }
  // 表单提交
  submitForm(): void {
    var that = this;
    for (const i in that.validateForm.controls) {
      that.validateForm.controls[i].markAsDirty({ onlySelf: true });
      that.validateForm.controls[i].updateValueAndValidity();
    }
    if (that.validateForm.invalid) return;
    that.btnLoading = true;
    let data:any = {
      typeName: that.validateForm.value.typeName,
      inventoryDays: that.validateForm.value.inventoryDays,
      unitPrice: that.validateForm.value.unitPrice || undefined,
      unit: that.validateForm.value.unit ? { id: that.validateForm.value.unit } : undefined,
      storageUnit: that.validateForm.value.storageUnit ? { id: that.validateForm.value.storageUnit } : undefined,
      hosId: that.hosId,
    };
    if (!that.add) {
      data = {...this.coopData, ...data};
    }
    that.mainService
      .simplePost("addData", "clinicalWasteType", data)
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideModal();
        that.initForm();
        if (data.status == 200) {
          that.showPromptModal(that.add ? "新增" : "编辑", true, "");
        } else {
          that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
        }
      });
  }

  // 编辑
  maskFlag: any = false;
  coopData:any = {};
  edit(data) {
    this.modal = true;
    this.add = false;
    this.coopId = data.id;
    this.coopData = data;
    this.validateForm.controls.typeName.setValue(data.typeName);
    this.validateForm.controls.inventoryDays.setValue(data.inventoryDays);
    this.validateForm.controls.unitPrice.setValue(data.unitPrice);
    this.validateForm.controls.unit.setValue(data.unit.id);
    this.validateForm.controls.storageUnit.setValue(data.storageUnit.id);
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    this.coopId = data.id;
    this.delModal = true;
  }
  // 确认删除
  confirmDel() {
    let that = this;
    that.btnLoading = true;
    that.mainService
      .simplePost("rmvData", "clinicalWasteType", [that.coopId])
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideDelModal();
        if (data["status"] == 200) {
          if (
            that.listOfData.length == 1 &&
            that.pageIndex == Math.ceil(that.listLength / that.pageSize)
          ) {
            that.listLength--;
            that.pageIndex = Math.ceil(that.listLength / that.pageSize) || 1;
          }
          that.showPromptModal("删除", true, "");
        } else {
          that.showPromptModal("删除", false, data["msg"]);
        }
      });
  }
  // 关闭删除模态框
  hideDelModal() {
    this.delModal = false;
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
    this.getList();
  }

  isLoading = false;
}
