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

import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { format, startOfDay, endOfDay, subDays} from "date-fns";
import { NzMessageService } from "ng-zorro-antd";
import { Subject } from "rxjs";
import { debounceTime, filter } from "rxjs/operators";
import host from "../../../assets/js/http";
import { HttpRequest, HttpResponse, HttpClient } from '@angular/common/http';

@Component({
  selector: "app-dispensing-batch",
  templateUrl: "./dispensing-batch.component.html",
  styleUrls: ["./dispensing-batch.component.less"],
})

export class DispensingBatchComponent implements OnInit, OnDestroy {
  @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,
    private http: HttpClient,
  ) {}
	
	ngOnDestroy() {
		clearInterval(this.logTimer)
	}
	
  ngOnInit() {
		this.searchParentDeptSubject.pipe(debounceTime(500)).subscribe((e) => {
			this.getAddDeparts(e);
		});
		this.hosId = this.tool.getCurrentHospital().id;
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
		this.getTaskTypesId();
    this.getAllHospital();
    this.getDeptHandoverType();
		this.autoUpdate(true)
  }
  listOfData: any[] = []; //表格数据
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  department: number; //所属科室
	infoDepartment: number; //所属科室
	hosId: number; 
	dateRange;//时间
	loadAllConsumeDept: boolean = true;//是否加载所有消耗科室
  batchNumber; //批次号
  num; //编码
  deptalias; //别名
  type; //类型
  deptHandoverType; //类型
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数
  btnLoading: boolean = false; //确认按钮loading状态
  printLoading: boolean = false; //批量打印按钮loading状态
  deptPhones: any = []; //新添加的科室电话列表
  isAddDeptsPhone = true; //添加新的科室电话是否禁用
  deptsPhoneId = 1; //科室电话自增id
  allParentdepart: any = []; //所有的父级科室列表
  hospitals1: any = []; //科室列表(搜索)
	addHospitals: any = [];
	rowData: any = null; //打印选择列表
	editModal:boolean = false; //编辑时弹框
  searchParentDeptSubject = new Subject();
  // 初始化增删改按钮
  coopBtns: any = {};
	saveLoading:boolean = false;
	taskTypeData:{id:''};
	
  // 导入---end
  //搜索父级科室
	isDeptLoading = false;
  changeInp(e) {
		this.isDeptLoading = true;
    this.searchParentDeptSubject.next(e);
  }
  // 配送建单
  coopData:any = {};
  addDateModal(data) {
    this.coopData = data;
    this.showDelModal1();
  }

  showDelModal1() {
    this.editModal = true;
  }
  hideDelModal1() {
    this.editModal = false;
  }
	
	// 30s倒计时
	logTimer = null; //定时器
	logTime = 0; //自动刷新秒数
	logTimeConst = 30; //自动刷新秒数
	autoUpdate(flag = true) {
	  if (flag) {
	    this.logTime = this.logTimeConst;
	  }
	  clearInterval(this.logTimer);
	  this.logTimer = setInterval(() => {
	    this.logTime--;
	    if (this.logTime === 0) {
	      this.logTime = this.logTimeConst;
				this.getList()
	    }
	  }, 1000);
	}
	
  // 编辑保存
  confirmDel1() {
    var that = this;
		for (const i in that.validateForm.controls) {
		  that.validateForm.controls[i].markAsDirty();
		  that.validateForm.controls[i].updateValueAndValidity();
		}
		if (that.validateForm.invalid) return;
    let data: any = {
			startTime:this.formStartDate?this.formStartDate:this.loadStartTime,//发起时间开始
			endTime:this.formEndDate?this.formEndDate:this.loadEndTime,//发起时间结束
			hosId:this.hosId,
			pharmacy:this.validateForm.value.addDepartment,
			id:that.coopId,
			loadAllConsumeDept:this.validateForm.value.loadAllConsumeDept?1:0
    };
		that.saveLoading = true;
		that.mainService
		  .simplePost("addData", "drugsBatch", data)
		  .subscribe((data) => {
		    that.saveLoading = false;
		    that.hideModal();
		    that.initForm();
		    if (data.status == 200) {
					this.editModal = false;
		      that.showPromptModal("编辑", true, "");
		    } else {
		      that.showPromptModal("编辑", false, data.msg);
		    }
		  });
  }

  // 搜索
  search() {
    this.pageIndex = 1;
    this.getList();
  }
  // 重置
  reset() {
    this.pageIndex = 1;
		this.batchNumber = null;
    this.startDate = null;
		this.endDate = null;
		this.dateRange = [];
    this.getList();
  }
  // 表格数据
  loading1 = false;
  getList() {
    var that = this;
    let data = {
      idx: that.pageIndex - 1,
      sum: that.pageSize,
      drugsBatch: {
    		batchNo:that.batchNumber,
        startTime: this.startDate,
    		endTime: this.endDate,
    		hosId: this.hosId
      },
    };
    if(that.batchNumber){
    	data.drugsBatch.batchNo = that.batchNumber
    }else{
    	delete data.drugsBatch.batchNo
    }
    this.loading1 = true;
    that.mainService
      .getFetchDataList("data", "drugsBatch", data)
      .subscribe((data) => {
        this.loading1 = false;
        that.listOfData = data.list;
        that.listLength = data.totalNum;
      });
  }
	
	// 日期选择
	startDate: string; //发起时间开始
	endDate: string; //发起时间结束
	changeDate(result?): void {
	  if (!result) {
	    this.startDate = this.endDate = "";
	    return;
	  }
	  this.startDate = format(startOfDay(result[0]), 'yyyy-MM-dd HH:mm:ss');
	  this.endDate = format(endOfDay(result[1]), 'yyyy-MM-dd HH:mm:ss');
	}
	
	// 新增、编辑日期选择
	formStartDate: string; //发起时间开始
	formEndDate: string; //发起时间结束
	formChangeDate(result?): void {
		if (!result) {
		  this.formStartDate = this.formEndDate = "";
		  return;
		}
		this.formStartDate = format(result[0], 'yyyy-MM-dd HH:mm:ss');
		this.formEndDate = format(result[1], 'yyyy-MM-dd HH:mm:ss');
	}
	
	// 获取所有科室
  getDeparts() {
		let data = {
		  batchId:this.rowData.id
		};
		this.mainService
		  .getConsumeDept(data)
		  .subscribe((res) => {
				this.isDeptLoading = false;
				this.hospitals1 = res.data
		  });
  }
	
	// 获取药房科室
	getAddDeparts(dept) {
		var that = this;
		let data:any = {
			department: {
				dept,
				hosIds: this.hosId,
				type:{
					id:''
				}
			},
			idx: 0,
			sum: 20,
		};
		if(this.isParentData==1){
			if(this.tool.getCurrentUserInfo().currentHospital &&
			this.tool.getCurrentUserInfo().currentHospital.parent){
				data.department.hosIds = this.hosId +','+this.tool.getCurrentUserInfo().currentHospital.parent.id
			}else{
				data.department.hosIds = this.hosId
			}
		}
		that.mainService.getDictionary("list", "dept_type").subscribe((res) => {
			let typeData = res.find(i=>i.value=='pharmacyRoom');
			if(typeData){
				data.department.type.id = typeData.id
			}
			that.mainService
				.getFetchDataList("data", "department", data)
				.subscribe((data) => {
					this.addHospitals = data.list
					that.isDeptLoading = false;
				});
		});
	}
		
  // 获取所有院区
  getAllHospital() {
    this.getList();
  }

  // 获取科室汇总交接类型
  deptHandoverTypes: Array<any> = [];
  getDeptHandoverType() {
    var that = this;
    that.mainService.getDictionary("list", "dept_handover_type").subscribe((data) => {
      console.log(data);
      that.deptHandoverTypes = data;
    });
  }
	
	// 获取任务id
	getTaskTypesId() {
		this.mainService.getDictionary("list", "ordinary_field").subscribe((data) => {
			this.taskTypeData = data.find(i=>i.value=='infusionSolutions')
		});
	}
	
	// 获取配置
	isParentData:any;
	getConfig(type) {
	  let postData = {
	    idx: 0,
	    sum: 10,
	    taskTypeConfig: {
				hosId:this.hosId,
				taskType:this.taskTypeData.id
	    }
	  };
	  this.mainService
		.getFetchDataList("simple/data", "taskTypeConfig", postData)
		.subscribe((result) => {
			if (result.status == 200) {
				let data = result.list[0] || {};
				this.isParentData = data.quoteParentData;
				if(type=='add'){
					this.add = true;
					this.isAddDeptsPhone = true;
					this.validateForm.controls.addDepartment.setValue(data.pharmacyDept || '');
				}
				this.getAddDeparts('')
				this.modal = true;
			}
		});
	}
	
  // 新增弹框
  showModal() {
    this.initForm();
		this.getConfig('add');
  }
  hideModal() {
    this.coopItem = null;
    this.modal = false;
    this.initForm();
  }
  // 初始化新增form表单
	loadStartTime = '';
	loadEndTime = '';
  initForm() {
    this.validateForm = this.fb.group({
      dispensingTime: [null, [Validators.required]],
      addDepartment: [null, [Validators.required]],
			loadAllConsumeDept: [true,[]]
    });
		let date = new Date();
		this.loadStartTime = format(subDays(date, 1), "yyyy-MM-dd") +' '+'08:00:00'
		this.loadEndTime = format(date, "yyyy-MM-dd") +' '+'08:00:00'
		this.validateForm.controls.dispensingTime.setValue([this.loadStartTime, this.loadEndTime]);
  }

  // 表单提交
  submitForm(): void {
    var that = this;
		for (const i in that.validateForm.controls) {
		  that.validateForm.controls[i].markAsDirty();
		  that.validateForm.controls[i].updateValueAndValidity();
		}
		if (that.validateForm.invalid) return;
    let data: any = {
			startTime:this.formStartDate?this.formStartDate:this.loadStartTime,//发起时间开始
			endTime:this.formEndDate?this.formEndDate:this.loadEndTime,//发起时间结束
			hosId:this.hosId,
			pharmacy:this.validateForm.value.addDepartment,
			loadAllConsumeDept:this.validateForm.value.loadAllConsumeDept?1:0
    };
  
    if (!that.add) {
			this.editModal = true
    }else{
			that.btnLoading = true;
			that.mainService
			  .simplePost("addData", "drugsBatch", 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);
			    }
			  });
		}
  }

  // 编辑
  coopItem: any = null;
  edit(e, data) {
    e.stopPropagation();
		this.getConfig('edit');
    this.add = false;
    this.coopId = data.id;
    this.coopItem = data;
    this.validateForm.controls.addDepartment.setValue(data.pharmacy);
    this.validateForm.controls.dispensingTime.setValue([data.startTime,data.endTime]);
		if(data.loadAllConsumeDept==1){
			this.validateForm.controls.loadAllConsumeDept.setValue(true);
		}else{
			this.validateForm.controls.loadAllConsumeDept.setValue(false);
		}
		this.loadStartTime = data.startTime
		this.loadEndTime = data.endTime
		this.modal = true
  }

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

  delModal: boolean = false; //删除模态框
  coopIds: any;
  coopFlag: any = false;
  /**
   *
   * @param e 事件对象
   * @param id
   */
  showDelModal(e, id) {
    e.stopPropagation();
    this.delModal = true;
    this.coopId = id;
  }
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    var that = this;
    that.btnLoading = true;
    that.mainService
      .coopTypeConfig(
        "rmvData",
        "drugsBatch",
         [that.coopId]
      )
      .subscribe((data) => {
        that.btnLoading = false;
        that.delModal = false;
        if (data.status==200) {
          that.showPromptModal("删除", true, "");
        } else {
          that.showPromptModal("删除", false, data.data[0].msg);
        }
      });
  }
	
	// 发药总量
	grossModal:boolean = false;
	grossLoading:boolean = false;
	viewData:any = [];
	dispensingGross(e,data){
		this.grossModal = true
		this.grossLoading = true
		this.mainService
		  .drugsGross(data.id)
		  .subscribe((res:any) => {
		    this.grossLoading = false;
				this.viewData = res.data
		  });
	}
	
	// 关闭发药总量
	hideGrossModal(){
		this.grossModal = false
	}
	
	// 发药信息
	infoModal:boolean = false;
	infoLoading:boolean = false;
	infoData:any = [];
	dispensingInfo(e,data){
		this.rowData = data
		this.getDeparts()
		this.infoModal = true
		this.infoLoading = true
		this.mainService
		  .drugsInfo({
				batchId:data.id,
				dataType:'batchDispensingMedicine'
			}).subscribe((res:any) => {
		    this.infoLoading = false;
				this.infoData = res.list
		  });
	}
	
	// 关闭发药信息
	hideInfoModal(){
		this.infoModal = false
	}
	// 发药信息搜索
	searchInfo(){
		this.getInfo()
	}
	
	getInfo(){
		this.infoLoading = true
		this.mainService
		  .drugsInfo({
				deptId:this.infoDepartment,
				batchId:this.rowData.id,
				dataType:'batchDispensingMedicine'
			}).subscribe((res:any) => {
		    this.infoLoading = false;
				this.infoData = res.list
		  });
	}
	
	// 发药信息重置
	resetInfo(){
		this.infoDepartment = null
		this.getInfo()
	}
	
	// 导出
	maskFlag:any = null;
	exportPc(e,data){
		this.maskFlag = this.message.loading("正在导出..", {
		  nzDuration: 0,
		}).messageId;
		this.mainService.exportReport("drugsBatch", {
			batchId:data.id
		}).subscribe(
		  (res:any) => {
		    this.message.remove(this.maskFlag);
		    this.maskFlag = false;
		    this.message.success('导出成功');
		    var file = new Blob([res], {
		      type: "application/vnd.ms-excel",
		    });
		    var fileURL = URL.createObjectURL(file);
		    var a = document.createElement("a");
		    a.href = fileURL;
		    a.target = "_blank";
		    a.download = `发药批次数据-${data.batchNo}.xls`;
		    document.body.appendChild(a);
		    a.click();
		  },
		  (err) => {
		    this.message.remove(this.maskFlag);
		    this.maskFlag = false;
		    this.message.error('导出失败');
		  }
		);
	}
	
  // 查看
  detail(e, data) {
    e.stopPropagation();
		this.router.navigateByUrl(`/dispensingDetail/${data.id}`);
  }

	// 发药并打印
	printData = []; 
	summaryDataList = [];
	batchNo:any = null;
	print(e, data, id){
		this.rowData = data
		e.stopPropagation();
		let that = this;
		that.printLoading = true;
		that.mainService
		  .transfusionPrint("drugsBatch", id)
		  .subscribe((res) => {
				this.batchNo = res.data.batchNo
				let arr = res.data.drugsListDTOS;
				this.summaryDataList = res.data.summaryDataList;
				for(let i of arr){
					for(let t of i.drugsConfigureDTOS){
						t.deptName = i.pharmacyDTO?i.pharmacyDTO.dept:'-'
					}
					i.drugsConfigureDTOS.push({
						drugsInfoDTO:{
							drugName:'合计',
							specs:'',
						},
						expendCount:i.totalExpendCount,
						addSub:i.totalAddSub,
						deptName:'',
						cartonActual:i.cartonActual
					})
				}
		    that.printData = arr;
		    that.printLoading = false;
				that.btnLoading = false;
				that.printModal = false;
		    setTimeout(() => {
		      const printContent = document.getElementById("report");
		      const WindowPrt = window.open("", "", "width=1000,height=1200");
		      WindowPrt.document.write(printContent.innerHTML);
		      WindowPrt.document.close();
		      WindowPrt.focus();
		      WindowPrt.print();
		      WindowPrt.close();
					setTimeout(()=>{
						this.getList();
					},200)
		    }, 500);
		  });
	}
	
	printModal = false;
	printE = '';
	printItemData = '';
	printItemId = '';
	dispensingPrint(e, data, id){
		this.printModal = true
		this.printE = e
		this.printItemData = data
		this.printItemId = id
	}
	
	confirmPrintDel(){
		this.btnLoading = true;
		this.print(this.printE, this.printItemData, this.printItemId)
	}
	
	hidePrintModal(){
		this.printModal = false
	}
}
