import { Component, OnInit, ViewChild } from "@angular/core";
import { MainService } from "src/app/services/main.service";
import { ToolService } from "src/app/services/tool.service";
import { Router } from '@angular/router';
import { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';
import { NzMessageService } from 'ng-zorro-antd';
import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';

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

  hosId;
  submitData:any = {
    totalBox: 0,
    totalBucket: 0,
    transportCompany: null,
    receptionCompany: null,
    driver: null,
    carNo: null,
    credentialsNumber: '',
  }

  clinicalWasteTypeSubject = new Subject<string>();

  ngOnInit() {
    this.clinicalWasteTypeSubject
      .pipe(debounceTime(300),distinctUntilChanged())
      .subscribe(clinicalWasteTypeIds => {
				this.changeClinicalWasteTypeList(clinicalWasteTypeIds);
      });
    this.hosId = this.tool.getCurrentHospital().id;
    this.getClinicalWasteTypeList();
    this.getCompanyTransType();
  }

  //删除
  loading3 = false;
  delModal: boolean = false; //删除模态框
  showDelModal() {
    this.delModal = true;
  }
  hideDelModal() {
    this.delModal = false;
  }
  confirmDel() {
    this.delModal = false;
    let maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let postData: any = {
      clinicalWasteTypeIds: this.clinicalWasteTypeIds,
      wasteOutInfo:{
        credentialsNumber: this.submitData.credentialsNumber,
        totalBox: this.submitData.totalBox,
        totalBucket: this.submitData.totalBucket,
        transportCompany: {id: this.submitData.transportCompany},
        receptionCompany: {id: this.submitData.receptionCompany},
        hosId: this.hosId,
        driver: {id: this.submitData.driver},
        carNo: this.carNoList.find(v => v.id == this.submitData.carNo).name,
      }
    };
    this.mainService
      .medicalWasteComplete(postData)
      .subscribe((res) => {
        this.message.remove(maskFlag);
        if (res.status == 200) {
          this.message.success("出库成功");
          this.router.navigateByUrl("/main/outgoingRecord");
        }
      });
  }

  submitForm(){
    if(!this.clinicalWasteTypeList.filter(v => v.checked).length){
      this.message.error("请选择医废类型");
      return;
    }
    if(!this.submitData.transportCompany){
      this.message.error("请选择运输单位");
      return;
    }
    if(!this.submitData.driver){
      this.message.error("请选择运输司机");
      return;
    }
    if(!this.submitData.carNo){
      this.message.error("请选择车牌号码");
      return;
    }
    if(!this.submitData.receptionCompany){
      this.message.error("请选择接收单位");
      return;
    }
    if(!this.totalCount){
      this.message.error("选择的类型，无医废数据请确认后发起出库");
      return;
    }
    this.showDelModal();

  }

  cancel(){
    this.router.navigateByUrl("/main/outgoingRecord");
  }

  // 医废类型
  clinicalWasteTypeList:any[] = [];
  getClinicalWasteTypeList() {
    let maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let postData: any = {
      idx: 0,
      sum: 9999,
      clinicalWasteType: {
        hosId: this.hosId,
      },
    };
    this.mainService
      .getFetchDataList("simple/data", "clinicalWasteType", postData)
      .subscribe((res) => {
        this.message.remove(maskFlag);
        if (res.status == 200) {
          let clinicalWasteTypeList = res.list || [];
          this.clinicalWasteTypeList = clinicalWasteTypeList.map(v => ({
            label: v.typeName,
            value: v.id,
            checked: false,
          }))
        }
      });
  }
  // 单位类型
  getCompanyTransType(){
    this.mainService.getDictionary("list", "company_trans_type")
      .subscribe((result) => {
        let company_trans_types = result || [];
        let transCompany = company_trans_types.find(v => v.value == 1);//运输单位
        let receiveCompany = company_trans_types.find(v => v.value == 2);//接收单位
        transCompany && this.getCompany(transCompany);
        receiveCompany && this.getCompany(receiveCompany);
      });
  }
  // 运输单位/接收单位
  transCompanyList:any[] = [];
  receiveCompanyList:any[] = [];
  laborerList:any[] = [];
  carNoList:any[] = [];
  getCompany(dictionary) {
    let postData: any = {
      idx: 0,
      sum: 9999,
      company: {
        hosId: this.hosId,
        transType: dictionary,
        busiType: { key: 'company_busi_type', value: '1' },
      },
    };
    this.mainService
      .getFetchDataList("simple/data", "company", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          if(dictionary.value == 1){
            // 运输单位
            this.transCompanyList = result.list || [];
          } else if(dictionary.value == 2){
            // 接收单位
            this.receiveCompanyList = result.list || [];
          }
        }
      });
  }

  businessCode1 = '';
  changeTransportCompany(id){
    let transCompany = this.transCompanyList.find(v => v.id == id);
    this.laborerList = transCompany.laborers || [];
    this.submitData.driver = null;
    this.carNoList = transCompany.carNo ? transCompany.carNo.split(',').map((v, index) => ({id: index + 1, name: v})) : [];
    this.submitData.carNo = null;
    this.businessCode1 = transCompany.businessCode;
  }

  driverPhone = '';
  changeDriver(id){
    let driver = this.laborerList.find(v => v.id == id);
    this.driverPhone = driver.mphone;
  }

  businessCode2 = '';
  mphone2 = '';
  contacts2 = '';
  changeReceiveCompany(id){
    let receiveCompany = this.receiveCompanyList.find(v => v.id == id);
    this.businessCode2 = receiveCompany.businessCode;
    this.mphone2 = receiveCompany.mphone;
    this.contacts2 = receiveCompany.contacts;
  }

  clinicalWasteTypeIds = '';
  changeClinicalWasteTypeListClick(clinicalWasteTypeList) {
    this.clinicalWasteTypeIds = clinicalWasteTypeList.filter(v => v.checked).map(v => v.value).toString();
    this.clinicalWasteTypeSubject.next(this.clinicalWasteTypeIds);
  }

  // 选择医废类型
  storageUnits:any[] = [];
  totalCount = 0;
  totalWeight = 0;
  changeClinicalWasteTypeList(clinicalWasteTypeIds){
    let maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let postData: any = {
      clinicalWasteTypeIds,
      hosId: this.hosId,
    };
    this.mainService
      .getWeightAndCount(postData)
      .subscribe((res) => {
        this.message.remove(maskFlag);
        if (res.status == 200) {
          this.storageUnits = res.storageUnits || [];
          this.totalCount = res.totalCount;
          this.totalWeight = res.totalWeight;
        }
      });
  }
}

