import { Component, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { ToolService } from 'src/app/services/tool.service';
import { MainService } from 'src/app/services/main.service';
import { NzMessageService } from 'ng-zorro-antd';
import { Location } from '@angular/common';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-batch-specimen',
  templateUrl: './batch-specimen.component.html',
  styleUrls: ['./batch-specimen.component.less']
})
export class BatchSpecimenComponent implements OnInit, AfterViewInit {
  @ViewChild('printBtn', { static: false }) printBtn: ElementRef<HTMLElement>;
  @ViewChild('specimenCodeElement', { static: false}) specimenCodeElementRef: ElementRef;

  constructor(
    private mainService: MainService,
    private tool: ToolService,
    private message: NzMessageService,
    private _location: Location,
    public router: Router,
    private route: ActivatedRoute,
  ) { }

  hosId:any = this.tool.getCurrentHospital().id; //当前院区
  deptDTO:any = this.tool.getCurrentUserDept(); //当前科室
  deptDisplay; //护士端是否显示可以别名，1是显示科室名称，2是显示科室别名
  listOfData: any[] = []; //表格数据

  searchTimerSubject = new Subject(); //防抖

  ngOnInit() {
    //防抖
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1]);
    });

    this.tool.getDeptDisplay().subscribe((result) => {
      if (result.status == 200) {
        this.deptDisplay = result.list[0].valueconfig;
      }
    });

    this.init();
  }

  ngAfterViewInit() {
    this.specimenCodeElementRef.nativeElement.focus();
  }

  init(){
    this.getConfig();
  }

  // 获取配置
  configs:any = {};
  getConfig() {
		let postData = {
      idx: 0,
      sum: 10,
      taskTypeConfig: {
        taskTypeDTO: {
          hosId: {
            id: this.hosId
          },
          ordinaryField: {
            key:"ordinary_field",
            value: 'specimenPackage'
          }
        }
      }
    };

    this.mainService
      .getFetchDataList("simple/data", "taskTypeConfig", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.configs = result.list[0] || {};
          this.querySaveSpePackage(true);
        }
      });
  }

  // 获取患者、试管类型列表、标本总数
  total:any;
  typeSpecimentList:any[] = [];
  patientSpecimentList:any[] = [];
  package:any = {};
  querySaveSpePackage(isInit = false){
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;

    let postData:any = {
      deptId: this.deptDTO.id,
    };

    if(this.route.snapshot.queryParams.id){
      postData.packageId = +this.route.snapshot.queryParams.id;
    }

    this.mainService
      .querySaveSpePackage(postData)
      .subscribe((result:any) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        if (result.state == 200) {
          this.total = result.totalCount;
          this.typeSpecimentList = result.tube || [];
          this.patientSpecimentList = result.patient || [];
          this.package = result.package || {};
          if(isInit){
            this.showDelModal({}, '您确认要重置标本吗，重置会先清空标本在根据规则自动清点？','重置标本','reset');
          }else{
            this.getList();
          }
        }
      })
  }

	// 批量移除
	infoContent:any;
	batchDel(){
		if(this.checkedDepIds.length==0){
			this.message.error('请勾选标本列表')
			return
		}
		this.confirmDelType = 'batchDel';
		this.tipsMsg1 = `您确认要移除${this.checkedDepIds.length}项标本吗？`
		this.delModal = true;
	}

	// 选中表格中科室
	mapOfCheckedId: { [key: string]: boolean } = {};
	checkedDepIds = []; //已选中科室id
	refreshStatus(): void {
	  this.isAllDisplayDataChecked = this.listOfData.every(
	    (item) => this.mapOfCheckedId[item.id]
	  );
	  let arr = [];
	  for (var k in this.mapOfCheckedId) {
	    if (this.mapOfCheckedId[k]) {
	      arr.push(Number(k));
	    }
	  }
	  this.checkedDepIds = arr;
	  console.log(this.checkedDepIds);
	}

	//表格整行选中
	selectedListData(id) {
	  this.mapOfCheckedId[id] = !this.mapOfCheckedId[id];
	  this.refreshStatus();
	}

	// 全选
	isAllDisplayDataChecked = false; //当前页是否全选
	checkAll(value: boolean): void {
	  this.listOfData.forEach((item) => (this.mapOfCheckedId[item.id] = value));
	  this.refreshStatus();
	}

  inspectActiveList: any = [];//选中检查列表
  patientActiveList: any = [];//选中患者列表

  coopData: any = {}; //当前操作列
  btnLoading: boolean = false; //提交按钮loading状态

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  showDelModal(
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    this.confirmDelType = type;
    this.delModal = true;
    this.coopData = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
    this.isShowEndDeptId = false;
  }
  // 确认删除
  confirmDel(e) {
    console.log(e)
    this.btnLoading = true;
    if (this.confirmDelType === "del" || this.confirmDelType ==='batchDel') {
      //删除-移除标本
      let postData = {
        speIds: this.confirmDelType === "del" ? this.coopData.id.toString() : this.checkedDepIds.toString(),
        packageId: this.package.id,
      }

      this.mainService
        .removePackageSpe(postData)
        .subscribe((data:any) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.state == 200) {
            this.showPromptModal('移除', true, "");
          } else {
            this.showPromptModal('移除', false, data.msg);
          }
        });
    }else if (this.confirmDelType === "reset") {
      //先重置再自动清点
      let postData = {
        packageId: this.package.id,
      }

      this.mainService
        .resetPackageSpe(postData)
        .subscribe((data:any) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.state == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }else if (this.confirmDelType === "package") {
      //打包
      let postData = {
        type: 'specimenPackage',
        id: this.package.id,
        endDeptId: e.endDeptId,
      }

      this.mainService
        .createOrTakeOrderSpecimen(postData)
        .subscribe((data:any) => {
          this.btnLoading = false;
          this.delModal = false;
          this.isShowEndDeptId = false;
          if (data.state == 200) {
            this.printPackage();
          } else {
            this.message.error(data.msg || "操作失败");
          }
        });
    }
		if(this.listOfData.length){
			this.listOfData.forEach(item => (this.mapOfCheckedId[item.id] = false));
			this.refreshStatus();
		}
  }

  // 打印
  base64:string = '';
  printPackage(){
    this.mainService
      .makeQrCode({}, this.package.packCode)
      .subscribe((data:any) => {
        if (data.state == 200) {
          this.total = data.totalCount;
          this.typeSpecimentList = data.tube || [];
          this.patientSpecimentList = data.patient || [];
          this.package = data.package || {};

          this.base64 = data.base64 || '';

          this.message.success("操作成功");
          setTimeout(()=>{
            this.printBtn.nativeElement.click();
            this.goBack();
          },0)
        } else {
          this.message.error(data.msg || "操作失败");
        }
      });
  }

  // 打包
  isShowEndDeptId:boolean = false;
  packageHandler(){
    this.isShowEndDeptId = true;
    this.getSpePackageEndDeptList();
  }

  // 查询标本包里的所有终点科室
  isShowEndDeptIdArr:any[] = [];
  getSpePackageEndDeptList(){
    this.mainService
      .getSpePackageEndDeptList({packageId: this.package.id})
      .subscribe((data:any) => {
        if (data.state == 200) {
          this.isShowEndDeptIdArr = data.data;

          this.showDelModal({}, `你确认要打包${this.total}只标本吗？`,'打包','package')
        } else {
          this.message.error(data.msg || "操作失败");
        }
      });
  }

  // 展示信息提示框（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.querySaveSpePackage();
  }

  loading1:boolean = false;

  getList(){
    let data = {
      idx: 0,
      sum: 99999,
      specimen: {
        packageId: this.package ? this.package.id : undefined,
        patientNo: this.activePatientNo || undefined,
        tubeType: this.activeTypeId ? { id: this.activeTypeId } : undefined,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "specimen", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
					// if(this.confirmDelType ==='batchDel'){
					// 	this.listOfData.forEach(item => (this.mapOfCheckedId[item.id] = false));
					// 	setTimeout(_=>{
					// 		this.refreshStatus();
					// 	})
					// }
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 返回
  goBack(){
    this._location.back();
  }

  // 选择试管类型
  activeTypeId:any;
  clickType(item){
    if(this.activeTypeId == item.id){
      this.activeTypeId = undefined;
    }else{
      this.activeTypeId = item.id;
    }

    this.querySaveSpePackage();
  }

  // 选择患者
  activePatientNo:any;
  clickPatient(item){
    if(this.activePatientNo == item.no){
      this.activePatientNo = undefined;
    }else{
      this.activePatientNo = item.no;
    }

    this.querySaveSpePackage();
  }

  /**
   * @description: PDA扫码复制到文本输入框
   * @return {*}
   * @author: seimin
   */
  specimenCode:string = '';
  inputChange(e){
    if(this.specimenCode.length >= 8){
      this.searchTimer(this.addSpeciment, this.specimenCode);
    }
  }

  // 添加标本
  maskFlag: any = false;
  addSpeciment(speCode){
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;

    let postData = {
      speCode,
      packageId: this.package.id,
    };

    this.mainService
      .addPackageSpe(postData)
      .subscribe((result:any) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;

        if(result.state == 200){
          this.message.success('操作成功！');
          this.specimenCode = '';//清空
          this.querySaveSpePackage();
        }else{
          this.message.error(result.msg || '操作失败！');
        }
      });
  }

  // 防抖
  searchTimer(fun, e) {
    this.searchTimerSubject.next([fun, e]);
  }

  // 自动清点规则
  isShowPackageSpecimenRule:boolean = false;
  showPackageSpecimenRule(){
    this.isShowPackageSpecimenRule = true;
  }

  // 关闭自动清点规则
  closePackageSpecimenRule(e){
    this.isShowPackageSpecimenRule = e;
  }
}
