import { Component, OnInit, ViewChild} 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 } 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-info-detail",
  templateUrl: "./dispensing-info-detail.component.html",
  styleUrls: ["./dispensing-info-detail.component.less"],
})
export class DispensingInfoDetailComponent 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,
    private http: HttpClient,
  ) {}
	
  ngOnInit() {
    this.searchParentDeptSubject.pipe(debounceTime(500)).subscribe((e) => {
     if(e[1]=='dept'){
			 this.getDeparts(e[0]);
		 }else if(e[1]=='commodity'){
			 this.getCommodityData(e[0])
		 }else{
			 this.getBathData(e[0])
		 }

    });
		this.hosId = this.tool.getCurrentHospital().id;
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getAllquest();
  }
  listOfData: any[] = []; //表格数据
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  department: ""; //所属科室
	batch:any = null;
	commodity:any = null;
	hosId: number; 
	dateRange;//时间
  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 = []; //科室列表(搜索)
	rowData: object = {}; //打印选择列表
  searchParentDeptSubject = new Subject();
  // 初始化增删改按钮
  coopBtns: any = {};
	viewData: any = []; //科室单查看数据
	commodityData:any = [];
	batchData:any = [];
	maskFlag:any = null;
	
	
  // 导出
  excelExport(){
    this.maskFlag = this.message.loading("正在导出..", {
      nzDuration: 0,
    }).messageId;
    this.mainService.exportReport("dispensingMedicine", {
			deptId:this.department,
			batchId:this.batch,
			startTime: this.startDate,
			endTime: this.endDate,
			drugId:this.commodity,
			hosId:this.hosId
		}).subscribe(
      (data) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.message.success('导出成功');
        var file = new Blob([data], {
          type: "application/vnd.ms-excel",
        });
        var fileURL = URL.createObjectURL(file);
        var a = document.createElement("a");
        a.href = fileURL;
        a.target = "_blank";
        a.download = "发药信息详情.xls";
        document.body.appendChild(a);
        a.click();
      },
      (err) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.message.error('导出失败');
      }
    );
  }

  //搜索父级科室
	loading = false;
  changeInp(e,type) {
		this.loading = true
    this.searchParentDeptSubject.next([e,type]);
  }

  // 搜索
  search() {
    this.pageIndex = 1;
    this.getList();
  }
  // 重置
  reset() {
    this.pageIndex = 1;
    this.department = null;
		this.batch = null;
		this.commodity = null;
    this.batchNumber = "";
		this.dateRange = [];
		this.startDate = "";
		this.endDate = "";
    this.getList();
  }
  // 表格数据
  loading1 = false;
  getList() {
    var that = this;
    let data = {
      idx: that.pageIndex - 1,
      sum: that.pageSize,
			deptId:this.department,
			batchId:this.batch,
			startTime: this.startDate,
			endTime: this.endDate,
			drugId:this.commodity,
			hosId:this.hosId
    };
		this.loading1 = true;
		this.mainService
			.drugsInfo(data).subscribe((res:any) => {
				this.loading1 = false;
				for(let i of res.list){
					i.num = i['4'] + i['5'] + i['6']
				}
				this.listOfData = res.list
				that.listLength = res.totalNum;
			});
  }
	
	// 日期选择
	startDate: string; //发起时间开始
	endDate: string; //发起时间结束
	changeDate(result?): void {
	  if (result.length==0) {
	    this.startDate = this.endDate = null;
	    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');
		this.dateRange = [this.startDate,this.endDate]
	}
	
	// 获取所有科室
  getDeparts(dept) {
    var that = this;
    let data:any = {
      department: {
        dept,
        hosIds: this.hosId,
      },
      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
		.getFetchDataList("data", "department", data)
		.subscribe((data) => {
			this.loading = false
			this.hospitals1 = data.list
		});
  }
	
	// 获取药品
	getCommodityData(name) {
	  let data = {
	    drugsInfo: {
	      drugName: name || "",
	      hosId: this.hosId || "" ,
	    	drugType:{
	    		id:'20327'
	    	}
	    },
	    idx: 0,
	    sum: 10,
	  };
	  this.mainService
		.getFetchDataList("data", "drugsInfo", data)
		.subscribe((data) => {
			this.loading = false
			this.commodityData = data.list
		});
	}
	
	// 获取批次号
	getBathData(name) {
	  let data = {
	    drugsBatch: {
	    	batchNo:name,
	    	hosId: this.hosId,
				batchState:{
					value:2
				}
	    },
	    idx: 0,
	    sum: 10,
	  };
	  this.mainService
		.getFetchDataList("data", "drugsBatch", data)
		.subscribe((data) => {
			this.loading = false
			this.batchData = data.list
		});
	}
	
	isParentData:any = null;
  getAllquest() {
		this.mainService.getDictionary("list", "ordinary_field").subscribe((data) => {
			let taskTypeData = data.find(i=>i.value=='infusionSolutions')
			let postData = {
			  idx: 0,
			  sum: 10,
			  taskTypeConfig: {
					hosId:this.hosId,
					taskType:taskTypeData.id
			  }
			};
			this.mainService
			  .getFetchDataList("simple/data", "taskTypeConfig", postData)
			  .subscribe((result) => {
			    if (result.status == 200) {
						let data = result.list[0] || {};
						this.isParentData = data.quoteParentData;
						this.getDeparts('')
			    }
			  });
		});
		this.getCommodityData('')
		this.getBathData('')
    this.getList();
  }
}
