import { Component, OnInit, ElementRef, ViewChild } from "@angular/core";
import { MainService } from "../../../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 } from 'date-fns';

@Component({
  selector: "app-configuration-closedData",
  templateUrl: "./configuration-closedData.component.html",
  styleUrls: ["./configuration-closedData.component.less"],
})
export class ConfigurationClosedDataComponent implements OnInit {
	@ViewChild('scrollContainer', {static: false}) scrollContainer: ElementRef;
	
  loading:boolean = false; //页面加载的loading
  btnLoading:boolean = false; //提交按钮的loading
  tabModalName:string = 'course'; //当前选中的tab
  hosId = this.tool.getCurrentHospital().id; //当前院区
	
	// tab类型
	dictionaryKeyList:any[] = [
		{
			name:'检验标本',key:'specimen'
		},
		{
			name:'病理申请单',key:'pathology'
		},
		{
			name:'药品',key:'drugsBag'
		},
		{
			name:'血制品',key:'blood'
		},
		{
			name:'预约检查',key:'subscribe'
		}
	];
	btnLoading1:boolean = false;
	btnLoading2:boolean = false;
	btnLoading3:boolean = false;
	// 是否关联工单
	bindOrder:any = 0;
	// 同步开始时间
	dateRange:any = [];
	// 业务状态
	 transState:any;
	// 目标状态
	completeState:any = 2;
	// 收取时间间隔区间
	arriveStartMinute:any;
	// 收取时间间隔区间
	arriveEndMinute:any;
	// 送达时间间隔区间
	sendStartMinute:any;
	// 送达时间间隔区间
	sendEndMinute:any;
	code:any;
  // 配置
  configs:any = {};
  // 任务类型
  tasktype:any = {};
  searchTimerSubject = 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]);
    });
    this.getSpeDic();
		this.getUsers();
  }
	
	// 点击数据字典key
	activeDictionaryKey:any = 'specimen';
	clickDictionaryKey(item){
	  this.activeDictionaryKey = item.key;
		this.getSpeDic();
		this.resetForm();
	}
	
	onCalendarChangeDate(dateArr){
	  console.log(dateArr)
	  if(dateArr.length == 2){
	    let dateStart = new Date(dateArr[0]);
	    let dateEnd = new Date(dateArr[1]);
	    dateStart.setHours(0,0,0);
	    dateEnd.setHours(23,59,59);
	    this.dateRange = [dateStart,dateEnd];
	  }
	}
	
	// 日期选择
	startDate: string; //发起时间开始
	endDate: string; //发起时间结束
	changeDate(result?): void {
	  if (!result) {
	    this.startDate = this.endDate = "";
	    return;
	  }
	  this.startDate = format(result[0], 'yyyy-MM-dd HH:mm:ss');
	  this.endDate = format(result[1], 'yyyy-MM-dd HH:mm:ss');
	}
	
  // 切换tab
  tabModal(tabModalName:string){
    this.tabModalName = tabModalName;
  }
	
	// 生成数据
	queryNum:any;
	generateModal:boolean = false;
	generateForm(){
		if(!this.startDate || !this.endDate){
			this.msg.error("同步开始时间不能为空");
			return
		}
		if(!this.arriveStartMinute || !this.arriveEndMinute){
			this.msg.error("收取时间间隔区间不能为空");
			return
		}
		if(!this.sendStartMinute || !this.sendEndMinute){
			this.msg.error("送达时间间隔区间不能为空");
			return
		}
		if(this.userIds.length==0){
			this.msg.error("配送人员不能为空");
			return
		}
		this.generateModal = true
	}
	
	hideGenerateModal() {
	  this.generateModal = false;
		this.btnLoading1 = false;
	}
	
	showGenerate:boolean = false;
	generateObj:any;
	confirmGenerate() {
	  var that = this;
	  let list = this.drugStatusList.find(i=> i.id == this.transState)
	  let postData:any = {
	  	patchDataConfig:{
	  		hosId: this.hosId,
	  		bindOrder: this.bindOrder,
	  		transStartTime: this.startDate || undefined,
	  		transEndTime: this.endDate || undefined,
	  		transState: list || undefined,
	  		transType: {
	  			value: this.activeDictionaryKey || undefined
	  		},
				code: this.code || undefined,
	  		completeState: this.completeState,
	  		arriveStartMinute: this.arriveStartMinute || undefined,
	  		arriveEndMinute: this.arriveEndMinute || undefined,
	  		sendStartMinute: this.sendStartMinute || undefined,
	  		sendEndMinute: this.sendEndMinute || undefined,
	  		userIds: this.userIds.length>0 ? this.userIds.join(',') : undefined
	  	}
	  };
	  this.btnLoading1 = true;
	  this.mainService
	    .generateData( postData).subscribe((result:any) => {
	      this.btnLoading1 = false;
	      if (result.state == 200) {
					this.hideGenerateModal()
					this.showNum = false
	        this.showGenerate = true
	        this.generateObj = result.data
					setTimeout(_=>{
						this.scrollContainer.nativeElement.scrollTop = this.scrollContainer.nativeElement.scrollHeight;
					},100)
	      }
	    });
	}
	
  // 查询
	showNum:boolean = false;
  submitForm() {
		if(!this.startDate || !this.endDate){
			this.msg.error("同步开始时间不能为空");
			return
		}
		if(!this.arriveStartMinute || !this.arriveEndMinute){
			this.msg.error("收取时间间隔区间不能为空");
			return
		}
		if(!this.sendStartMinute || !this.sendEndMinute){
			this.msg.error("送达时间间隔区间不能为空");
			return
		}
		if(this.userIds.length==0){
			this.msg.error("配送人员不能为空");
			return
		}
    let list = this.drugStatusList.find(i=> i.id == this.transState)
    let postData:any = {
    	patchDataConfig:{
    		hosId: this.hosId,
    		bindOrder: this.bindOrder,
    		transStartTime: this.startDate || undefined,
    		transEndTime: this.endDate || undefined,
    		transState: list || undefined,
    		transType: {
    			value: this.activeDictionaryKey || undefined
    		},
				code: this.code || undefined,
    		completeState: this.completeState,
    		arriveStartMinute: this.arriveStartMinute || undefined,
    		arriveEndMinute: this.arriveEndMinute || undefined,
    		sendStartMinute: this.sendStartMinute || undefined,
    		sendEndMinute: this.sendEndMinute || undefined,
    		userIds: this.userIds.length>0 ? this.userIds.join(',') : undefined
    	}
    };
    this.btnLoading2 = true;
    this.mainService
      .queryCount( postData).subscribe((result:any) => {
        this.btnLoading2 = false;
        if (result.state == 200) {
					this.showNum = true
					this.showGenerate = false
          this.queryNum = result.data
					setTimeout(_=>{
						this.scrollContainer.nativeElement.scrollTop = this.scrollContainer.nativeElement.scrollHeight;
					},100)
        }
      });
  }
	
	// 重置
	resetForm(){
		this.showNum = false;
		this.showGenerate = false;
		this.bindOrder = 0;
		this.startDate = "";
		this.endDate = "";
		this.dateRange = [];
		this.code = undefined;
		this.transState = undefined;
		this.completeState = 2;
		this.arriveStartMinute = undefined;
		this.arriveEndMinute = undefined;
		this.sendStartMinute = undefined;
		this.sendEndMinute = undefined;
		this.userIds = [];
	}
	
	// 获取字典
	drugStatusList:any = [];
	getSpeDic(){
		let key = null;
		if(this.activeDictionaryKey=='specimen'){
			key = 'speState'
		}else if (this.activeDictionaryKey=='drugsBag'){
			key = 'drug_state'
		}else{
			key = 'blood_trans_state'
		}
		this.mainService.getDictionary("list", key).subscribe((data) => {
			this.drugStatusList = data
		});
	}
	
	// 人员边输边搜节流阀
	changeUser(e) {
	  this.searchTimer(this.getUsers, e);
	}
	
	// 边输入边搜索节流阀
	searchTimer(fun, e) {
	  this.isLoading = true;
	  this.searchTimerSubject.next([fun, e]);
	}
	
	// 配送人员
	userIds:any = [];
	distributionList:any;
	isLoading:boolean = false;
	getUsers(e?) {
	  let postData = {
	    user: {
	      name: e,
	      hospital: { id: this.hosId },
	      simpleQuery: true,
	    },
	    idx: 0,
	    sum: 20,
	  };
	  this.isLoading = true;
	  this.mainService
	    .getFetchDataList("data", "user", postData)
	    .subscribe((data) => {
	      this.isLoading = false;
	      this.distributionList = data.list;
	    });
	}
}