import { Component, OnInit, ViewChild, ElementRef } from "@angular/core";
import { MainService } from "src/app/services/main.service";
import { ToolService } from "src/app/services/tool.service";
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { ActivatedRoute } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: "app-patient-search",
  templateUrl: "./patient-search.component.html",
  styleUrls: ["./patient-search.component.less"],
})
export class PatientSearchComponent implements OnInit {
  @ViewChild("remarkEle", { static: false }) remarkEle: ElementRef;
  constructor(
    private mainService: MainService,
    private tool: ToolService,
    private route: ActivatedRoute,
    private fb: FormBuilder,
  ) {}

  hosId = this.tool.getCurrentHospital().id; //当前院区

  searchCriteria:any = {};
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  changeInpSubject = new Subject();

  // 初始化增删改按钮
  coopBtns: any = {};

  ngOnInit() {
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[1] === 'department'){
        this.getDepartmentList(v[0]);
      }else if(v[1] === 'departmentSearch'){
        this.getDepartmentSearchList(v[0]);
      }
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.searchCriteria.hosId = this.tool.getCurrentHospital().id;
    this.getList(1);
    this.getGenderList();
    this.getCareLevelList();
    this.getIllnessStateList();
    this.getPatientTypeList();
    this.getHospitalList();
    this.getHospitalSearchList();
  }

  // 获取院区列表
  hospitalList = [];
  getHospitalList() {
    this.hospitalList = this.tool.getHospitalList();
  }

  changeHospital(e){
    this.deptList = [];
    this.validateForm.controls.department.setValue(null);

    this.tripTypeList = [];
    this.validateForm.controls.tripType.setValue(null);
  }

  // 获取院区列表
  hospitalSearchList = [];
  getHospitalSearchList() {
    this.hospitalSearchList = this.tool.getHospitalList();
  }

  changeHospitalSearch(e){
    this.deptSearchList = [];
    this.searchCriteria.department = undefined;
  }

  // 搜索科室
  deptList = []; // 院区下的科室列表(搜索框)
  isLoading = false;
  getDepartmentList(dept) {
    let data = {
      department: {
        searchType: 1,// 简单查询
        dept,
        hospital: {
          id: this.validateForm.value.hosId,
        },
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("simple/data", "department", data)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.deptList = data.list;
        }else{
          this.deptList = [];
        }
      });
  }

  // 搜索科室
  deptSearchList = []; // 院区下的科室列表(搜索框)
  getDepartmentSearchList(dept) {
    let data = {
      department: {
        searchType: 1,// 简单查询
        dept,
        hospital: {
          id: this.searchCriteria.hosId,
        },
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("simple/data", "department", data)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.deptSearchList = data.list;
        }else{
          this.deptSearchList = [];
        }
      });
  }
  changeInp(dept, type) {
    this.isLoading = true;
    this.changeInpSubject.next([dept, type]);
  }
  // 打开搜索框
  openDepartment(flag) {
    if (flag) {
      this.changeInp("", "department");
    }
  }
  // 打开搜索框
  openDepartmentSearch(flag) {
    if (flag) {
      this.changeInp("", "departmentSearch");
    }
  }
  // 打开搜索框
  openTripType(flag) {
    if (flag) {
      this.getTripTypeList();
    }
  }
  // 重置
  reset() {
    this.searchCriteria = {
      hosId: this.tool.getCurrentHospital().id,
    };
    this.getList(1);
  }

  // 查看标本历史记录
  historyPromptModalShow = false; //标本历史记录弹窗开关
  scode = ""; //查看历史记录携带
  viewSpecimenHistory(data) {
    this.scode = data.scode;
    this.historyPromptModalShow = true;
  }
  // 关闭标本历史记录弹窗
  closeModelHistory(e) {
    this.historyPromptModalShow = JSON.parse(e).show;
  }

  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let postData = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      hosId: this.searchCriteria.hosId,
      patientName: this.searchCriteria.patientName,
      department: this.searchCriteria.department || undefined,
      careLevel: this.searchCriteria.careLevel || undefined,
      illnessState: this.searchCriteria.illnessState || undefined,
      patientType: this.searchCriteria.patientType || undefined,
    };
    this.loading1 = true;
    this.mainService.listMsgByMain('listPatient',postData).subscribe((data) => {
      this.loading1 = false;
      if (data["status"] == 200) {
        this.listOfData = data["list"];
        this.listLength = data["totalNum"];
      }
    });
  }

  // 新增弹框
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  showModal() {
    this.add = true;
    this.modal = true;
    this.initForm();
    this.validateForm.controls.hosId.setValue(this.searchCriteria.hosId);
  }
  hideModal() {
    this.modal = false;
  }

  // 初始化新增form表单
  initForm() {
    if (this.add) {
      this.deptList = [];
    }
    this.validateForm = this.fb.group({
      patientName: ['', [Validators.required]],
			gender: [null],
			age: [undefined],
			patientCode: ['', [Validators.required]],
			residenceNo: ['', [Validators.required]],
			barCode: ['', [Validators.required]],
			bedNum: [''],
			patientPhone: [''],
      hosId: [null, [Validators.required]],
      department: [null, [Validators.required]],
      careLevel: [null, [Validators.required]],
      illnessState: [null],
      patientType: [null, [Validators.required]],
      tripType: [null],
      remark: [null],
    });
  }
  // 表单提交
  btnLoading: boolean = false; //提交按钮loading状态
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty({ onlySelf: true });
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.btnLoading = true;
    let postData = {};
    if(this.add){
			postData = {
        patient: {
          hosId: this.validateForm.value.hosId,
          patientName: this.validateForm.value.patientName,
          gender: {
            id: this.validateForm.value.gender
          },
          age: this.validateForm.value.age,
          patientCode: this.validateForm.value.patientCode,
          residenceNo: this.validateForm.value.residenceNo,
          barCode: this.validateForm.value.barCode,
          bedNum: this.validateForm.value.bedNum,
					patientPhone: this.validateForm.value.patientPhone || undefined,
          department: {
            id: this.validateForm.value.department,
          },
          careLevel: {
            id: this.validateForm.value.careLevel,
          },
          illnessState: this.validateForm.value.illnessState ? {
            id: this.validateForm.value.illnessState,
          } : undefined,
          patientType: {
            id: this.validateForm.value.patientType,
          },
          tripType:  this.validateForm.value.tripType || undefined,
          remark:  this.validateForm.value.remark || undefined,
        }
      }
    }else{
			postData = {
        patient: {
          ...this.coopData,
          hosId: this.validateForm.value.hosId,
          patientName: this.validateForm.value.patientName,
          gender: {
            id: this.validateForm.value.gender
          },
          age: this.validateForm.value.age,
          patientCode: this.validateForm.value.patientCode,
          residenceNo: this.validateForm.value.residenceNo,
          barCode: this.validateForm.value.barCode,
          bedNum: this.validateForm.value.bedNum,
					patientPhone: this.validateForm.value.patientPhone || undefined,
          department: {
            id: this.validateForm.value.department,
          },
          careLevel: {
            id: this.validateForm.value.careLevel,
          },
          illnessState: this.validateForm.value.illnessState ? {
            id: this.validateForm.value.illnessState,
          } : undefined,
          patientType: {
            id: this.validateForm.value.patientType,
          },
          tripType:  this.validateForm.value.tripType || undefined,
          remark:  this.validateForm.value.remark || undefined,
        }
      }
    }

    this.mainService
      .coopData("addData", "patient", postData)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideModal();
        if (data.status == 200) {
          this.showPromptModal(this.add ? "新增" : "编辑", true, "");
        } else{
					this.showPromptModal(this.add ? "新增" : "编辑", false, data.msg);
				}
      });
  }

  // 展示信息提示框（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);
  }

  // 编辑
  maskFlag:any = false;
  coopData:any = {};
  edit(data) {
    this.initForm();
    this.validateForm.controls.hosId.setValue(data.hosId);
    this.validateForm.controls.patientName.setValue(data.patientName);
    if(data.gender){
			this.validateForm.controls.gender.setValue(data.gender.id);
		}else{
      this.validateForm.controls.gender.setValue(null);
    }
    this.validateForm.controls.age.setValue(data.age);
    this.validateForm.controls.patientCode.setValue(data.patientCode);
    this.validateForm.controls.residenceNo.setValue(data.residenceNo);
    this.validateForm.controls.barCode.setValue(data.barCode);
    this.validateForm.controls.bedNum.setValue(data.bedNum);
		
		if(data.patientPhone){
		  this.validateForm.controls.patientPhone.setValue(data.patientPhone);
		}else{
		  this.validateForm.controls.patientPhone.setValue(null);
		}
    if(data.department){
      this.deptList = [data.department];
      this.validateForm.controls.department.setValue(data.department.id);
    }else{
      this.validateForm.controls.department.setValue(null);
    }
    if(data.careLevel){
      this.validateForm.controls.careLevel.setValue(data.careLevel.id);
    }else{
      this.validateForm.controls.careLevel.setValue(null);
    }
    if(data.illnessState){
      this.validateForm.controls.illnessState.setValue(data.illnessState.id);
    }else{
      this.validateForm.controls.illnessState.setValue(null);
    }
    if(data.patientType){
      this.validateForm.controls.patientType.setValue(data.patientType.id);
    }else{
      this.validateForm.controls.patientType.setValue(null);
    }
    if(data.tripType){
      this.validateForm.controls.tripType.setValue(data.tripType);
      this.tripTypeList = [data.tripTypeDTO];
    }
    this.validateForm.controls.remark.setValue(data.remark);

    this.modal = true;
    this.add = false;
    this.coopData = data;
  }

  // 获取性别
	genderList: any = [];
	getGenderList() {
    this.mainService.getDictionary("list", "user_gender").subscribe((data) => {
      this.genderList = data || [];
    });
	}

  // 获取护理等级
	careLevelList: any = [];
	getCareLevelList() {
    this.mainService.getDictionary("list", "levelOfCare").subscribe((data) => {
      this.careLevelList = data || [];
    });
	}

  // 获取病情级别
	illnessStateList: any = [];
	getIllnessStateList() {
    this.mainService.getDictionary("list", "stateOfAnIllness").subscribe((data) => {
      this.illnessStateList = data || [];
    });
	}

  // 获取患者类别
	patientTypeList: any = [];
	getPatientTypeList() {
    this.mainService.getDictionary("list", "patient_type").subscribe((data) => {
      this.patientTypeList = data || [];
    });
	}

  // 获取陪检方式
	tripTypeList: any = [];
	getTripTypeList() {
    let postData = {
      workOrderInspectScore: {
        hosId: this.validateForm.value.hosId
      },
      idx: 0,
      sum: 99999,
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "workOrderInspectScore", postData)
      .subscribe((res) => {
        this.isLoading = false;
        if (res.status == 200) {
          this.tripTypeList = res.list;
        }else{
          this.tripTypeList = [];
        }
      });
	}

  // 注意事项获取焦点
  isShowNoteList:boolean = false;
  focusNote(){
    this.isShowNoteList = true;
    this.getNoteList();
  }

  // 选择注意事项
  selectNote(name){
    this.validateForm.controls.remark.setValue(name);
    this.isShowNoteList = false;
    // this.remarkEle.nativeElement.focus();
  }

  // 获取注意事项列表
  noteList:any[] = [];
  noteLoading:boolean = false;
  getNoteList() {
    this.noteLoading = true;
    this.mainService.getDictionary('list', 'inspect_notes',).subscribe(result=>{
      this.noteLoading = false;
      this.noteList = result || [];
    });
  }

  // 点击其他位置
  clickExtra(e){
    if(document.documentElement.contains(document.querySelector('#noteList')) && e.target !== document.querySelector('#noteFocus')){
      this.isShowNoteList = false;
    }
  }

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  showDelModal(
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    this.confirmDelType = type;
    this.delModal = true;
    this.coopData = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "clearSign") {
      //清空标记
      this.mainService
        .clearPatientMark({ patientId: this.coopData.id })
        .subscribe((data:any) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }

  // 查看日志弹窗
  logPromptModalShow = false; //弹窗开关
  patientId = ""; //查看记录携带id
  showLogs(data) {
    this.patientId = data.id;
    this.logPromptModalShow = true;
  }
  // 关闭日志弹窗
  closeModelLog(e) {
    this.logPromptModalShow = JSON.parse(e).show;
  }
}
