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 { 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-drug-cloud",
  templateUrl: "./drug-cloud.component.html",
  styleUrls: ["./drug-cloud.component.less"],
})
export class DrugCloudComponent 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) => {
			this.isDeptLoading = true;
			if(e[1]=='dept'){
				this.getDeparts(e[0]);
			}else{
				this.getDrugInfo(e[0]);
			}
    });
		this.hosId = this.tool.getCurrentHospital().id;
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.getAllHospital();
  }
  listOfData: any[] = []; //表格数据
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  department: number; //所属科室
	drug: number; //药品名称
	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 = {};
	drugData: any = []; //药品搜索列表
	drugTypeData: any = {}; //药品类型
	viewData: any = []; //历史记录
  // 导入---start
  // model-取消
  isShow = false;
  hideExcelImport() {
    this.isShow = false;
  }
  // 触发
  excelImport() {
    this.isShow = true;
  }

  // 导入---end
  //搜索父级科室
	isDeptLoading = false;
  changeInp(e,type) {
    this.searchParentDeptSubject.next([e,type]);
  }

  // 配送建单
  coopData:any = {};
  addDateModal(data) {
    this.coopData = data;
    this.showDelModal1();
  }
  delModal1: boolean = false; //删除模态框

  showDelModal1() {
    this.delModal1 = true;
  }
  hideDelModal1() {
    this.delModal1 = false;
  }

  // 搜索
  search() {
    this.pageIndex = 1;
    this.getList();
  }
  // 重置
  reset() {
    this.pageIndex = 1;
    this.department = null;
    this.drug = null;
    this.getList();
  }
	
	// 获取药品类型
	getDrugType(){
		this.mainService.getDictionary("list", "drug_type").subscribe((data) => {
			this.drugTypeData = data.find(i=>i.value=='infusion_solutions')
			this.getDrugInfo('')
		});
	}
	
	// 获取药品信息
	getDrugInfo(e) {
	  let data = {
	    idx: 0,
	    sum: 20,
	    drugsInfo: {
				drugName: e,
	      hosId: this.hosId || "" ,
				drugType:{
					id:this.drugTypeData.id
				}
	    },
	  };
	  this.mainService
	    .getFetchDataList("data", "drugsInfo", data)
	    .subscribe((data) => {
				this.isDeptLoading = false;
	      this.drugData = data.list;
				this.getList();
	    });
	}
	
  // 表格数据
  loading1 = false;
  getList() {
    var that = this;
    let data = {
      idx: that.pageIndex - 1,
      sum: that.pageSize,
      drugsCloudInventory: {
        deptId: that.department,
        drugId: that.drug,
        hosId: this.hosId
      },
    };
    this.loading1 = true;
    that.mainService
      .getFetchDataList("data", "drugsCloudInventory", data)
      .subscribe((data) => {
        this.loading1 = false;
        that.listOfData = data.list;
        that.listLength = data.totalNum;
      });
  }
	
	
	// 获取所有科室
  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) => {
				setTimeout(_=>{
					this.isDeptLoading = false
					this.hospitals1 = data.list
				},500)
      });
  }
	
  // 获取所有院区
	isParentData:any = null;
  getAllHospital() {
		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.getDrugType();
			    }
			  });
		});
  }


  // 新增弹框
  showModal() {
    this.initForm();
    // this.changeHosp();
    this.add = true;
    this.isAddDeptsPhone = true;
    this.deptPhones = [];
  }
  hideModal() {
    this.modal = false;
    this.initForm();
  }
  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      parentOfficeName: [null],
      officeName: [null, [Validators.required]],
      deptalias: [null],
      officeNo: [null, [Validators.required]],
      officeNum: [null, [Validators.required]],
      building: [null, [Validators.required]],
      floor: [null, [Validators.required]],
      officeAddress: [null, [Validators.required]],
      officeType: [null, [Validators.required]],
      deptHandoverType: [null],
      startTime1: [null],
      endTime1: [null],
      dynamicCode1: [null],
      startTime2: [null],
      endTime2: [null],
      dynamicCode2: [null],
    });
  }
  // 科室位置必填
  buildValidator = (control: FormControl): { [s: string]: boolean } => {
    if (
      this.validateForm &&
      this.validateForm.value &&
      (!this.validateForm.value.building ||
        !this.validateForm.value.floor ||
        !this.validateForm.value.officeAddress)
    ) {
      return { required: 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 flag true是批量删除，false是单个删除
   * @param id
   */
  showDelModal(e, flag, id) {
    e.stopPropagation();
    this.delModal = true;
    this.coopFlag = flag;
    if (flag) {
      this.coopIds = id;
    } else {
      this.coopId = id;
    }
  }
  hideDelModal() {
    this.delModal = false;
  }

  // 查看
  detail(e, item) {
    e.stopPropagation();
		var that = this;
		let data = {
			idx: 0,
			sum: 9999,
			drugsLog: {
			  hosId: this.hosId,
			  drugId: item.drugId,
				deptId: item.deptId
			}
		};
		this.loading1 = true;
		that.mainService
		  .getFetchDataList("data", "drugsLog", data)
		  .subscribe((data) => {
		    this.loading1 = false;
				this.modal = true
		    that.viewData = data.list;
		  });
  }

}
