import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { NzMessageService } from "ng-zorro-antd";

@Component({
  selector: "app-hs-prompt-modal",
  templateUrl: "./hs-prompt-modal.component.html",
  styleUrls: ["./hs-prompt-modal.component.less"],
})
export class HsPromptModalComponent implements OnInit {
  // 切换科室，切换弹窗
  // changeShow = true //true显示第一个弹窗，false显示选择科室的弹窗
  validateForm!: FormGroup;
  dutyDepts = []; //当值科室列表
  isLoading = false;
  currentHospital; //当前院区
  hospitals = []; //所有院区
  currentDept; //当前科室
  @Input() show: boolean;
  @Input() changeShow: boolean;
  @Input() closeTime: number;
  @Input() closeTimeFlag;
  @Input() deptType:string = 'nurse';//默认按护士端的科室条件搜索

  @Output() closeModelHs = new EventEmitter<any>(); //1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件
  @Output() clearModelHs = new EventEmitter<any>(); //1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件

  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
    private msg: NzMessageService,
    private tool: ToolService
  ) {}
  searchDeptSubject = new Subject();
  deptDisplay; //护士端是否显示可以别名，1是显示科室名称，2是显示科室别名
  deptDisplayLoading: boolean = false;
	user:any;
  ngOnInit() {
    this.deptDisplayLoading = true;
    this.tool.getDeptDisplay().subscribe((result) => {
      this.deptDisplayLoading = false;
      if (result.status == 200) {
        this.deptDisplay = result.list[0].valueconfig;
      }
    });
    this.searchDeptSubject.pipe(debounceTime(500)).subscribe((v: any) => {
      this.search(v.hosId, v.e);
    });
    this.hospitals = this.tool.getHospitalList();
    this.currentHospital = this.tool.getCurrentHospital();
    this.currentDept = this.tool.getCurrentUserDept();
		this.user = this.tool.getCurrentUserInfo();
    this.initForm();
  }
  initForm() {
    this.search(this.currentHospital.id, "");
    this.validateForm = this.fb.group({
      hospital: [this.currentHospital.id, [Validators.required]], //院区
      dutyDeptFc: [null, [Validators.required]], //当班科室
    });
  }
  // 关闭弹窗
  hideModal() {
    this.initForm();
    this.closeModelHs.emit(JSON.stringify({ show: false, changeShow: true })); //emits(向上弹射)事件
  }
  // 切换科室
  changeModal() {
    this.clearModelHs.emit(JSON.stringify({ clear: true, changeShow: false })); //emits(向上弹射)事件
  }
  // 获取当前用户信息
  getCurrentUserNow() {
    this.mainService.getCurrentUser1().subscribe((data) => {
      this.msg.remove(this.maskFlag);
      this.maskFlag = false;
      if (data["status"] == 200) {
        let user = JSON.parse(localStorage.getItem("user"));
        user.user.dept = data["data"].dept;
        user.user.currentHospital = data["data"].currentHospital;
        localStorage.setItem("user", JSON.stringify(user));
        this.showPromptModal("切换科室", true, "");
        this.hideModal();
      }
    });
  }
  // 确定
  maskFlag: any = false;
  ok() {
    let flag = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
      if (this.validateForm.controls[i].valid === false) {
        flag = false;
      }
    }
    if (!flag) {
      return;
    }
    this.maskFlag = this.msg.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let postData = {
      currentHosId: this.validateForm.controls.hospital.value,
      loginType: "PC",
    };
    this.mainService.changeHospital(postData).subscribe((result) => {
      if (result.status == 200) {
        let dataObj = {
          user: {
						account: this.user.account,
						upType: "changeDept",
            dept: {
              id: this.validateForm.controls.dutyDeptFc.value,
            },
            id: JSON.parse(localStorage.getItem("user")).user.id,
          },
        };
        this.mainService
          .coopData("updData", "user", dataObj)
          .subscribe((data) => {
            if (data.status == 200) {
              this.getCurrentUserNow();
            } else {
              this.showPromptModal("切换科室", false, "");
              this.msg.remove(this.maskFlag);
              this.maskFlag = false;
            }
          });
      }
    });
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  promptModalShow = false;
  promptContent = "";
  ifSuccess = false;
  promptInfo = "";
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
  }
  //当值科室搜索
  searchDept(hosId, e) {
    this.isLoading = true;
    this.searchDeptSubject.next({ hosId, e });
  }
  // 院区选择
  searchHospital(hosId) {
    this.validateForm.controls.dutyDeptFc.setValue(null);
    this.searchDept(hosId, "");
  }
  // 当值科室搜索
  currentKeywords = "";
  search(hosId, e) {
    let keywords = "";
    if (e) {
      keywords = e;
    }
    this.currentKeywords = keywords;
    let dataObj = {};
    if(this.deptType === 'nurse'){
      dataObj = {
        idx: 0,
        sum: 10,
        department: {
          searchType: 1,// 简单查询
          hospital: { id: hosId },
          keyWord: keywords,
          nurseSign: 1,
          flag: 1,
        },
      }
    }else if(this.deptType === 'pharmacy'){
      dataObj = {
        idx: 0,
        sum: 10,
        department: {
          searchType: 1,// 简单查询
          hospital: { id: hosId },
          dept: keywords,
          type: {id: "386"},
        },
      }
    }else if(this.deptType === 'pathology'){
      dataObj = {
        idx: 0,
        sum: 10,
        department: {
          searchType: 1,// 简单查询
          hospital: { id: hosId },
          dept: keywords,
          type: {id: "282"},
        },
      }
    }
    this.mainService
      .getFetchDataList("data", "department", dataObj)
      .subscribe((data) => {
        if (this.currentKeywords == keywords) {
          this.isLoading = false;
        }
        if (data.status == 200) {
          this.dutyDepts = data.list;
        }
      });
  }
}
