import { Component, OnInit } from "@angular/core";
import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { format, subDays, endOfDay, startOfDay } from "date-fns";
import { Validators, FormGroup, FormBuilder } from '@angular/forms';
import { ActivatedRoute, Router } from "@angular/router";

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

  currentUserAccount: any = JSON.parse(localStorage.getItem("user")).user.account; //当前登录人账号
  searchCriteria = {
    //搜索条件
    scode: "",
    parent: "",
    hospital: null,
    department: null,
    speState: null,
    receiverName: null,
    dateRange: [],
    checkDept: null,
  };
  types = []; // 类型列表(搜索框)
  departmentSearch = []; // 院区下的科室列表(搜索框)
  userSearch = []; // 院区下的人员列表(搜索框)
  allHospital: any = []; //院区下拉框
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
	hosId:any;
  checkOptionsOne: Array<any> = [
    { label: "服务中心收取", value: "0", checked: true },
  ];
  changeInpSubject = new Subject();
	changeInpUserSubject = new Subject();
  changeInp2Subject = new Subject();
	changeInpPaSubject = new Subject();
	coopBtns:any;

  ngOnInit() {
		this.coopBtns = this.tool.initCoopBtns(this.route);
		this.hosId = this.tool.getCurrentHospital().id;
		// this.searchCriteria.dateRange = [
		// 	format(subDays(new Date(), 7), "yyyy-MM-dd") + ' ' +'00:00:00',
		// 	format(endOfDay(new Date()), "yyyy-MM-dd HH:mm:ss")
		// ]
		// this.startDate = format(subDays(new Date(), 7), "yyyy-MM-dd") + ' ' +'00:00:00';
		// this.endDate = format(endOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.searchDepartment(v[0], v[1]);
    });
    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.getAllHospital();
		this.getProjectList();
  }
  // 表格筛选
  log(value: object[]): void {
    console.log(value);
    this.getList(1, this.sortCurrentKey, this.sortCurrentValue);
  }
	// 关闭弹窗
	closeModel(e){
		this.showModal = JSON.parse(e).show;
	}

	// 查看标本
	speId:any;
	showModal:boolean = false;
	viewSpe(packageId){
		this.speId = packageId;
		this.showModal = true;
	}
  // 搜索类型
  isLoading1 = false;
  searchTypes() {
    this.isLoading1 = true;
    this.mainService.getDictionary("list", "speState").subscribe((res) => {
      this.isLoading1 = false;
      this.types = res;
    });
  }
  // 清空标本
  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  showDelModal(tipsMsg1: string) {
    this.delModal = true;
    this.tipsMsg1 = tipsMsg1;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认
  btnLoading: boolean = false; //提交按钮loading状态
  confirmDel() {
    this.btnLoading = true;
    this.mainService
      .coopDataM("api/emptySpecimenData", { hosId: 1, isEmpty: "ok" })
      .subscribe((data) => {
        this.btnLoading = false;
        this.delModal = false;
        if (data.status == 200) {
          this.showPromptModal("标本清空", true, "");
        } else {
          this.showPromptModal("标本清空", false, "");
        }
      });
  }
  // 展示信息提示框（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, this.sortCurrentKey, this.sortCurrentValue);
  }
  // 查看标本历史记录
  historyPromptModalShow = false; //标本历史记录弹窗开关
  scode = ""; //查看历史记录携带
  viewSpecimenHistory(data) {
    this.scode = data.scode;
    this.historyPromptModalShow = true;
  }
  // 关闭标本历史记录弹窗
  closeModelHistory(e) {
    this.historyPromptModalShow = JSON.parse(e).show;
  }
  // 日期选择
  startDate: string; //发起时间开始
  endDate: string; //发起时间结束
	changeDate(result?): void {
	  if (result.length==0) {
	    this.startDate = this.endDate = null;
	    return;
	  }
	  this.startDate = format(result[0], 'yyyy-MM-dd HH:mm:ss');
	  this.endDate = format(result[1], 'yyyy-MM-dd HH:mm:ss');
    this.searchCriteria.dateRange = [this.startDate, this.endDate];
	}
	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.searchCriteria.dateRange = [dateStart,dateEnd];
	  }
	}

	// 搜索患者
	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;
		  });
	}

	// 获取检验项目
	projectList:any = [];
	getProjectList(){
	let data = {
		idx: 0,
		sum: 9999,
		dictionary: {
			key: "examination_items",
		},
	};
	this.loading1 = true;
	this.mainService
		.getFetchDataList("simple/data", "dictionary", data)
		.subscribe((data) => {
			this.loading1 = false;
			if (data.status == 200) {
				this.projectList = data.list || [];
			}
		});
	}

	// 获取患者
	patientList:any = [];
	getPatient(type, patientName?){
		let postData = {
		  idx: 0,
		  sum: 20,
			patient:{
				department:{
					id: type==1 ? this.validateForm.value.sickRoom : this.validateAutoForm.value.sickRoom
				},
				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"];
		  }
		});
	}

	// 选择检验项目
	stypeId:any;
	tubeTypeId:any;
	onExamineChange(e){
		let item = this.projectList.find(i => i.id == e);
		if(item){
			this.validateForm.controls.stype.setValue(item.dictionaryDTO.name)
			this.validateForm.controls.tubeType.setValue(item.extra5DTO.name)
			this.stypeId = item.dictionaryDTO.id
			this.tubeTypeId = item.extra5DTO.id
		}else{
			this.validateForm.controls.stype.setValue(null)
			this.validateForm.controls.tubeType.setValue(null)
			this.stypeId = null
			this.tubeTypeId = null
		}
	}

	onAutoExamineChange(e){

	}

	// 选择申请科室
	onDeptChange(e){
		this.validateForm.controls.patientId.setValue(null)
		this.getPatient(1);
	}

	// 选择患者
	onPatientChange(e){

	}

	//  选择开始时间
	applyDate:any;
	onApplyChange(result: Date): void {

	}

	// 自动生成
	autoCreateModal:boolean = false;
	autoCreate(){
		this.autoCreateModal = true
		this.initAutoForm()
	}

	// 初始化form
	validateAutoForm: FormGroup
	initAutoForm(){
		this.validateAutoForm = this.fb.group({
			sickRoom: [null, [Validators.required]],
			patientId: [null, []],
			examinationItemsId: [null, []],
			amount: [1, [Validators.required]],
			urgent: [null, []],
			sendMsg: ['0', []],
		});
	}

	numChange(e){
		console.log(4, e)
	}

	// 选择申请科室
	onAutoDeptChange(e){
		this.validateAutoForm.controls.patientId.setValue(null)
		this.getPatient(2);
	}

	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 = {
			specimen:{
				sickRoom: this.validateAutoForm.value.sickRoom,
				patientId: this.validateAutoForm.value.patientId || undefined,
				examinationItemsId: this.validateAutoForm.value.examinationItemsId || undefined,
				urgent: this.validateAutoForm.value.urgent || undefined,
				sendMsg: this.validateAutoForm.value.sendMsg || undefined
			}
		};
		that.btnLoading = true;
		that.mainService
		  .autoMake("specimen", 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);
		    }
		  });
	}

	// 设置核收
	collectModal:boolean = false;
	itemData:any;
	collect(e, data){
		this.itemData = data;
		this.collectModal = true
		this.initCollectForm()
	}

	// 初始化form
	validateCollectForm: FormGroup
	initCollectForm(){
		this.validateCollectForm = this.fb.group({
			collect: [null, [Validators.required]],
			sendMsg: ['0', [Validators.required]],
		});
	}

	hideCollectModal(){
		this.collectModal = false
	}

	// 设置核收提交
	submitCollectForm(){
		var that = this;
		for (const i in that.validateCollectForm.controls) {
		  that.validateCollectForm.controls[i].markAsDirty();
		  that.validateCollectForm.controls[i].updateValueAndValidity();
		}
		if (that.validateCollectForm.invalid) return;
		let data = {
			specimen:{
				operationType: 'checkCollect',
				id: this.itemData.id,
				checkCollectUserId: this.validateCollectForm.value.collect,
				sendMsg: this.validateCollectForm.value.sendMsg
			}
		};
		that.btnLoading = true;
		that.mainService
		  .dataPost("updData", "specimen", data)
		  .subscribe((data) => {
		    that.btnLoading = false;
		    that.hideCollectModal();
		    that.initCollectForm();
		    if (data.status == 200) {
		      that.showPromptModal("操作", true, "");
		    } else {
		      that.showPromptModal("操作", false, data.msg);
		    }
		  });
	}

	// 消息发送
	sendModal:boolean = false;
	tipsMsg2:any = '您确定要发送消息吗？';
	send(e, data){
		this.itemData = data;
		this.sendModal = true;
	}

	hideSendModal(){
		this.sendModal = false;
	}

	// 确定发送消息
	confirmSend(){
		let data = {
			specimen:{
				operationType: 'sendMessage',
				id: this.itemData.id,
			}
		};
		this.btnLoading = true;
		this.mainService
		  .dataPost("updData", "specimen", data)
		  .subscribe((data) => {
		    this.btnLoading = false;
				this.sendModal = false;
		    if (data.status == 200) {
		      this.showPromptModal("操作", true, "");
		    } else {
		      this.showPromptModal("操作", false, data.msg);
		    }
		  });
	}

	// 新增
	addModal:boolean = false;
	view: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({
	    sickRoom: [null, [Validators.required]],
	    checkDept: [null, [Validators.required]],
	    patientId: [null, [Validators.required]],
			examinationItemsId: [null, [Validators.required]],
	    stype: [null, [Validators.required]],
	    tubeType: [null, [Validators.required]],
	    speState: ['已采集', [Validators.required]],
			urgent: ['0', [Validators.required]],
			collectNurseId: [null, []],
			sendMsg: ['0', []],
	  });
	}

	// 表单提交
	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 = {
			specimen:{
				patientId:this.validateForm.value.patientId,
				checkDept: {
					id: this.validateForm.value.checkDept
				},
				sickRoom: {
					id: this.validateForm.value.sickRoom
				},
				collectNurseId: this.validateForm.value.collectNurseId || undefined,
				urgent: this.validateForm.value.urgent,
				examinationItemsId: this.validateForm.value.examinationItemsId,
				stype: {
					id: this.stypeId
				},
				tubeType: {
					id: this.tubeTypeId
				},
				sendMsg: this.validateForm.value.sendMsg
			}
	  };
		that.btnLoading = true;
	  that.mainService
	    .dataPost("addData", "specimen", data)
	    .subscribe((data) => {
	      that.btnLoading = false;
	      that.hideModal();
	      that.initForm();
	      if (data.status == 200) {
	        that.showPromptModal("新增", true, "");
	      } else {
	        that.showPromptModal("新增", false, data.msg);
	      }
	    });
	}

  // 重置
  reset() {
    this.searchCriteria = {
      //搜索条件
      scode: "",
      parent: "",
      hospital: this.allHospital[0] ? this.allHospital[0]["id"] + "" : null,
      department: null,
      speState: null,
      receiverName: null,
      dateRange: [],
      checkDept: null,
    };
		this.startDate = null;
		this.endDate = null;
    this.sortCurrentKey = "";
    this.sortCurrentValue = "";
    this.sortCurrent = {
      arrive_time: null,
    };
    this.getList(1, this.sortCurrentKey, this.sortCurrentValue);
  }
  // 选择院区
  changeHospital(id, type) {
    if (type === "search") {
      this.searchCriteria.department = null;
    }
  }
  // 打开搜索框
  changeSearch1(flag) {
    if (flag) {
      this.searchTypes();
    }
  }
  // 打开搜索框
  changeSearch(flag) {
    if (flag) {
      this.changeInp("no", "search");
    }
  }
  // 打开搜索框
  changeSearch2(flag) {
    if (flag) {
      this.changeInp2("no", "search");
    }
  }
  // 边输边搜节流阀
  isLoading = false;
  deptKey = "";
  changeInp(dept, type) {
    if (!dept) {
      return;
    }
    if (dept === "no") {
      dept = "";
    }
    this.deptKey = dept;
    this.isLoading = true;
    this.changeInpSubject.next([dept, type]);
  }
  // 搜索科室
  searchDepartment(dept, type) {
    let data = {
      department: {
        dept,
        hospital: {
          id: this.searchCriteria.hospital,
        },
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("data", "department", data)
      .subscribe((data) => {
        if (data.status == 200) {
          if (type === "search") {
            if (this.deptKey === dept) {
              this.isLoading = false;
              this.departmentSearch = data.list;
            }
          }
        }
      });
  }
  // 边输边搜节流阀
  userKey = "";
  changeInp2(keyword, type) {
    if (!keyword) {
      return;
    }
    if (keyword === "no") {
      keyword = "";
    }
    this.userKey = keyword;
    this.isLoading = true;
    this.changeInp2Subject.next([keyword, type]);
  }
  // 搜索科室
  searchUser(keyword, type) {
    let data = {
      user: {
        usertype: { id: 106 },
        name: keyword,
        hospital: {
          id: this.searchCriteria.hospital,
        },
      },
      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;
            }
          }
        }
      });
  }

  // 获取所有院区
  /**
   *
   *
   * @memberof RoundRobinComponent
   */
  getAllHospital() {
    this.allHospital = [this.tool.getCurrentHospital()];
    this.searchCriteria.hospital = this.tool.getCurrentHospital().id + "";
    this.getList(1, this.sortCurrentKey, this.sortCurrentValue);
    this.changeHospital(this.searchCriteria.hospital, "search");
  }

  // 表格数据
  loading1 = false;
  getList(type, field?: string, sort?: string) {
    console.log(this.searchCriteria.dateRange);
    if (type == 1) {
      this.pageIndex = 1;
    }
    let postData: any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      specimen: {
        receivedMark: this.checkOptionsOne[0].checked ? 1 : undefined,
        hosId: this.searchCriteria.hospital,
        sickRoom: this.searchCriteria.department
          ? {
              id: this.searchCriteria.department,
            }
          : undefined,
        checkDept: this.searchCriteria.checkDept
          ? {
              id: this.searchCriteria.checkDept,
            }
          : undefined,
        receiverName: this.searchCriteria.receiverName
          ? this.searchCriteria.receiverName
          : undefined,
        scode: !this.searchCriteria.scode
          ? undefined
          : this.searchCriteria.scode,
        keyWord: !this.searchCriteria.parent
          ? undefined
          : this.searchCriteria.parent,
        speState: this.searchCriteria.speState
          ? { id: this.searchCriteria.speState }
          : undefined,
				startArriveTime: this.startDate || undefined,
				endArriveTime: this.endDate || undefined,
      },
    };
    if (field && sort) {
      postData.specimen.orderBy = sort === "ascend" ? field : `${field} desc`;
    }
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "specimen", postData)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }
      });
  }

  // 列表排序
  sortCurrent = {
    arrive_time: null,
  };
  sortCurrentKey: string = "";
  sortCurrentValue: string | null = "";
  sort(e) {
    const { key, value } = e;
    this.sortCurrentKey = key;
    this.sortCurrentValue = value;
    this.getList(this.pageIndex, this.sortCurrentKey, this.sortCurrentValue);
  }
}
