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 } from "date-fns";
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup, FormControl } from "@angular/forms";
@Component({
  selector: "app-operation-search",
  templateUrl: "./operation-search.component.html",
  styleUrls: ["./operation-search.component.less"],
})
export class OperationSearchComponent implements OnInit {
  constructor(
		private mainService: MainService, 
		private tool: ToolService,
		public route: ActivatedRoute,
		private router: Router,
		private fb: FormBuilder,
	) {}

  currentUserAccount: any = JSON.parse(localStorage.getItem("user")).user.account; //当前登录人账号
  searchCriteria = {
    //搜索条件
		firstOperation:false,
    hospital: null,
    department: null,
    speState: null,
    dateRange: [],
    departmentRoom: null,
  };
  types = []; // 类型列表(搜索框)
  departmentSearch = []; // 院区下的科室列表(搜索框)
  userSearch = []; // 院区下的人员列表(搜索框)
  allHospital: any = []; //院区下拉框
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  checkOptionsOne: Array<any> = [
    { label: "服务中心收取", value: "0", checked: true },
  ];
  changeInpSubject = new Subject();
  changeInpUserSubject = new Subject();
	changeDeptInpSubject = new Subject();
	changeRoomInpSubject = new Subject();
	changeDoctorSubject = new Subject();
	validateForm: FormGroup; //新增/编辑表单
	coopBtns:any;
	hosId:any;
	
