import { Component, OnInit } from "@angular/core";
import { MainService } from 'src/app/services/main.service';
import { ToolService } from 'src/app/services/tool.service';
import { NzMessageService } from 'ng-zorro-antd';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { format, startOfMinute } from 'date-fns';

@Component({
  selector: "app-big-transfusion-set",
  templateUrl: "./big-transfusion-set.component.html",
  styleUrls: ["./big-transfusion-set.component.less"],
})
export class BigTransfusionSetComponent implements OnInit {
  loading:boolean = false; //页面加载的loading
  btnLoading:boolean = false; //提交按钮的loading
  tabModalName:string = 'characteristics'; //当前选中的tab
  surgeryField = null; //手术关联业务
  hosId = this.tool.getCurrentHospital().id; //当前院区
  // 接手术关联任务类型
  infusionSolutionsTypeId:Number;
	pharmacyDept:''; //默认发药科室
  taskTypes1:any[] = [];
  taskTypeData:{id:''};
  // 苏醒室科室
  recoveryDeptId:any;
  recoveryDepts:any[] = [];
	quoteParentData:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 自动建单
  autoCreateOrders:any[] = [
    {label:'是否开启',value: 0}
  ];
	// 定时建单
	timingOrder:any[] = [
	  {label:'是否开启',value: 0}
	];
	// 打印并建单
	printOrder:any[] = [
	  {label:'是否开启',value: 0}
	];
	radioValue:string = '';
	// 定时建单-选择时分
	executeTime:Date | null = null;
  // 是否开通送回病房
  autoSendWard:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否开通送回苏醒室
  autoSendAwakeningRoom:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否开通关联手术清洁建单
  autoRemandClean:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否开启手术即将开始通知
  surgeryBegin:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 建单时间
  autoTime:Date | null = null;
  tasktype1Id:any;
  tasktype2Id:any;
  cleanTypeId:any;
	associationTypeIds:any;
	questionnaireManagementData:any; //调查问卷数据
	questionnaireIds:Number; //问卷参数
	intervalTime:string = ''; //间隔时间参数
	taskTypeIds:any = []; //任务类型参数
	editId:'';
	targetData:any = [];
	stateData:any = [];
	hospitals:any = [];
	// 间隔时间数据
	timeData:any[] = [
	  {label:'10',value: 10},
		{label:'15',value: 15},
		{label:'30',value: 30},
		{label:'60',value: 60}
	];
  // 配置
  configs:any = {};
	isParentData:any = null;
  searchTimerSubject = new Subject();
	searchParentDeptSubject = new Subject();
  constructor(private mainService: MainService,private tool: ToolService,private msg: NzMessageService) {}

