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 { HttpRequest, HttpResponse, HttpClient } from '@angular/common/http';

@Component({
  selector: "app-dispensing-detail",
  templateUrl: "./dispensing-detail.component.html",
  styleUrls: ["./dispensing-detail.component.less"],
})
export class DispensingDetailComponent 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;
			this.getBuilding(e[0]);
    });
		this.detailId = this.route.snapshot.params.id;
		this.hosId = this.tool.getCurrentHospital().id;
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getAllHospital();
  }
	detailId:null; //列表数据
	deptId:null; //选中的科室id
  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; 
	rowId:number; //清单id
	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 = []; //科室列表
	buildingList: any = []; //楼栋列表
	deptList: any = []; //楼栋科室
	building:''; //楼栋
	deptIndex:number; //选中index
  searchParentDeptSubject = new Subject();
  // 初始化增删改按钮
  coopBtns: any = {};
	deptName:null;
  //搜索父级科室
	isDeptLoading = false;
	isSpinning = false;
	delGrantModal = false;
	showInsp = false;
  changeInp(e, type) {
    this.searchParentDeptSubject.next([e, type]);
  }

  // 表格数据
  loading1 = false;
  getList() {
    var that = this;
    let data = {
    	idx: 0,
    	sum: 9999,
    	drugsConfigure: {
    	  hosId: this.hosId,
				deptId :this.deptId?this.deptId:null,
    	  batchId: this.detailId
    	}
    };
    this.loading1 = true;
    that.mainService
      .getFetchDataList("data", "drugsConfigure", data)
      .subscribe((data) => {
        this.loading1 = false;
        that.listOfData = data.list;
      });
  }
	
	// 发药科室列表
	getDispensingDept(e,type){
		var that = this;
		let data = {
			idx: 0,
			sum: 9999,
			drugsConfigure: {
			  hosId: this.hosId,
				deptId :e,
				batchId:''
			}
		};
		if(type=='dept'){
			data.drugsConfigure.batchId = this.detailId
		}else{
			delete data.drugsConfigure.batchId
		}
		let deptData = this.hospitals1.find(i=>i.id==e)
		that.mainService
		  .getFetchDataList("data", "drugsConfigure", data)
		  .subscribe((res) => {
				if(res.list.length==0){
					this.message.error(`您选择的科室“	${deptData.dept}”时间段内没有消耗药品无法添加发药单。`)
				}else{
					this.getDeptData(e,'all','load')
				}
		  });
	}
	
	// 科室点击
	deptClick(e,item,index){
		e.stopPropagation();
		this.deptId = item.applyDeptDTO.id
		this.deptName = item.applyDeptDTO.dept
		this.deptIndex = index
		this.getList()
	}
	
	// 科室删除
	deptDel(e,item,index){
		e.stopPropagation();
		this.delModal = true;
		this.coopId = item.applyDept;
	}
	
	hideDelModal() {
	  this.delModal = false;
	}
	
	// 确认删除
	confirmDel() {
		var that = this;
		let data = {
			hosId: this.hosId,
			deptId :this.coopId,
			batchId: this.detailId
		};
		that.btnLoading = true;
		that.mainService
		  .transfusionConfigDeptDel(data)
		  .subscribe((res) => {
				that.btnLoading = false;
				that.delModal = false;
				this.deptId = null
				this.deptName = null
				this.deptIndex = null
				this.getDeptData('','all','load')
				if (res.status==200) {
				  that.showPromptModal("删除", true, "");
				} else {
				  that.showPromptModal("删除", false, res.msg);
				}
		  });
	}
	// 选择楼栋
	buildingChange(e){
		this.deptId = null
		this.deptName = null
		this.deptIndex = null
		this.listOfData=[]
		this.showInsp = true
		this.getDeptData(e,'','')
	}
	
	// 根据楼栋查询科室
	getDeptData(e,type,initial){
		var that = this;
		let data = {
		  idx: 0,
		  sum: 99999,
		  drugsList: {
				hosId: this.hosId,
				buildingId:e,
				batch:{
					id:this.detailId
				}
		  },
		};
		if(type=='all'){
			delete data.drugsList.buildingId
		}else{
			data.drugsList.buildingId = e
		}
		if(this.showInsp){
			this.isSpinning = true
		}
		that.mainService
		  .getFetchDataList("data", "drugsList", data)
		  .subscribe((res) => {
				this.isSpinning = false
		    that.deptList = res.list;
				if(initial=='load'){
					if(res.list.length>0){
						this.deptId = res.list[0].applyDeptDTO.id
						this.deptName = res.list[0].applyDeptDTO.dept
						this.deptIndex = 0
					}
					this.getList()
				}
		  });
	}
	
	// 选择科室
	addDeptId=''
	deptChange(e){
		this.addDeptId = e
		
	}
	// 添加科室
	addDept(){
		if(this.addDeptId){
			this.showInsp = true
			this.getDispensingDept(this.addDeptId,'dept')
		}else{
			this.message.error('请先选择发药科室')
		}
	}
	
	// 获取楼栋
	getBuilding(name){
		let postData = {
		  building: {
		    cascadeHosId: this.hosId,
		    buildingName: name
		  },
		  idx: 0,
		  sum: 20,
		};
		this.mainService
		  .getFetchDataList("data", "building", postData)
		  .subscribe((result) => {
				setTimeout(_=>{
					this.isDeptLoading = false
					this.buildingList = result.list;
				},500)
		  });
	}
	
	// 获取所有科室
  getDeparts() {
    let data = {
      batchId:this.detailId
    };
    this.mainService
      .getConsumeDept(data)
      .subscribe((res) => {
				this.isDeptLoading = false;
				this.hospitals1 = res.data
      });
  }
	
  // 获取所有院区
  getAllHospital() {
		this.getDeparts()
		this.getBuilding('')
		this.getDeptData('','all','load')
		this.getDicData()
  }
	
	// 获取单发箱发字典
	dicData = [];
	getDicData(){
		this.mainService.getDictionary("list", "give_out_type").subscribe((res) => {
			this.dicData = res
		});
	}
	
	// 单发/箱发
	content = '';
	giveName = '';
	grantClick(e, data){
		this.rowId = data.id
		this.giveName = data.giveOutType.value
		if(data.giveOutType.value==1){
			this.content = `您确认要修改发药类型为箱发吗？`
		}else{
			this.content = `您确认要修改发药类型为单发吗？`
		}
		this.delGrantModal = true
	}
	
	// 修改发放类型
	confirmGrantDel(){
		var that = this;
		let list = null;
		console.log(11,this.dicData)
		if(this.giveName=='1'){
			list = this.dicData.find(i=>i.value == '2')
		}else{
			list = this.dicData.find(i=>i.value == '1')
		}
		let data = {
			id:this.rowId,
			deptId:this.deptId,
			giveOutType:{
				id:list.id
			}
		};
		that.btnLoading = true;
		that.mainService
		  .simplePost("addData", "drugsConfigure", data)
		  .subscribe((data) => {
		    that.btnLoading = false;
		    that.hideGrantModal();
				this.getList()
		    if (data.status == 200) {
		      that.showPromptModal("修改", true, "");
		    } else {
		      that.showPromptModal("修改", false, data.msg);
		    }
		  });
	}
	
	hideGrantModal(){
		this.delGrantModal = false;
	}
	
	// 增加/减少
	rowData = null;
	itemClick(e, data, type){
		this.isRight = null;
		e.stopPropagation();
		this.rowId = data.id
		this.rowData = data
		if(type=='add'){
			this.add = true
		}else{
			this.add = false
		}
		this.modal = true
		this.initForm();
	}
	
	// 表单提交
	isRight = null;
	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 = {
			addSub:this.validateForm.value.addNum,
			id:this.rowId,
			hosId:this.hosId,
			deptId:this.deptId,
	  };
		if(this.rowData.giveOutType.value==2){
			let num1 = Number(this.rowData.expendCount) + Number(this.rowData.formerInventory) + Number(data.addSub)
			let num2 = num1 / this.rowData.drugsInfoDTO.packingSpecs
			if(num2 % 1 === 0){
				this.isRight = true
			}else{
				this.isRight = false
				this.message.error('数量错误，请重新填写！')
				return
			}
		}
		that.btnLoading = true;
	  that.mainService
	    .simplePost("addData", "drugsConfigure", data)
	    .subscribe((data) => {
	      that.btnLoading = false;
	      that.hideModal();
				this.getList()
	      if (data.status == 200) {
	        that.showPromptModal(that.add ? "增加" : "减少", true, "");
	      } else {
	        that.showPromptModal(that.add ? "增加" : "减少", false, data.msg);
	      }
	    });
	}

  // 新增弹框
  showModal() {
    this.add = true;
    this.isAddDeptsPhone = true;
    this.deptPhones = [];
  }
	// 返回
	back(){
		this.router.navigateByUrl(`/main/dispensingBatch`);
	}
	
  hideModal() {
		this.initForm();
    this.modal = false;
  }
  // 初始化新增form表单
  initForm() {
		if(this.add){
			this.validateForm = this.fb.group({
			  addNum: [null, [Validators.required]]
			});
		}else{
			this.validateForm = this.fb.group({
				delNum: [null, [Validators.required]]
			});
		}
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
  }

  delModal: boolean = false; //删除模态框
  coopIds: any;
  coopFlag: any = false;

}