  ngOnInit() {
		this.coopBtns = this.tool.initCoopBtns(this.route);
		this.hosId = this.tool.getCurrentHospital().id;
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getPatient(v);
    });
    this.changeInpUserSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getUserList(v);
    });
		this.changeDeptInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.searchDepartment(v);
		});
		this.changeRoomInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.operatingRoom(v[0], v[1]);
		});
		this.getPatient();
		this.getUserList();
		this.operatingRoom('', '');
		this.searchDepartment('');
		this.searchTypes();
    this.getAllHospital();
  }
	
	// 搜索患者
	changePatient(e){
		this.isLoading = true;
		this.changeInpSubject.next(e);
	}	
	
	// 搜索用户
	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;
		  });
	}
	
	// 获取患者
	patientList:any = [];
	getPatient(patientName?){
		let postData = {
		  idx: 0,
		  sum: 20,
		  hosId: this.hosId,
		  patientName: patientName,
		};
		this.mainService.listMsgByMain('listPatient',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"];
		  }
		});
	}
	
	// 选择患者
	onPatientChange(e){
		console.log(2222, e)
		let item = this.patientList.find(i=>i.id == e)
		console.log(777,item)
		if(item){
			if(item.department){
				let list = this.departmentSearch.find(i =>i.id == item.department.id)
				if(list){
					this.validateForm.controls.areaDept.setValue(item.department.id)
				}else{
					this.departmentSearch.push({
						dept: item.department.dept,
						id: item.department.id
					})
					this.validateForm.controls.areaDept.setValue(item.department.id)
				}
			}else{
				this.validateForm.controls.areaDept.setValue(null)
			}
		}
	}
	
	//  选择开始时间
	applyDate:any;
	onApplyChange(result: Date): void {
		this.applyDate = format(result, 'yyyy-MM-dd HH:mm');
		console.log('Selected Time: ', this.applyDate );
		this.validateForm.controls.applyDate.setValue(this.applyDate + ':00');
	}
	
	//  选择开始时间
	printDate:any;
	onOperationChange(result: Date): void {
		this.printDate = format(result, 'yyyy-MM-dd HH:mm');
		console.log('Selected Time: ', this.printDate );
		this.validateForm.controls.printDate.setValue(this.printDate + ':00');
	}
	
	// 新增弹框
	add:boolean = true;
	modal:boolean = false;
	addMoadl() {
	  this.add = true;
		this.view = false;
		this.modal = true;
		this.itemData = null;
		this.getUserList();
	  this.initForm();
	}
	hideModal() {
	  this.modal = false;
	  this.initForm();
	}
	
	// 初始化新增form表单
	initForm() {
	  this.validateForm = this.fb.group({
			patientName:[null, [Validators.required]],
	    patientPhone: [null, []],
	    patientFamilyPhone: [null, []],
			applyDate: [null, [Validators.required]],
	    printDate: [null, [Validators.required]],
	    firstOperation: ['0', [Validators.required]],
			areaDept: [null, [Validators.required]],
			surgeryDept: [null, [Validators.required]],
			// surgeryName: [null, [Validators.required]],
			doctorId: [null, []],
			docAssistantInfos: [null, []],
			itinerantNurseId: [null, []],
			nurseId: [null, []],
			state: [null, [Validators.required]],
			type: [null, [Validators.required]],
	  });
	}
		
	// 表单提交
	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 = {
			surgery:{
				...this.itemData,
				patientDTO:{
					id: this.validateForm.value.patientName
				},
				patientPhone: this.validateForm.value.patientPhone || undefined,
				patientFamilyPhone: this.validateForm.value.patientFamilyPhone || undefined,
				applyDate: this.validateForm.value.applyDate,
				printDate: this.validateForm.value.printDate,
				firstOperation: this.validateForm.value.firstOperation,
				areaDept: this.validateForm.value.areaDept,
				surgeryDept: this.validateForm.value.surgeryDept,
				// surgeryName: this.validateForm.value.surgeryName,
				doctorId: this.validateForm.value.doctorId,
				docAssistantInfos: this.validateForm.value.docAssistantInfos ? this.validateForm.value.docAssistantInfos.join(",") : undefined,
				itinerantNurseId: this.validateForm.value.itinerantNurseId || undefined,
				nurseId: this.validateForm.value.nurseId || undefined,
				state:{
					id:this.validateForm.value.state,
				},
				type:{
					id:this.validateForm.value.type,
				},
				id:0,
			}
	  };
	  if (!that.add) {
	    data.surgery.id = that.coopId;
	  }else{
			delete data.surgery.id
		}
		that.btnLoading = true;
	  that.mainService
	    .dataPost(this.add ? "addData":"updData", "surgery", data)
	    .subscribe((data) => {
	      that.btnLoading = false;
	      that.hideModal();
	      that.initForm();
	      if (data.status == 200) {
	        that.showPromptModal(that.add ? "新增" : "编辑", true, "");
	      } else {
	        that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
	      }
	    });
	}
	
	// 查看
	view:boolean = false
	detail(e, data){
		this.view = true;
		this.initForm();
		this.itemData = data;
		this.coopId = data.id;
		this.setForm(data)
	}
	
	// 编辑
	itemData:any;
	coopId:any;
	edit(e, data) {
		this.view = false;
		this.add = false
		this.initForm();
		this.getUserList();
		this.itemData = data;
		this.coopId = data.id;
		this.setForm(data)
	}
	
	// 数据回显
	setForm(data){
		if(data.patientDTO){
			let item = this.patientList.find(i => i.id == data.patientDTO.id)
			if(item){
				this.validateForm.controls.patientName.setValue(data.patientDTO.id);
			}else{
				let i = data.patientDTO
				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.push({
					patientName: i.patientName,
					id: data.patientDTO.id,
					department: i.department
				})
				this.validateForm.controls.patientName.setValue(data.patientDTO.id);
			}
		}
		this.validateForm.controls.patientPhone.setValue(data.patientPhone);
		this.validateForm.controls.patientFamilyPhone.setValue(data.patientFamilyPhone);
		this.validateForm.controls.applyDate.setValue(data.applyDate)
		this.validateForm.controls.printDate.setValue(data.printDate);
		this.validateForm.controls.firstOperation.setValue(data.firstOperation+"");
		if(data.areaDeptDTO){
			let item = this.departmentSearch.find(i => i.id == data.areaDeptDTO.id)
			if(item){
				this.validateForm.controls.areaDept.setValue(data.areaDeptDTO.id);
			}else{
				this.departmentSearch.push({
					dept: data.areaDeptDTO.dept,
					id: data.areaDeptDTO.id
				})
				this.validateForm.controls.areaDept.setValue(data.areaDeptDTO.id);
			}
		}
		if(data.surgeryDeptDTO){
			let item = this.operatingRoomDept.find(i => i.id == data.surgeryDeptDTO.id)
			if(item){
				this.validateForm.controls.surgeryDept.setValue(data.surgeryDeptDTO.id);
			}else{
				this.operatingRoomDept.push({
					dept: data.surgeryDeptDTO.dept,
					id: data.surgeryDeptDTO.id
				})
				this.validateForm.controls.surgeryDept.setValue(data.surgeryDeptDTO.id);
			}
		}
		if(data.doctorId){
			let item = this.userList.find(i => i.id == data.doctorId)
			if(item){
				this.validateForm.controls.doctorId.setValue(data.doctorId);
			}else{
				this.userList.push({
					name: data.doctorName,
					id: data.doctorId
				})
				this.validateForm.controls.doctorId.setValue(data.doctorId);
			}
		}
		if(data.docAssistantInfos){
			let arr = data.docAssistantInfos.split(";")
			let arr2 = data.assistantDoctorName.split(";")
			let docAssistantInfosArr = []
			for(let i = 0; i<arr.length; i++){
				arr[i] = Number(arr[i])
				docAssistantInfosArr.push({
					name: arr2[i],
					id: arr[i]
				})
			}
			docAssistantInfosArr.forEach(i=> {
				let item = this.userList.find(x => x.id == i.id)
				if(!item){
					this.userList.push({
						name: i.name,
						id: i.id
					})
				}
			})
			this.validateForm.controls.docAssistantInfos.setValue(arr);
		}
		if(data.itinerantNurseId){
			let item = this.userList.find(i => i.id == data.itinerantNurseId)
			if(item){
				this.validateForm.controls.itinerantNurseId.setValue(data.itinerantNurseId);
			}else{
				this.userList.push({
					name: data.itinerantNurseName,
					id: data.itinerantNurseId
				})
				this.validateForm.controls.itinerantNurseId.setValue(data.itinerantNurseId);
			}
		}
		if(data.nurseId){
			let item = this.userList.find(i => i.id == data.nurseId)
			if(item){
				this.validateForm.controls.nurseId.setValue(data.nurseId);
			}else{
				this.userList.push({
					name: data.nurseName,
					id: data.nurseId
				})
				this.validateForm.controls.nurseId.setValue(data.nurseId);
			}
		}
		this.validateForm.controls.state.setValue(data.state && data.state.id || null);
		this.validateForm.controls.type.setValue(data.type && data.type.id || null);
		this.modal = true
	}
	
	// 查看日志
	logModal:boolean = false;
	viewLog(e, data){
		this.view = false;
		this.add = false;
		this.itemData = data;
		this.logModal = true;
	}
	
	hideLogModal(){
		this.logModal = false;
	}
	
  // 表格筛选
  log(value: object[]): void {
    console.log(value);
    this.getList(1, this.sortCurrentKey, this.sortCurrentValue);
  }
  // 搜索类型
  isLoading1 = false;
	operationType:any = [];
  searchTypes() {
    this.isLoading1 = true;
    this.mainService.getDictionary("list", "surgery_trans_state").subscribe((res) => {
      this.isLoading1 = false;
      this.types = res;
    });
		this.mainService.getDictionary("list", "surgery_trans_type").subscribe((res) => {
		  this.isLoading1 = false;
		  this.operationType = 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(0, 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) {
      this.startDate = this.endDate = "";
      return;
    }
		this.startDate = format(result[0], "yyyy-MM-dd ") + "00:00:00";
		this.endDate = format(result[1], "yyyy-MM-dd ") + "23:59:59";
  }
  // 重置
  reset() {
    this.searchCriteria = {
      //搜索条件
      hospital: this.allHospital[0] ? this.allHospital[0]["id"] + "" : null,
			firstOperation:false,
			department: null,
			speState: null,
			dateRange: [],
			departmentRoom: null,
    };
		this.startDate = null;
		this.endDate = 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.changeDeptInp("no", "search");
    }
  }
  // 打开搜索框
  changeSearch2(flag) {
    if (flag) {
      this.changeOperatingRoomInp("no", "search");
    }
  }
	
	changeDoctor(name){
		this.isLoading = true;
		this.changeDoctorSubject.next(name);
	}
	
  // 边输边搜节流阀
  isLoading = false;
  deptKey = "";
  changeDeptInp(dept, type?) {
    if (!dept) {
      return;
    }
    if (dept === "no") {
      dept = "";
    }
    this.deptKey = dept;
    this.isLoading = true;
    this.changeDeptInpSubject.next(dept);
  }
	
	changeOperatingRoomInp(dept, type) {
    if (!dept) {
      return;
    }
    if (dept === "no") {
      dept = "";
    }
    this.deptKey = dept;
    this.isLoading = true;
    this.changeRoomInpSubject.next([dept, type]);
  }
	
  // 搜索科室
  searchDepartment(dept) {
    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) {
					this.isLoading = false;
					this.departmentSearch = data.list;
        }
      });
  }
	
	// 手术室
	operatingRoomDept:any;
	operatingRoom(dept, type) {
		var that = this;
		that.mainService.getDictionary("list", "dept_type").subscribe((res2) => {
			let item1 = res2.find(i=>i.name=='手术室科室')
			let data1 = {
			  idx: 0,
			  sum: 9999,
			  department: {
					dept,
			    hospital: { id: that.searchCriteria.hospital || "" },
			    type: { id: item1.id || "" },
			  },
			};

			that.mainService
			  .getFetchDataList("data", "department", data1)
			  .subscribe((res) => {
					this.isLoading = false;
					that.operatingRoomDept = res.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) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let postData: any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      surgery: {
				applyDateStart: this.startDate,
				applyDateEnd: this.endDate,
				platform: 'list',
        firstOperation: this.searchCriteria.firstOperation ? 1 : undefined,
        hosId: this.searchCriteria.hospital,
        areaDept: this.searchCriteria.department ? this.searchCriteria.department :undefined,
				surgeryDept: this.searchCriteria.departmentRoom ? this.searchCriteria.departmentRoom : undefined,
        state: this.searchCriteria.speState
          ? { value: this.searchCriteria.speState }
          : undefined,
      },
    };

    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "surgery", 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);
  }
}