  ngOnInit():void {
    // todo
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1], v[2], v[3]);
    });
		
		this.searchParentDeptSubject.pipe(debounceTime(500)).subscribe((e) => {
			this.isLoading = true;
			this.getDeparts(e,'search');
		});
		this.getTaskTypesId()

  }

  // 切换tab
  tabModal(tabModalName:string){
    this.tabModalName = tabModalName;
  }

  // 保存
  submitForm() {
    if(!this.infusionSolutionsTypeId){
      this.msg.create("warning", "请选择任务类型！");
      return;
    }
		if(!this.pharmacyDept){
		  this.msg.create("warning", "请选择默认发药科室！");
		  return;
		}
    let editData = {
			id:'',
			taskType:this.taskTypeData.id,
			hosId: this.hosId,
			infusionSolutionsTypeId:this.infusionSolutionsTypeId, //任务类型参数
			pharmacyDept:this.pharmacyDept,//默认发药科室
			timingOrder:0,//定时建单
			printOrder:0,// 打印并建单
			executeTime:'',// 定时建单-选择时分
			autoCreate:0,
			quoteParentData:0
    };
		if(this.editId){
			editData.id = this.editId
		}else{
			delete editData.id 
		}
		
		if(this.autoCreateOrders[0].checked){
			editData.autoCreate = 1
		}else{
			delete editData.autoCreate
		}
		
		if(this.quoteParentData[0].checked){
			editData.quoteParentData = 1
		}else{
			delete editData.quoteParentData
		}
		if(this.radioValue=='1'){
			editData.timingOrder = 1
			editData.executeTime = this.executeTime ? format(startOfMinute(this.executeTime), "yyyy-MM-dd HH:mm:ss") : undefined
		}else{
			delete editData.timingOrder
			delete editData.executeTime
		}
		
		if(this.radioValue=='2'){
			editData.printOrder = 1
		}else{
			delete editData.printOrder
		}
		
    this.btnLoading = true;
    this.mainService
      .simplePost("addData", "taskTypeConfig", editData)
      .subscribe((result) => {
        this.btnLoading = false;
        if (result.status == 200) {
          this.getConfig();
        }
      });
  }
	
  // 用户输入搜索任务类型
  isLoading: boolean = false;
  changeTasktype(e) {
    this.searchTimer(this.getTaskTypes, e, false);
  }

  // 边输入边搜索节流阀
  searchTimer(fun, e, isFirst, type?) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e, isFirst, type]);
  }
	
	// 搜索科室
	changeInp(e) {
	  this.searchParentDeptSubject.next(e);
	}
	
  //获取关联任务类型
  // 1 患者其他服务
  // 2 其他临床服务
  getTaskTypes(e:string = '', isFirst:boolean = false, type) {
    isFirst && (this.loading = true);
    let postData:any = {
      idx: 0,
      sum: 9999,
      taskType: {
        taskName: e,
        simpleQuery: true,
				associationType : {
					key: 'association_types',
					value: 'other'
				},
        hosIds: this.hosId
      }
    };
		if(this.quoteParentData[0].checked){
			if(this.tool.getCurrentUserInfo().currentHospital &&
			this.tool.getCurrentUserInfo().currentHospital.parent){
				postData.taskType.hosIds = this.hosId +','+this.tool.getCurrentUserInfo().currentHospital.parent.id
			}else{
				postData.taskType.hosIds = this.hosId
			}
		}
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "taskType", postData)
      .subscribe((result) => {
        this.isLoading = false;
        if (result.status == 200) {
          this.taskTypes1 = result.list || [];
					// if(type=='load'){
					// 	this.getTaskTypesId();
					// }
        }
      });
  }
	
	// 获取任务id
	getTaskTypesId() {
		this.mainService.getDictionary("list", "ordinary_field").subscribe((data) => {
			this.taskTypeData = data.find(i=>i.value=='infusionSolutions')
			this.getConfig();
		});
	}
	
	// 获取所有科室
	getDeparts(dept, type) {
	  var that = this;
	  let data = {
	    department: {
	      dept,
	      hosIds: this.hosId,
				type:{
					id:''
				}
	    },
	    idx: 0,
	    sum: 20,
	  };
		if(this.quoteParentData[0].checked){
			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) => {
					if(type=='search'){
						setTimeout(_=>{
							this.hospitals = data.list
							that.isLoading = false;
						},500)
					}else{
						this.hospitals = data.list
						that.loading  = false;
					}
			  });
		});
	}
	
	parentChange(e){
		this.getTaskTypes('', true, 'load');
		this.getDeparts('','load');
		this.infusionSolutionsTypeId = null;
		this.pharmacyDept = null;
	}
	
  // 获取配置
  getConfig() {
    this.loading = true;
    let postData = {
      idx: 0,
      sum: 10,
      taskTypeConfig: {
				hosId:this.hosId,
				taskType:this.taskTypeData.id
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskTypeConfig", postData)
      .subscribe((result) => {
        this.loading = false;
        if (result.status == 200) {
    			let data = result.list[0] || {};
					this.isParentData = data.quoteParentData;
					this.editId = data.id
					this.autoCreateOrders[0].checked = data.autoCreate == 1;
					this.quoteParentData[0].checked = data.quoteParentData == 1;
    			this.infusionSolutionsTypeId = data.infusionSolutionsTypeId
					this.pharmacyDept = data.pharmacyDept
					this.getTaskTypes('', true, 'load');
					this.getDeparts('','load')
					if(data.timingOrder=='1'){
						this.radioValue = '1'
						this.executeTime = data.executeTime ? new Date(data.executeTime) : null;
					}else if(data.printOrder=='1'){
						this.radioValue = '2'
					}
        }
      });
  }
}

