import { Component, OnInit, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core';
import { MainService } from '../../services/main.service';
import { ToolService } from 'src/app/services/tool.service';
import { format, startOfDay, endOfDay } from 'date-fns';
import { NzMessageService } from 'ng-zorro-antd';
import { Router } from '@angular/router';
@Component({
  selector: 'app-specimen-package-list-modal',
  templateUrl: './specimen-package-list-modal.component.html',
  styleUrls: ['./specimen-package-list-modal.component.less']
})
export class SpecimenPackageListModalComponent implements OnInit {
  @ViewChild('printBtnPackage', { static: false }) printBtnPackage: ElementRef<HTMLElement>;
  // 切换科室，切换弹窗
  hosId;
  hsLoading = false;
  packageList: any = [];// 标本列表
  pageIndex: number = 1;//表格当前页码
  pageSize: number = 10;//表格每页展示条数
  total: number = 0;//表格总数据量
  searchCriteria:any = {}

  deptId = this.tool.getCurrentUserDept().id;
  @Input() specimenPackageStateValue = '';
  @Output() closeModelHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件

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

  ngOnInit() {
    this.hosId = this.tool.getCurrentHospital().id;

    this.getStatusList();
  }
  // 关闭弹窗
  hideModal() {
    this.closeModelHs.emit(JSON.stringify({ show: false }));//emits(向上弹射)事件
  }

  // 切换状态下拉框
  selectStatus(e){
    this.getSpecimenPackageList(1);
  }

  // 分页获取数据
  getList(){
    this.getSpecimenPackageList();
  }
	
	// 关闭弹窗
	closeModel(e){
		this.showModal = false;
	}
	
	// 查看标本
	speId:any;
	showModal:boolean = false;
	viewSpe(data){
		this.speId = data.id;
		this.showModal = true;
	}
	
  // 获取状态
  specimentPackageTypeList: any[] = [];
  getStatusList() {
    this.mainService.getDictionary("list", "pathology_pack_status").subscribe((data:any) => {
      this.specimentPackageTypeList = data || [];

      let obj = this.specimentPackageTypeList.find(v => v.value == this.specimenPackageStateValue);
      if(obj){
        this.searchCriteria.status = obj.id;
      }
      this.getSpecimenPackageList(1);
    })
  }

  // 获取标本列表
  getSpecimenPackageList(idx?) {
    if (idx) {
      this.pageIndex = 1;
    }
    let postData = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      pathologyPackInfo: {
        deptId: this.deptId,
        busiType: 'specimen',//标本打包
        status: this.searchCriteria.status ? { id: this.searchCriteria.status } : undefined,
      }
    }
    this.hsLoading = true;
    this.mainService.getFetchDataList('simple/data','pathologyPackInfo',postData).subscribe(data => {
      this.hsLoading = false;
      this.packageList = data.list || [];
      this.total = data.totalNum || 0;
    })
  }

  // 修改
  toSpecimenPackage(data){
    this.router.navigateByUrl(`/batchSpecimen?id=${data.id}`);
  }

  // 补打
  base64:string = '';
  typeSpecimentList:any[] = [];
  patientSpecimentList:any[] = [];
  package:any = {};
  printPackage(item){
    this.mainService
      .makeQrCode({}, item.packCode)
      .subscribe((data:any) => {
        if (data.state == 200) {
          this.typeSpecimentList = data.tube || [];
          this.patientSpecimentList = data.patient || [];
          let packageDTO:any = data.package || {};
          if(packageDTO.endDeptList){
            packageDTO.endDeptNames = packageDTO.endDeptList.map(v => v.dept).toString();
          }else{
            packageDTO.endDeptNames = "";
          }
          this.package = packageDTO;

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

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

  // 获取配置
  configs:any = {};
  printPackageByConfig(data) {
		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.printPackage(data);
        }
      });
  }

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  coopData: any; //当前操作列
  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;
  }
  btnLoading:boolean = false;
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      this.mainService
        .simplePost("rmvData", "pathologyPackInfo", [this.coopData.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, 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.getSpecimenPackageList(1);
  }
}



