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, startOfMinute, addMinutes } from 'date-fns';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { Location } from '@angular/common';
import cloneDeep from 'lodash-es/cloneDeep'
import { Router } from "@angular/router";
@Component({
  selector: 'app-inspect-info-config',
  templateUrl: './inspect-info-config.component.html',
  styleUrls: ['./inspect-info-config.component.less']
})
export class InspectInfoConfigComponent implements OnInit {

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

  searchData:any = {
    dateRange: new Date(), //检查时间
  }
  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.getTaskType();
    this.init();
  }

  // 修改陪检方式
  changeTripType(tripTypeId, id){
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let postData = this.listOfData.find(v => v.id == id);
    postData.operationType = 'evaluatePatient';
    this.mainService
    .simplePost("addData", 'patient', 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 || "修改陪检方式失败");
      }
    });
  }

  // 修改危重等级
  changeIllnessState(illnessStateId, id){
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let postData = this.listOfData.find(v => v.id == id);
    postData.illnessState = {
      id: illnessStateId,
    }
    postData.operationType = 'evaluatePatient';
    this.mainService
    .simplePost("addData", 'patient', 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.getIllnessState();
    this.getWorkOrderInspectScore();
    this.getList();
  }

  // 防抖
  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: 10,
      hosId: this.hosId,
      department: this.deptDTO.id,
      hasBedNum: 1,//有床号
      patientName: e,
    };
    this.isLoading = true;
    this.mainService
      .listMsgByMain('listPatient',postData)
      .subscribe((data:any) => {
        this.isLoading = false;
        this.patientList = data.list || [];
      });
  }

  maskFlag: any = false;

  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 === "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);
          }
        });
    }else if (this.confirmDelType === "delInspect") {
      //删除-检查
      this.mainService
        .coopData("rmvData", "inspect", [this.coopData.inspect.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);
          }
        });
    }
  }

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

  // 修改检查项目-确定
  submitSelectDate({date, endCheckTime, deptId, remark}){
    let postData = {
      id: this.coopData.inspect.id,
      yyTime: date || undefined,
			endCheckTime: endCheckTime,
      execDeptId: deptId,
      remark,
    }
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .simplePost("updData", 'inspect', postData)
      .subscribe((data:any) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        if (data.status == 200) {
          this.isShowSelectDate = false;
          this.showPromptModal('修改', true, "");
        } else {
          this.showPromptModal('修改', false, data.msg);
        }
      });
  }

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

  // 修改注意事项
  isShowSelectRemark:boolean = false;
  editRemark(data){
    this.isShowSelectRemark = true;
    this.coopData = data;
  }

  // 修改注意事项-确定
  submitSelectRemark(remark){
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;

    let postData = {
      ...this.coopData.data,
      remark,
      operationType: 'evaluatePatient',
    };

    this.mainService
    .simplePost("addData", 'patient', postData)
    .subscribe((data) => {
      this.message.remove(this.maskFlag);
      this.maskFlag = false;
      this.getList();
      if (data.status == 200) {
        this.isShowSelectRemark = false;
        this.message.success("编辑注意事项成功");
      } else {
        this.message.error(data.msg || "编辑注意事项失败");
      }
    });
  }

  // 修改注意事项-取消
  cancelSelectRemark(e) {
    this.isShowSelectRemark = 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 postData = {
      idx: 0,
      sum: 99999,
      hosId: this.hosId,
      department: this.deptDTO.id,
      queryInspect: 1,//带inspects
      hasBedNum: 1,//有床号
      startTime: this.searchData.dateRange ? format(startOfDay(this.searchData.dateRange), 'yyyy-MM-dd HH:mm:ss') : undefined,
      endTime: this.searchData.dateRange ? format(endOfDay(this.searchData.dateRange), 'yyyy-MM-dd HH:mm:ss') : undefined,
      id: this.searchData.id || undefined,
      noneTripType: this.searchData.noneTripType || undefined,
      noneEndDept: this.searchData.noneEndDept || undefined,
      noneYY: this.searchData.noneYY || undefined,
      noneGdid: this.searchData.noneGdid || undefined,
    };
    this.loading1 = true;
    this.mainService
      .listMsgByMain('listPatient',postData)
      .subscribe((data:any) => {
        this.loading1 = false;
        if (data.status == 200) {
          let listOfData = data.list || [];
          listOfData.forEach(v => {
						for(let i of v.inspects){
							if(i.yyTime){
								i.newTime = format(new Date(i.yyTime), 'MM-dd HH:mm')
								if(i.endCheckTime){
									i.newTime2 = format(new Date(i.endCheckTime), 'HH:mm')
									i.yyEndTime = i.newTime + '--' + i.newTime2
								}else{
									// i.newTime = format(new Date(i.yyTime), 'yyyy-MM-dd HH:mm')
									i.yyEndTime = i.newTime
								}
							}else{
								i.newTime = null
								i.newTime2 = null
							}
						}
            if(v.illnessState){
              v.illnessStateCopy = v.illnessState.id;
            }
          })
          this.listOfData = listOfData;
          this.inspectTotalCount = this.listOfData.reduce((v, i) => v + i.inspects.length, 0);
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 重置
  reset(){
    this.searchData = {
      dateRange: new Date(),
    };
    this.getList();
  }

  //获取陪检方式
  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("请求数据失败");
        }
      });
  }

  //获取危重等级
  illnessStateList:any[] = [];
  getIllnessState() {
    this.mainService.getDictionary('list', 'stateOfAnIllness').subscribe((data) => {
      this.illnessStateList = data || [];
    });
  }

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

  // 追加项目
  patientDTO:any = {};
  isShowAddInspect = false; //弹窗开关
  addInspect(patientDTO){
    this.patientDTO = patientDTO;
    this.isShowAddInspect = true;
  }
  // 关闭弹窗
  closeAddInspectModel(e) {
    this.isShowAddInspect = JSON.parse(e).show;
  }
  // 确定弹窗
  confirmAddInspectModel(e) {
    console.log(e);
    let obj = JSON.parse(e);
    let postData:any = {
      inspectList: [{
        patientCode: this.patientDTO.patientCode,
        patientName: this.patientDTO.patientName,
        barCode: this.patientDTO.barCode,
        inspectCheckType: { id: obj.inspectData.id },
        applyDeptId: this.deptDTO.id,
        execDeptId: obj.inspectData.execDeptId,
        bedNum: this.patientDTO.bedNum,
        hosId: this.hosId,
        yyTime: format(new Date(obj.inspectData.date), 'yyyy-MM-dd ') + format(startOfMinute(new Date(obj.inspectData.time)), 'HH:mm:ss'),
				endCheckTime: obj.inspectData.endCheckTime
			}] || undefined,
    };
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .simplePost("addData", "inspect", postData)
      .subscribe((data:any) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        if (data.status == 200) {
          this.isShowAddInspect = obj.show;
          this.showPromptModal('添加', true, "");
        } else {
          this.showPromptModal('添加', false, data.msg);
        }
      });
  }

  //获取任务类型
  tasktype:any = {};// 任务类型
 getTaskType() {
   let postData = {
     idx: 0,
     sum: 1,
     taskType: {
       simpleQuery: true,
       hosId: {
         id: this.hosId
       },
       associationType: {
         key: 'association_types',
         value: 'inspect',
       }
     }
   };
   this.mainService
     .getFetchDataList("simple/data", "taskType", postData)
     .subscribe((result) => {
       if (result.status == 200) {
         this.tasktype = result.list[0] || {};
         this.getConfig();
       }
     });
 }

  // 获取配置
  configs:any = {};
  getConfig() {
    let postData = {
      idx: 0,
      sum: 1,
      taskTypeConfig: {
        taskTypeDTO: {
          hosId: {
            id: this.hosId
          },
          associationType: this.tasktype.associationType,
        }
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskTypeConfig", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.configs = result.list[0] || {};
        }
      });
  }

  // 查看工单详情
	detail(e, gdId) {
	  e.stopPropagation();
	  this.router.navigateByUrl("/inspectInfoConfig/orderDetail/" + gdId);
	}
}
