import { Component, OnInit } from '@angular/core';
import { ToolService } from 'src/app/services/tool.service';
import { MainService } from 'src/app/services/main.service';
import { NzMessageService } from 'ng-zorro-antd';
import { startOfDay, endOfDay, format } from 'date-fns';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { Location } from '@angular/common';
import cloneDeep from 'lodash-es/cloneDeep'
@Component({
  selector: 'app-batch-inspection',
  templateUrl: './batch-inspection.component.html',
  styleUrls: ['./batch-inspection.component.less']
})
export class BatchInspectionComponent implements OnInit {

  constructor(
    private mainService: MainService,
    private tool: ToolService,
    private message: NzMessageService,
    private _location: Location,
  ) { }

  dateRange: any = []; //预约时间
  patientId: any; //患者
  hosId:any = this.tool.getCurrentHospital().id; //当前院区
  deptDTO:any = this.tool.getCurrentUserDept(); //当前科室
  deptDisplay; //护士端是否显示可以别名，1是显示科室名称，2是显示科室别名
  listOfData: any[] = []; //表格数据

  searchTimerSubject = new Subject(); //防抖

  ngOnInit() {
    //防抖
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1]);
    });

    this.tool.getDeptDisplay().subscribe((result) => {
      if (result.status == 200) {
        this.deptDisplay = result.list[0].valueconfig;
      }
    });

    this.init();
  }

  // 修改陪检方式
  changeTripType(tripTypeId, id){
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let postData = this.listOfData.find(v => v.id == id);
    this.mainService
    .simplePost("addData", 'patientInspectLog', postData)
    .subscribe((data) => {
      this.message.remove(this.maskFlag);
      this.maskFlag = false;
      if (data.status == 200) {
        this.message.success("修改陪检方式成功");
      } else {
        this.getList();
        this.message.error(data.msg || "修改陪检方式失败");
      }
    });
  }

  init(){
    this.getPatientInspectTime();
    this.getWorkOrderInspectScore();
    this.getList();
  }

  // 获取批量建单设置中的默认时间
  getPatientInspectTime(){
    this.mainService.getPatientInspectTime().subscribe((result:any) => {
      if(result.startTime && result.endTime){
        this.dateRange = [new Date(result.startTime), new Date(result.endTime)];
      }else{
        this.dateRange = [];
      }
    });
  }

  // 日期选择
  onCalendarChangeDate(dateArr){
    if(dateArr.length == 2){
      this.dateRange = [startOfDay(dateArr[0]), endOfDay(dateArr[1])];
    }
  }

  // 防抖
  isLoading = false;
  isSelecting:boolean = false; // 是否在选中状态
  searchTimer(fun, e) {
    if (this.isSelecting) {
      this.isSelecting = false; // 重置标志
      return; // 跳过处理
    }
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e]);
  }

  // 搜索
  changeInp(type, e) {
    if(type === 'patient'){
      this.searchTimer(this.getPatientList, e);
    }
  }

  // 设置标志
  setIsSelecting(flag){
    this.isSelecting = flag; // 设置标志
  }


  openChangePatient(flag){
    flag && this.setIsSelecting(false);
    flag && this.getPatientList();
  }

  // 获取患者
  patientList: any = [];
  getPatientList(e = undefined) {
    let postData = {
      idx: 0,
      sum: 20,
      patient: {
        department: this.deptDTO,
        keyWord: e,
      }
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "patient", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.patientList = data.list || [];
      });
  }

  maskFlag: any = false;

  addPatientList(){
    if(!this.dateRange.length){
      this.message.info('请选择预约时间!');
      return;
    }

    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;

    let postData = {
      startTime: this.dateRange.length ? format(this.dateRange[0], 'yyyy-MM-dd HH:mm:ss') : undefined,
      endTime: this.dateRange.length ? format(this.dateRange[1], 'yyyy-MM-dd HH:mm:ss') : undefined,
      inspectStateValue: 1,//待陪检
      noneGdid: 1,//未绑定工单
      nonePilId: 1,//未绑定患者闭环
      deptId: this.deptDTO.id,
    };

    this.mainService
      .getPatientInspectList(postData)
      .subscribe((result:any) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.inspectActiveList = result.list || [];
        this.patientActiveList = result.patientList || [];
        if(this.patientActiveList.length){
          this.showDelModal(this.patientActiveList, `您确认添加“<b class="red">${this.patientActiveList.length}</b>”位患者共“<b class="red">${this.inspectActiveList.length}</b>”项检查吗？`,'批量添加患者','add');
        }else{
          this.message.info('当前时间区间没有检查！');
        }
      });
  }

  changePatientId(id){
    this.setIsSelecting(true);
    setTimeout(() => {
      this.patientId = null;
    }, 0)

    if(!id){
      return;
    }

    if(!this.dateRange.length){
      this.message.info('请选择预约时间!');
      return;
    }

    let patientDTO = this.patientList.find(v => v.id == id);
    this.patientActiveList = [patientDTO];
    let postData = {
      startTime: this.dateRange.length ? format(this.dateRange[0], 'yyyy-MM-dd HH:mm:ss') : undefined,
      endTime: this.dateRange.length ? format(this.dateRange[1], 'yyyy-MM-dd HH:mm:ss') : undefined,
      patientCodes: patientDTO.patientCode,
      inspectStateValue: 1,//待陪检
      noneGdid: 1,//未绑定工单
      nonePilId: 1,//未绑定患者闭环
      deptId: this.deptDTO.id,
    };
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .getPatientInspectList(postData)
      .subscribe((result:any) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.inspectActiveList = result.list || [];
        this.showDelModal(this.patientActiveList, `<b class="red">${patientDTO.patientName}</b>在时间范围内有<b class="red">${this.inspectActiveList.length}</b>项检查项目，是否确认添加？`,'添加','add');
      });
  }

  inspectActiveList: any = [];//选中检查列表
  patientActiveList: any = [];//选中患者列表

  coopData: any = {}; //当前操作列
  btnLoading: boolean = false; //提交按钮loading状态

  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 === "del") {
      //删除-移除患者
      this.mainService
        .simplePost("rmvData", "patientInspectLog", [this.coopData.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }else if (this.confirmDelType === "delInspect") {
      //删除-检验项目
      this.coopData.data.inspectList.forEach(v => {
        if(v.id == this.coopData.inspect.id){
          v.pilId = undefined;
        }
      })
      let postData = {
        type: 'plan',
        pilList: [{
          ...this.patientInspectLogDTO,
          inspectList: this.coopData.data.inspectList.filter(v => v.id == this.coopData.inspect.id),
        }]
      }
      this.mainService
        .addPatientInspectList(postData)
        .subscribe((data:any) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.state == 200) {
            this.showPromptModal('删除', true, "");
          } else {
            this.showPromptModal('删除', false, data.msg);
          }
        });
    }else if (this.confirmDelType === "add") {
      //新增-患者陪检闭环
      let postData = {
        patientIds: this.inspectActiveList.length === 0 ? this.patientActiveList.map(v => v.id).toString() : undefined,
        inspectIds: this.inspectActiveList.length !== 0 ? this.inspectActiveList.map(v => v.id).toString() : undefined,
      }
      this.mainService
        .bindPatientInspect(postData)
        .subscribe((data:any) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.state == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }else if (this.confirmDelType === "reset") {
      //重置
      let ids = this.listOfData.filter(v => v.state.value == 1).map(v => v.id);
      this.mainService
        .simplePost("rmvData", "patientInspectLog", ids)
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }

  // 修改检验项目
  isShowSelectDate:boolean = false;
  editInspect(data){
    this.isShowSelectDate = true;
    this.coopData = data;
  }

  // 修改检验项目-确定
  submitSelectDate(date){
    console.log(date)
    this.coopData.data.inspectList.forEach(v => {
      if(v.id == this.coopData.inspect.id){
        v.yyTime = date;
      }
    })
    let postData = {
      type: 'plan',
      pilList: [{
        ...this.coopData.data,
        inspectList: this.coopData.data.inspectList.filter(v => v.id == this.coopData.inspect.id),
      }]
    }
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .addPatientInspectList(postData)
      .subscribe((data:any) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        if (data.state == 200) {
          this.isShowSelectDate = false;
          this.showPromptModal('修改', true, "");
        } else {
          this.showPromptModal('修改', false, data.msg);
        }
      });
  }

  // 修改检验项目-取消
  cancelSelectDate(e) {
    this.isShowSelectDate = false;
  }


  // 批量发起陪检
  isShowSelectDateYytime:boolean = false;
  addYytime(){
    let obj1 = this.listOfData.find(v => !v.tripType);
    if(obj1){
      this.message.warning(`${obj1.patientName}患者没有选择陪检方式，请调整后提交申请！`)
      return;
    }

    let obj2 = this.listOfData.find(v => !v.inspectList || v.inspectList.length == 0);
    if(obj2){
      this.message.warning(`${obj2.patientName}患者没有检验项目，请调整后提交申请！`)
      return;
    }
    this.isShowSelectDateYytime = true;
  }

  // 批量发起陪检-预约陪检
  submitSelectDateYytime(date){
    console.log(date)
    if(+date <= +new Date()){
      this.message.warning(`预约时间不能小于当前时间！`)
      return;
    }
    let pilList = cloneDeep(this.listOfData);
    pilList.forEach(v => {
      v.yyTime = date;
      delete v.inspectList;
    })
    let postData = {
      type: 'appointment',
      pilList,
    }
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .addPatientInspectList(postData)
      .subscribe((data:any) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        if (data.state == 200) {
          this.isShowSelectDateYytime = false;
          this.showPromptModal('操作', true, "");
        } else {
          this.showPromptModal('操作', false, data.msg);
        }
      });
  }

  // 批量发起陪检-立即执行
  submitSelectDateDirect(){
    let pilList = cloneDeep(this.listOfData);
    pilList.forEach(v => {
      delete v.inspectList;
    })
    let postData = {
      type: 'action',
      pilList,
    }
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .addPatientInspectList(postData)
      .subscribe((data:any) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        if (data.state == 200) {
          this.isShowSelectDateYytime = false;
          this.showPromptModal('操作', true, "");
        } else {
          this.showPromptModal('操作', false, data.msg);
        }
      });
  }

  // 批量发起陪检-取消
  cancelSelectDateYytime(e) {
    this.isShowSelectDateYytime = 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();
  }

  loading1:boolean = false;
  inspectTotalCount:number = 0;

  getList(){
    let data = {
      idx: 0,
      sum: 9999,
      patientInspectLog: {
        state: { value: '1,2' },
        deptId: this.deptDTO ? this.deptDTO.id : undefined,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "patientInspectLog", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.inspectTotalCount = this.listOfData.reduce((v, i) => v + i.planInspectCount, 0);
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  //获取陪检方式
  workOrderInspectScoreList:any[] = [];
  getWorkOrderInspectScore() {
    let postData = { idx: 0, sum: 9999, workOrderInspectScore: { hosId: this.hosId } };
    this.mainService
      .getFetchDataList("simple/data", "workOrderInspectScore", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.workOrderInspectScoreList = result.list || [];
        } else {
          this.message.error("请求数据失败");
        }
      });
  }

  // 返回
  goBack(){
    this._location.back();
  }

  // 追加项目
  patientInspectLogDTO:any = {};
  isShowAddInspect = false; //弹窗开关
  addInspect(patientInspectLogDTO){
    this.patientInspectLogDTO = patientInspectLogDTO;
    this.isShowAddInspect = true;
  }
  // 关闭弹窗
  closeAddInspectModel(e) {
    this.isShowAddInspect = JSON.parse(e).show;
  }
  // 确定弹窗
  confirmAddInspectModel(e) {
    console.log(e);
    let obj = JSON.parse(e);
    this.isShowAddInspect = obj.show;
    if(obj.type == 1){
      //检验项目
      let postData = {
        inspectIds: obj.list.map(v => v.id).toString() || undefined,
      }
      this.maskFlag = this.message.loading("正在加载中..", {
        nzDuration: 0,
      }).messageId;
      this.mainService
        .bindPatientInspect(postData)
        .subscribe((data:any) => {
          this.message.remove(this.maskFlag);
          this.maskFlag = false;
          if (data.state == 200) {
            this.showPromptModal('添加', true, "");
          } else {
            this.showPromptModal('添加', false, data.msg);
          }
        });
    }else if(obj.type == 2){
      // 手动添加
      let postData = {
        type: 'plan',
        pilList: [{
          ...this.patientInspectLogDTO,
          inspectList: obj.list.map(v => ({
            patientCode: this.patientInspectLogDTO.patientCode,
            patientName: this.patientInspectLogDTO.patientName,
            barCode: this.patientInspectLogDTO.barCode,
            inspectCheckType: { id: v.id },
            applyDeptId: this.patientInspectLogDTO.deptId,
            bedNum: this.patientInspectLogDTO.bedNum,
            hosId: this.patientInspectLogDTO.hosId,
            pilId: this.patientInspectLogDTO.id,
            yyTime: this.dateRange.length ? format(this.dateRange[0], 'yyyy-MM-dd HH:mm:ss') : undefined,
          })) || undefined,
        }]
      }
      this.maskFlag = this.message.loading("正在加载中..", {
        nzDuration: 0,
      }).messageId;
      this.mainService
        .addPatientInspectList(postData)
        .subscribe((data:any) => {
          this.message.remove(this.maskFlag);
          this.maskFlag = false;
          if (data.state == 200) {
            this.showPromptModal('添加', true, "");
          } else {
            this.showPromptModal('添加', false, data.msg);
          }
        });
    }
  }
}
