import { Component, OnInit } from "@angular/core";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { MainService } from "src/app/services/main.service";
import { ToolService } from "src/app/services/tool.service";
import { format } from 'date-fns';
import { Validators, FormGroup, FormControl, FormBuilder } from '@angular/forms';
import { ActivatedRoute, Router } from "@angular/router";
import { NzMessageService } from "ng-zorro-antd";

@Component({
  selector: "app-blood-search",
  templateUrl: "./blood-search.component.html",
  styleUrls: ["./blood-search.component.less"],
})
export class BloodSearchComponent implements OnInit {
  constructor(
		private mainService: MainService, 
		private msg: NzMessageService, 
		private tool: ToolService,
		private fb: FormBuilder,
		public route: ActivatedRoute,
	) {}

  searchCriteria = {
    //搜索条件
    bloodCode: "", //血袋号
		applyDept: null,
		arriver: null,
    dateRange: [],
    state: null,
  };
  deptList = []; // 院区下的配送人员列表(搜索框)
  hosId;
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  changeInpSubject = new Subject();
	changeInp2Subject = new Subject();
	changeInpUserSubject = new Subject();
	changeInpPaSubject = new Subject();
  ngOnInit() {
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.searchDept(v);
    });
		
		this.changeInp2Subject.pipe(debounceTime(500)).subscribe((v) => {
		  this.searchUser(v[0], v[1]);
		});
		
		this.changeInpUserSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.getUserList(v);
		});
		
		this.changeInpPaSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.getPatient(v[1], v[0]);
		});
		
		this.getUserList();
		this.getDicList();
    this.getHospital();
  }
  // 搜索类型
  isLoading1 = false;
  types = []; // 类型列表(搜索框)
  searchTypes() {
    this.isLoading1 = true;
    this.mainService.getDictionary("list", "blood_trans_state").subscribe((res) => {
      this.isLoading1 = false;
      this.types = res;
    });
  }
  // 打开搜索框
  changeSearch1(flag) {
    if (flag) {
      this.searchTypes();
    }
  }
	// 打开搜索框
	changeSearch2(flag) {
	  if (flag) {
	    this.changeInp2("no", "search");
	  }
	}
	
	// 搜索患者
	changePatient(e, type){
		this.isLoading = true;
		this.changeInpPaSubject.next([e, type]);
	}	
	
	// 搜索用户
	changeUser(e){
		this.isLoading = true;
		this.changeInpUserSubject.next(e);
	}	
	
	// 获取用户
	userList:any = [];
	getUserList(name?){
		let data = {
		  idx: 0,
		  sum: 20,
		  user: {
		    name: name,
		    hospital: { id: this.hosId || "" },
		  },
		};
		this.mainService
		  .getFetchDataList("data", "user", data)
		  .subscribe((data) => {
		    this.isLoading = false;
		    this.userList = data.list;
		  });
	}
	
	// 获取血型/单位/abo/rh
	bloodTypeList:any = [];
	unitList:any = [];
	aboList:any = [];
	rhList:any = [];
	getDicList(){
		this.mainService.getDictionary("list", "blood_trans_type").subscribe((res) => {
		  this.bloodTypeList = res;
		});
		this.mainService.getDictionary("list", "blood_unit").subscribe((res) => {
		  this.unitList = res;
		});
		this.mainService.getDictionary("list", "abo_type").subscribe((res) => {
		  this.aboList = res;
		});
		this.mainService.getDictionary("list", "rh_type").subscribe((res) => {
		  this.rhList = res;
		});
	}
	
	// 获取患者
	patientList:any = [];
	getPatient(type, patientName?){
		console.log(1234, type, patientName)
		let postData = {
		  idx: 0,
		  sum: 20,
			patient:{
				department:{
					id: type==1 ? this.validateForm.value.applyDept : this.validateAutoForm.value.applyDept
				},
				keyWord: patientName,
			}
		};
		this.mainService.getFetchDataList('nurse', 'patient', postData).subscribe((data) => {
		  this.isLoading = false;
		  if (data["status"] == 200) {
				data["list"].forEach(i=>{
					if(i.bedNum && i.residenceNo){
						i.patientName = i.patientName + '('+ i.bedNum +')' +'-'+ i.residenceNo
					}
					if(i.bedNum && !i.residenceNo){
						i.patientName = i.patientName + '('+ i.bedNum +')'
					}
					if(!i.bedNum && !i.residenceNo){
						i.patientName = i.patientName 
					}
					if(!i.bedNum && i.residenceNo){
						i.patientName = i.patientName +'-'+ i.residenceNo
					}
				})
		    this.patientList = data["list"];
		  }
		});
	}
	
	// 选择申请科室
	onDeptChange(e){
		this.validateForm.controls.patientId.setValue(null)
		this.getPatient(1);
	}
	
	// 选择患者
	onPatientChange(e){
	
	}
	
	//  选择开始时间
	applyDate:any;
	onStartChange(result: Date): void {
		if( typeof result == 'object'){
			this.applyDate = format(result, 'yyyy-MM-dd HH:mm:ss');
			this.validateForm.controls.overDate.setValue(this.applyDate);
		}
	}
	
	// 自动生成
	autoCreateModal:boolean = false;
	autoCreate(){
		this.autoCreateModal = true
		this.initAutoForm()
	}
	
	// 初始化form
	validateAutoForm: FormGroup
	initAutoForm(){
		this.validateAutoForm = this.fb.group({
			applyDept: [null, [Validators.required]],
			sendDept: [null, [Validators.required]],
			patientId: [null, []],
			amount: [1, [Validators.required]],
			sendMsgType: ['noMsg', []],
		});
	}
	
	numChange(e){
		console.log(4, e)
	}
	
	// 选择消息类型
	autoMsgTypeChange(e){
		if(e=='createAndSignMsg'){
			this.validateAutoForm.addControl(
				'arriver',
				new FormControl(null, Validators.required)
			);
		}else{
			this.validateAutoForm.removeControl('arriver');
		}
	}
	
	// 选择申请科室
	onAutoDeptChange(e){
		this.validateAutoForm.controls.patientId.setValue(null)
		this.getPatient(2);
	}
	
	aboName:any;
	onAboChange(e){
		let item = this.aboList.find(i=> i.id == e)
		if(item){
			this.aboName = item.name
		}
	}
	
	unitName:any;
	onUnitChange(e){
		let item = this.unitList.find(i=> i.id == e)
		if(item){
			this.unitName = item.name
		}
	}
	
	rhName:any;
	onRhChange(e){
		let item = this.rhList.find(i=> i.id == e)
		if(item){
			this.rhName = item.name
		}
	}
	
	hideAutoModal(){
		this.autoCreateModal = false
		this.patientList = []
	}
	
	// 自动生成提交
	submitAutoForm(){
		var that = this;
		for (const i in that.validateAutoForm.controls) {
		  that.validateAutoForm.controls[i].markAsDirty();
		  that.validateAutoForm.controls[i].updateValueAndValidity();
		}
		if (that.validateAutoForm.invalid) return;
		let data = {
			blood:{
				applyDept: this.validateAutoForm.value.applyDept,
				sendDept: this.validateAutoForm.value.sendDept,
				patientId: this.validateAutoForm.value.patientId || undefined,
				arriver: this.validateAutoForm.value.arriver || undefined,
				sendMsgType: this.validateAutoForm.value.sendMsgType || undefined
			}
		};
		if(this.validateAutoForm.value.sendMsgType=='createAndSignMsg'){
			data.blood.arriver = this.validateAutoForm.value.arriver
		}else{
			delete data.blood.arriver
		}
		that.btnLoading = true;
		that.mainService
		  .autoMake("blood", this.validateAutoForm.value.amount, data)
		  .subscribe((data:any) => {
		    that.btnLoading = false;
		    that.hideAutoModal();
		    that.initAutoForm();
		    if (data.status == 200) {
		      that.showPromptModal("生成", true, "");
		    } else {
		      that.showPromptModal("生成", false, data.msg);
		    }
		  });
	}
	
	// 新增
	addModal:boolean = false;
	view:boolean = false;
	add:boolean = false;
	addForm(){
		this.addModal = true;
		this.initForm();
	}
	
	hideModal() {
	  this.addModal = false;
		this.patientList = [];
	  this.initForm();
	}
	
	// 初始化form
	validateForm: FormGroup; //新增/编辑表单
	initForm() {
	  this.validateForm = this.fb.group({
	    applyDept: [null, [Validators.required]],
	    sendDept: [null, [Validators.required]],
			useDept: [null, []],
	    patientId: [null, [Validators.required]],
			type: [null, [Validators.required]],
	    volume: [null, [Validators.required]],
	    unit: [null, [Validators.required]],
	    state: ['发血', [Validators.required]],
			aboType: [null, [Validators.required]],
			rhType: [null, [Validators.required]],
			bleedUser: [null, [Validators.required]],
			overDate: [null, [Validators.required]],
			sendMsg: ['0', []],
	  });
	}
	
	// 表单提交
	btnLoading:boolean = false;
	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 = {
			blood:{
				patientId:this.validateForm.value.patientId,
				applyDept: this.validateForm.value.applyDept,
				sendDept: this.validateForm.value.sendDept,
				useDept: this.validateForm.value.useDept,
				bleedUser:this.validateForm.value.bleedUser,
				volume: this.validateForm.value.volume,
				type: {
					id: this.validateForm.value.type
				},
				unit: this.unitName,
				aboType: this.aboName,
				rhType: this.rhName,
				overDate: this.validateForm.value.overDate,
				sendMsg: this.validateForm.value.sendMsg
			}
	  };
		that.btnLoading = true;
	  that.mainService
	    .dataPost("addData", "blood", data)
	    .subscribe((data) => {
	      that.btnLoading = false;
	      that.hideModal();
	      that.initForm();
	      if (data.status == 200) {
	        that.showPromptModal("新增", true, "");
	      } else {
	        that.showPromptModal("新增", false, data.msg);
	      }
	    });
	}
	
	// 批量发送
	batchModal:boolean = false;
	infoContent:any;
	batchSend(){
		if(this.checkedDepIds.length==0){
			this.msg.error('请勾选血制品列表')
			return
		}
		this.infoContent = `您选择了${this.checkedDepIds.length}条血制品信息，确认发送建单消息吗`
		this.batchModal = true
		this.initMsgForm();
	}
	
	// 初始化form
	validateMsgForm: FormGroup
	initMsgForm(){
		this.validateMsgForm = this.fb.group({
			sendMsgType: ['createMsg', [Validators.required]]
		});
	}
	
	// 选择消息发送类型
	msgTypeChange(e){
		if(e=='createAndSignMsg'){
			this.validateMsgForm.addControl(
				'arriver',
				new FormControl(null, Validators.required)
			);
		}else{
			this.validateMsgForm.removeControl('arriver');
		}
	}
	
	// 提交批量消息发送
	submitMsgForm(): void{
		var that = this;
		for (const i in that.validateMsgForm.controls) {
		  that.validateMsgForm.controls[i].markAsDirty();
		  that.validateMsgForm.controls[i].updateValueAndValidity();
		}
		if (that.validateMsgForm.invalid) return;
		let data = {
			blood:{
				ids: this.checkedDepIds.toString(),
				sendMsgType: this.validateMsgForm.value.sendMsgType,
				arriver: this.validateMsgForm.value.arriver,
			}
		};
		if(this.validateMsgForm.value.sendMsgType=='createAndSignMsg'){
			data.blood.arriver = this.validateMsgForm.value.arriver
		}else{
			delete data.blood.arriver
		}
		that.btnLoading = true;
		that.mainService
		  .dataPost("updData", "blood", data)
		  .subscribe((data) => {
		    that.btnLoading = false;
		    that.hideMsgModal();
		    that.initMsgForm();
		    if (data.status == 200) {
					this.mapOfCheckedId = {};
					this.checkedDepIds = [];
		      that.showPromptModal("发送", true, "");
		    } else {
		      that.showPromptModal("发送", false, data.msg);
		    }
		  });
	}
	
	hideMsgModal(){
		this.batchModal = false;
	}
	
  // 重置
  reset() {
    this.searchCriteria = {
      //搜索条件
			applyDept: null,
			arriver: null,
      bloodCode: "",
      dateRange: [],
      state: null,
    };
    this.getList(1);
  }

  // 获取所有院区
  getHospital() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList(1);
    this.getBloodProductsConfig();
  }
  // 血制品页面控制
  bloodProductsConfig:any = {};
  ttconfig_sign_type4:boolean = false;
  getBloodProductsConfig(){
    let postData = {
      "idx": 0,
      "sum": 10,
      "taskTypeConfig": {
          "taskTypeDTO": {
              "hosId": {
                  "id": this.hosId
              },
              "ordinaryField": {
                  "key": "ordinary_field",
                  "value": "blood"
              }
          }
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskTypeConfig", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.bloodProductsConfig = result.list[0] || {};
          this.ttconfig_sign_type4 = this.bloodProductsConfig.signTypeList.some(v => v.value == 4);
        }
      });
  }
  // 查看标本历史记录
  historyPromptModalShow = false; //标本历史记录弹窗开关
  bloodId = ""; //查看历史记录携带
  viewBloodHistory(data) {
    this.bloodId = data.id;
    this.historyPromptModalShow = true;
  }
  // 关闭标本历史记录弹窗
  closeModelHistory(e) {
    this.historyPromptModalShow = JSON.parse(e).show;
  }
  // 打开搜索框
  changeSearch(flag) {
    if (flag) {
      this.changeInp("no");
    }
  }
  // 边输边搜节流阀
  isLoading = false;
  changeInp(dept) {
    // if (!dept) {
    //   return;
    // }
    if (dept === "no") {
      dept = "";
    }
    this.isLoading = true;
    this.changeInpSubject.next(dept);
  }
  // 搜索科室
  searchDept(dept) {
    let postData = {
      department: {
        hospital: { id: this.hosId },
        dept,
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.isLoading = false;
          this.deptList = result.list;
        }
      });
  }
	
	// 边输边搜节流阀
	userKey = "";
	changeInp2(keyword, type) {
	  // if (!keyword) {
	  //   return;
	  // }
	  if (keyword === "no") {
	    keyword = "";
	  }
	  this.userKey = keyword;
	  this.isLoading = true;
	  this.changeInp2Subject.next([keyword, type]);
	}
	
	userSearch:any = [];
	// 搜索科室
	searchUser(keyword, type) {
	  let data = {
	    user: {
	      usertype: { id: 106 },
	      name: keyword,
	      dept: {
	        id: this.searchCriteria.applyDept,
	      },
	    },
	    idx: 0,
	    sum: 10,
	  };
	  this.mainService
	    .getFetchDataList("data", "user", data)
	    .subscribe((data) => {
	      if (data.status == 200) {
	        if (type === "search") {
	          if (this.userKey === keyword) {
	            this.isLoading = false;
	            this.userSearch = data.list;
	          }
	        }
	      }
	    });
	}
	
	
	// 选中表格中科室
	mapOfCheckedId: { [key: string]: boolean } = {};
	checkedDepIds = []; //已选中科室id
	refreshStatus(): void {
	  this.isAllDisplayDataChecked = this.listOfData.every(
	    (item) => this.mapOfCheckedId[item.id]
	  );
	  let arr = [];
	  for (var k in this.mapOfCheckedId) {
	    if (this.mapOfCheckedId[k]) {
	      arr.push(Number(k));
	    }
	  }
	  this.checkedDepIds = arr;
	  console.log(this.checkedDepIds);
	}
	
	//表格整行选中
	selectedListData(id) {
	  this.mapOfCheckedId[id] = !this.mapOfCheckedId[id];
	  this.refreshStatus();
	}
	
	// 全选
	isAllDisplayDataChecked = false; //当前页是否全选
	checkAll(value: boolean): void {
		// let isConformTo = this.listOfData.some(
		//   (item) => item.state.value==1 || item.state.value==4 || item.state.value=='cx'
		// )
		// if(isConformTo){
		// 	this.msg.error('只有“发血、病房接收”状态才能被选择')
		// 	return
		// }
	  this.listOfData.forEach((item) => {
			if(item.state.value!=1 && item.state.value!=4 && item.state.value!='cx'){
				this.mapOfCheckedId[item.id] = value
			}
		});
	  this.refreshStatus();
	}
	
  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let postData: any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      blood: {
        hosId: this.hosId,
				applyDept: this.searchCriteria.applyDept || undefined,
				arriver: this.searchCriteria.arriver || undefined,
        state: this.searchCriteria.state ? { id: this.searchCriteria.state } : undefined,
      },
    };
    if (this.searchCriteria.dateRange.length) {
      postData.blood.printDateStart =
        format(this.searchCriteria.dateRange[0], "yyyy-MM-dd ") + "00:00:00";
      postData.blood.printDateEnd =
        format(this.searchCriteria.dateRange[1], "yyyy-MM-dd ") + "23:59:59";
    }
    if (this.searchCriteria.bloodCode) {
      postData.blood.bloodCode = this.searchCriteria.bloodCode;
    }
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "blood", postData)
      .subscribe((data) => {
        this.loading1 = false;
        if (data["status"] == 200) {
          this.listOfData = data["list"];
          this.listLength = data["totalNum"];
        }
      });
  }
	
	// 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
	promptContent: string; //操作提示框提示信息
	ifSuccess: boolean; //操作成功/失败
	promptInfo: string; //操作结果提示信息
	promptModalShow: boolean; //操作提示框是否展示
	showPromptModal(con, success, promptInfo?) {
	  this.promptModalShow = false;
	  this.promptContent = con;
	  this.ifSuccess = success;
	  this.promptInfo = promptInfo;
	  setTimeout(() => {
	    this.promptModalShow = true;
	  }, 100);
	  this.getList(1);
	}
}

