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";
import { debounceTime } from 'rxjs/operators';
import { Subject } from 'rxjs';

@Component({
  selector: "app-recycling-restriction",
  templateUrl: "./recycling-restriction.component.html",
  styleUrls: ["./recycling-restriction.component.less"],
})
export class RecyclingRestrictionComponent 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; //院区（搜索）
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

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

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

  changeInpSubject = new Subject(); //防抖

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[0] == 'clinicalWasteType'){
        this.getClinicalWasteTypes(v[1]);
      }else if(v[0] == 'deptIds'){
        this.getDeptIds(v[1]);
      }
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.getAllHospital();
    this.getClinicalWasteTypes();
    this.getDeptIds();
  }

  // 初始化增删改按钮
  coopBtns: any = {};
  // 表格数据
  loading1 = false;
  getList() {
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      clinicalWasteLimit: {
        hosId: this.hosId,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "clinicalWasteLimit", data)
      .subscribe((data) => {
        this.loading1 = false;
        let listOfData = data.list || [];
        listOfData.forEach((item) => {
          item.deptNames = item.depts.map(v => v.dept).toString();
        })
        this.listOfData = listOfData;
        this.listLength = data.totalNum;
      });
  }

  // 获取所有医废类型
  clinicalWasteTypes: Array<any> = [];
  getClinicalWasteTypes(keyword = "") {
    this.mainService.getFetchDataList("simple/data", "clinicalWasteType", {idx: 0, sum: 9999, clinicalWasteType: { hosId: this.hosId, typeName: keyword }}).subscribe((data) => {
      this.isLoading = false;
      this.clinicalWasteTypes = data.list || [];
    });
  }

  // 获取所有医废类型
  deptIdsList: Array<any> = [];
  getDeptIds(keyword = "") {
    this.mainService.getFetchDataList("data", "department", {idx: 0, sum: 9999, department: { cascadeHosId: this.hosId, dept: keyword, searchType: 1 }}).subscribe((data) => {
      this.isLoading = false;
      this.deptIdsList = data.list || [];
    });
  }

  // 边输边搜节流阀
  isLoading = false;
  changeInp(type, e) {
    this.isLoading = true;
    this.changeInpSubject.next([type, e]);
  }

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

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

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      clinicalWasteType: [null, [Validators.required]],
      deptIds: [[], [Validators.required]],
      minWeight: [0, [Validators.required]],
      maxWeight: [0, [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;
    if(that.validateForm.value.minWeight > that.validateForm.value.maxWeight){
      this.message.info('最小重量不能大于最大重量');
      return;
    }
    that.btnLoading = true;
    let data:any = {
      clinicalWasteType: {id: that.validateForm.value.clinicalWasteType},
      deptIds: that.validateForm.value.deptIds.toString(),
      minWeight: that.validateForm.value.minWeight,
      maxWeight: that.validateForm.value.maxWeight,
      hosId: that.hosId,
    };
    if (!that.add) {
      data = {...this.coopData, ...data};
    }
    console.log(data);
    that.mainService
      .simplePost("addData", "clinicalWasteLimit", 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.clinicalWasteType.setValue(data.clinicalWasteType ? data.clinicalWasteType.id : null);
    this.validateForm.controls.deptIds.setValue(data.depts.map(v => v.id));
    this.validateForm.controls.minWeight.setValue(data.minWeight);
    this.validateForm.controls.maxWeight.setValue(data.maxWeight);
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    this.coopId = data.id;
    this.delModal = true;
  }
  // 确认删除
  confirmDel() {
    let that = this;
    that.btnLoading = true;
    that.mainService
      .simplePost("rmvData", "clinicalWasteLimit", [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();
  }
}
