import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { MainService } from "src/app/services/main.service";
import { ToolService } from "src/app/services/tool.service";
import { startOfDay, endOfDay, format, startOfMinute, addMinutes } from 'date-fns';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
  selector: "app-inspect-search",
  templateUrl: "./inspect-search.component.html",
  styleUrls: ["./inspect-search.component.less"],
})
export class InspectSearchComponent implements OnInit {
  constructor(
    private mainService: MainService,
    private tool: ToolService,
    private route: ActivatedRoute,
    private message: NzMessageService,
  ) {}

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

  checkOptionsOne: Array<any> = [
    { label: "未标记检查科室", value: "0", checked: false },
    { label: "无预约时间检查", value: "1", checked: false },
  ];

  dateRange: any = []; //入库时间区间

  searchCriteria = {
    //搜索条件
    patientName: "",
    inspectCode: "",
    hospital: null,
    workerId: null,
    inspectState: null,
  };
  workerSearch = []; // 院区下的配送人员列表(搜索框)
  allHospital: any = []; //院区下拉框
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  changeInpSubject = new Subject();
	hosId:any = this.tool.getCurrentHospital().id; //当前院区
	
  ngOnInit() {
		this.getTaskType();
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.searchWorker(v);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getAllHospital();
  }

  // 表格筛选
  log(value: object[]): void {
    this.getList(1);
  }

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

  // 搜索类型
  isLoading1 = false;
  types = []; // 类型列表(搜索框)
  searchTypes() {
    this.isLoading1 = true;
    this.mainService.getDictionary("list", "inspect_state").subscribe((res) => {
      this.isLoading1 = false;
      this.types = res;
    });
  }
  // 打开搜索框
  changeSearch1(flag) {
    if (flag) {
      this.searchTypes();
    }
  }
  // 重置
  reset() {
    this.dateRange = [];
    this.searchCriteria = {
      //搜索条件
      patientName: "",
      inspectCode: "",
      hospital: this.allHospital[0] ? this.allHospital[0]["id"] : null,
      workerId: null,
      inspectState: null,
    };
    this.getList(1);
  }

  // 获取所有院区
  getAllHospital() {
    this.allHospital = [this.tool.getCurrentHospital()];
    this.searchCriteria.hospital = this.tool.getCurrentHospital().id;
  }
	
	//获取任务类型
	 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] || {};
					 this.getList(1);
	       }
	     });
	 }
	 
  // 查看标本历史记录
  historyPromptModalShow = false; //标本历史记录弹窗开关
  scode = ""; //查看历史记录携带
  viewSpecimenHistory(data) {
    this.scode = data.scode;
    this.historyPromptModalShow = true;
  }
  // 关闭标本历史记录弹窗
  closeModelHistory(e) {
    this.historyPromptModalShow = JSON.parse(e).show;
  }
  // 打开搜索框
  changeSearch(flag) {
    if (flag) {
      this.changeInp("no");
    }
  }
  // 边输边搜节流阀
  isLoading = false;
  changeInp(worker) {
    if (!worker) {
      return;
    }
    if (worker === "no") {
      worker = "";
    }
    this.isLoading = true;
    this.changeInpSubject.next(worker);
  }
  // 搜索配送人员
  searchWorker(worker) {
    let postData = {
      user: {
        name: worker,
        hospital: { id: this.searchCriteria.hospital },
        usertype: { id: 106 },
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("data", "user", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.isLoading = false;
          this.workerSearch = result.list;
        }
      });
  }

  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let postData = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      hosId: this.searchCriteria.hospital || undefined,
      patientName: this.searchCriteria.patientName || undefined,
      inspectCode: this.searchCriteria.inspectCode || undefined,
      workerId: this.searchCriteria.workerId || undefined,
      inspectState: this.searchCriteria.inspectState || undefined,
      createStartTime: this.dateRange.length ? format(this.dateRange[0], 'yyyy-MM-dd HH:mm:ss') : undefined,
      createEndTime: this.dateRange.length ? format(this.dateRange[1], 'yyyy-MM-dd HH:mm:ss') : undefined,
      noneEndDept: this.checkOptionsOne[0].checked ? true : undefined,
      noneYytime: this.checkOptionsOne[1].checked ? true : undefined,
      queryInspect: 1,//带检查项目
    };
    this.loading1 = true;
    this.mainService
      .listMsgByMain("listInspect", postData)
      .subscribe((data) => {
        this.loading1 = false;
        if (data["status"] == 200) {
					data["list"].forEach(i =>{
						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.yyEndTime = i.newTime
							}
						}else{
							i.yyEndTime = null
						}
					})
          this.listOfData = data["list"];
          this.listLength = data["totalNum"];
        }
      });
  }

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

  // ============================add start==================
  // 新增检查
  isShowAddInspect = false; //弹窗开关
  addModal(){
    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: [{
        remark: obj.inspectData.remark || undefined,
        patientCode: obj.patientDTO.patientCode,
        patientName: obj.patientDTO.patientName,
        barCode: obj.patientDTO.barCode,
        inspectCheckType: { id: obj.inspectData.id },
        applyDeptId: obj.inspectData.applyDeptId,
        execDeptId: obj.inspectData.execDeptId,
        bedNum: obj.patientDTO.bedNum,
        hosId: this.searchCriteria.hospital,
        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);
        }
      });
  }
  // ============================add end==================

  coopData: any = {}; //当前操作列
  // 修改检验项目
  isShowSelectDate:boolean = false;
  edit(data){
    this.isShowSelectDate = true;
    this.coopData = data;
  }

  // 修改检查项目-确定
  maskFlag: any = false;
  submitSelectDate({date, endCheckTime, deptId, remark, applyDeptId, patientDTO}){
    let postData = {
      id: this.coopData.id,
      yyTime: date || undefined,
			endCheckTime: endCheckTime,
      execDeptId: deptId,
      remark,
      applyDeptId,
      patientCode: patientDTO.patientCode,
      patientName: patientDTO.patientName,
      barCode: patientDTO.barCode,
      bedNum: patientDTO.bedNum,
    }
    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;
  }

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