import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";

import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { EmergencyInfoService } from './emergency-info.service';
import { format, startOfDay, endOfDay } from 'date-fns';
import { NzMessageService } from "ng-zorro-antd";
import { MainService } from 'src/app/services/main.service';

@Component({
  selector: "app-emergency-info",
  templateUrl: "./emergency-info.component.html",
  styleUrls: ["./emergency-info.component.less"],
})
export class EmergencyInfoComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
		private message: NzMessageService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
		private router: Router,
    private tool: ToolService,
    private quickOrderAcceptanceService: EmergencyInfoService,
		private mainService: MainService,
  ) {}

  listOfData: any[] = []; //表格数据

  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  department: any; //所属科室
  hosId: any; //院区（搜索）
  typeList: Array<any>; //快捷类型
  taskTypeList: Array<any>; //所有任务类型
  deptList: Array<any>; //所有科室
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示

  btnLoading: boolean = false; //提交按钮loading状态
  changeInpSubject = new Subject(); //防抖
  changeInpDeptSubject = new Subject(); //防抖

  // 初始化增删改按钮
  coopBtns: any = {};
	alarmStatus:any;
	incidentStatus:any;
	alarmIp:any;
	alarmUrgency:any;
	dateRange:any = [];
	
  ngOnInit() {
		// 全局监听
		this.tool.getEventEndObservable().subscribe(res => {
			console.log('全局的监听触发2222', res);
			let data:any = res;
			if(data.message == '关单'){
				this.getList(true)
			}
		});
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getTasktype(v[0]);
    });
    //防抖
    this.changeInpDeptSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getDept(v[0]);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList(true);
		this.getGdList();
  }
	
	// 日期选择
	startDate: string; //发起时间开始
	endDate: string; //发起时间结束
	changeDate(result?): void {
	  if (result.length==0) {
	    this.startDate = this.endDate = null;
	    return;
	  }
		this.startDate = format(result[0], 'yyyy-MM-dd HH:mm:ss');
		this.endDate = format(result[1], 'yyyy-MM-dd HH:mm:ss');
	  this.dateRange = [this.startDate,this.endDate]
	}
	
	onCalendarChangeDate(dateArr){
	  console.log(dateArr)
	  if(dateArr.length == 2){
	    let dateStart = new Date(dateArr[0]);
	    let dateEnd = new Date(dateArr[1]);
	    dateStart.setHours(0,0,0);
	    dateEnd.setHours(23,59,59);
	    this.dateRange = [dateStart,dateEnd];
	  }
	}
	
	// 获取工单状态
	gdList:any = [];
	alarmList:any = [];
	urgencyList:any = [];
	getGdList() {
	  this.isLoading = true;
	  this.quickOrderAcceptanceService.getDictionary("incident_status").subscribe((res) => {
	    this.isLoading = false;
	    this.gdList = res || [];
	  });
		this.quickOrderAcceptanceService.getDictionary("alarm_status").subscribe((res) => {
		  this.isLoading = false;
		  this.alarmList = res || [];
		});
		this.quickOrderAcceptanceService.getDictionary("alarm_urgency").subscribe((res) => {
		  this.isLoading = false;
		  this.urgencyList = res || [];
		});
	}
	
  // 搜索
  search() {
    this.getList(true);
  }
	
	// 重置
	reset() {
		this.alarmStatus = null;
		this.incidentStatus = null;
		this.alarmIp = null;
		this.alarmUrgency = null;
		this.startDate = null;
		this.endDate = null;
		this.dateRange = [];
	  this.getList(true);
	}
	
  // 表格数据
  loading1 = false;
  getList(isResetPageIndex = false, type?) {
    isResetPageIndex && (this.pageIndex = 1);
    let data = {
      pageIndex: this.pageIndex,
      pageSize: this.pageSize,
			alarm:{
				hosId: this.hosId,
				alarmStatus:{
					id:this.alarmStatus
				},
				incidentStatus:this.incidentStatus,
				alarmIp:this.alarmIp,
				alarmUrgency:{
					id:this.alarmUrgency,
				},
				startTime: this.startDate || undefined,
				endTime: this.endDate || undefined,
			}
    };
		if(this.alarmStatus){
			data.alarm.alarmStatus.id = this.alarmStatus
		}else{
			delete data.alarm.alarmStatus
		}
		if(this.alarmUrgency){
			data.alarm.alarmUrgency.id = this.alarmUrgency
		}else{
			delete data.alarm.alarmUrgency
		}
    this.loading1 = true;
		if(type!='page'){
			this.mapOfCheckedId = {};
			this.checkedDepIds = [];
		}
    this.isAllDisplayDataChecked = false;
    this.quickOrderAcceptanceService
      .query(data)
      .subscribe((result) => {
        this.loading1 = false;
        this.listOfData = result.list;
        this.listLength = result.totalNum;
      });
  }

  // 获取任务类型列表
  getTasktype(keywords = '') {
    let hosId = this.tool.getCurrentHospital().id;
    this.isLoading = true;
    this.quickOrderAcceptanceService.queryTasktype({
      hosId,
      keywords,
    }).subscribe((res) => {
      this.isLoading = false;
      this.taskTypeList = res.list || [];
    });
  }

  // 获取科室列表
  getDept(keywords = '') {
    let hosId = this.tool.getCurrentHospital().id;
    this.isLoading = true;
    this.quickOrderAcceptanceService.queryDept({
      hosId,
      keywords,
    }).subscribe((res) => {
      this.isLoading = false;
      this.deptList = res.list || [];
    });
  }

  // 获取快捷类型
  getTypeList() {
    this.isLoading = true;
    this.quickOrderAcceptanceService.getDictionary("receiveRuleType").subscribe((res) => {
      this.isLoading = false;
      this.typeList = res || [];
    });
  }

  // 新增弹框
  showModal() {
    this.add = true;
    this.modal = true;
    this.initForm();
  }
  hideModal() {
    this.modal = false;
    this.initForm();
  }

  // 初始化新增form表单
  initForm() {
    if (this.add) {
      this.typeList = [];
      this.taskTypeList = [];
      this.deptList = [];
    }
    this.validateForm = this.fb.group({
      title: ['', [Validators.required]],
      taskTypeIds: [null, [Validators.required]],
      deptIds: [null, [Validators.required]],
      type: [null, [Validators.required]],
    });
  }
  // 表单提交
  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;
    if(this.add){
      this.quickOrderAcceptanceService
      .add({
        title: this.validateForm.value.title,
        taskTypeIds: this.validateForm.value.taskTypeIds,
        deptIds: this.validateForm.value.deptIds,
        type: {id: this.validateForm.value.type},
        hosId: this.hosId,
      })
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideModal();
        this.initForm();
				this.operateType = 'no'
        if (data.status == 200) {
          this.showPromptModal(this.add ? "新增" : "编辑", true, "");
        } else {
          this.showPromptModal(this.add ? "新增" : "编辑", false, data.msg);
        }
      });
    }else{
      this.quickOrderAcceptanceService
      .update({
        title: this.validateForm.value.title,
        taskTypeIds: this.validateForm.value.taskTypeIds,
        deptIds: this.validateForm.value.deptIds,
        type: {id: this.validateForm.value.type},
        coopData: this.coopData,
      })
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideModal();
        this.initForm();
				this.operateType = 'no'
        if (data.status == 200) {
          this.showPromptModal(this.add ? "新增" : "编辑", true, "");
        } else {
          this.showPromptModal(this.add ? "新增" : "编辑", false, data.msg);
        }
      });
    }
  }
	
	// 批量恢复
	infoContent:any;
	optModal:boolean = false;
	operationType:any;
	batchRecover(){
		if(this.checkedDepIds.length==0){
			this.message.error('请勾选告警列表')
			return
		}
		this.operationType = 'batchRecovery'
		this.infoContent=`您确认要恢复${this.checkedDepIds.length}项告警吗？`
		this.optModal = true
	}
	
	// 批量不处理
	batchNo(){
		if(this.checkedDepIds.length==0){
			this.message.error('请勾选告警列表')
			return
		}
		this.operationType = 'batchUnprocessed'
		this.infoContent=`您确认要不处理${this.checkedDepIds.length}项告警吗？`
		this.optModal = true
	}
	
	// 确认
	confirmOpt() {
	  this.btnLoading = true;
	  this.quickOrderAcceptanceService
	  .operation({
	    operationType: this.operationType,
	    ids: this.checkedDepIds,
	  })
	  .subscribe((data) => {
	    this.btnLoading = false;
	    this.hideOptModal();
			this.operateType = 'no'
	    if (data.status == 200) {
	      this.showPromptModal("操作", true, "");
	    } else {
	      this.showPromptModal("操作", false, data.msg);
	    }
	  });
	}
	
	// 关闭模态框
	hideOptModal() {
	  this.optModal = false;
	}
	
	// 消息发送
	sendModal:boolean = false;
	tipsMsg2:any = '您确定要发送消息吗？';
	send(data){
		this.itemData = data;
		this.sendModal = true;
	}
	
	hideSendModal(){
		this.sendModal = false;
	}
	
	// 确定发送消息
	operateType:any;
	confirmSend(){
		let data = {
			alarm:{
				operationType: 'sendMsg',
				id: this.itemData.id,
			}
		};
		this.btnLoading = true;
		this.mainService
		  .dataPost("updData", "alarm", data)
		  .subscribe((data) => {
		    this.btnLoading = false;
				this.sendModal = false;
		    if (data.status == 200) {
					this.operateType = 'send'
		      this.showPromptModal("操作", true, "");
		    } else {
		      this.showPromptModal("操作", false, data.msg);
		    }
		  });
	}
	
	// 建单
	addOrder(data){
		this.tool.triggerEvent({
			message:'建单',
			data: data
		})
	}
	
	// 查看工单
	detailModalShow = false; //弹窗开关
	detail(e, data) {
	  e.stopPropagation();
		if(!data.incidentSign){
			return
		}
	  this.coopData = data;
	  this.detailModalShow = true;
	}
	// 关闭弹窗
	closeDetailModelOrder(e) {
	  this.detailModalShow = JSON.parse(e).show;
	}
	// 弹窗确定
	confirmDetailModelOrder(e){
	  console.log(e);
	  this.detailModalShow = false;
	  this.getList(true);
	}
	
	refreshList(){
		
	}
	
	// 查看列表
	itemData:any;
	lookModal:boolean = false;
	look(data){
		this.itemData = data;
		this.lookModal = true
	}
	
	// 关闭查看
	close(){
		this.lookModal = false
	}
	
  // 选中表格中科室
  mapOfCheckedId: { [key: string]: boolean } = {};
  checkedDepIds = []; //已选中科室id
  refreshStatus(): void {
    this.isAllDisplayDataChecked = this.listOfData.every(
      (item) => this.mapOfCheckedId[item.id]
    );
    let arr = [];
    for (var k in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[k]) {
        arr.push(Number(k));
      }
    }
    this.checkedDepIds = arr;
    console.log(this.checkedDepIds);
  }

  //表格整行选中
  selectedListData(id) {
    this.mapOfCheckedId[id] = !this.mapOfCheckedId[id];
    this.refreshStatus();
  }

  // 全选
  isAllDisplayDataChecked = false; //当前页是否全选
  checkAll(value: boolean): void {
    this.listOfData.forEach((item) => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  // 编辑
  maskFlag: any = false;
  coopData = {};
  edit(data) {
    this.validateForm.controls.title.setValue(data.title);
    this.validateForm.controls.type.setValue(data.type ? data.type.id : null);
    this.validateForm.controls.taskTypeIds.setValue(data.taskTypeList ? data.taskTypeList.map(v => v.id) : null);
    this.validateForm.controls.deptIds.setValue(data.deptList ? data.deptList.map(v => v.id) : null);
    this.modal = true;
    this.add = false;
    this.coopId = data.id;
    this.coopData = data;
    this.getTasktype();
    this.getDept();
    this.getTypeList();
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    this.coopId = data.id;
    this.delModal = true;
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
		if(this.operateType = 'send'){
			this.getList();
		}else{
			this.getList(true);
		}
  }

  // 边输边搜节流阀
  isLoading = false;
  changeInp(e) {
    this.changeInpSubject.next([e]);
  }

  // 边输边搜节流阀
  changeDeptInp(e) {
    this.changeInpDeptSubject.next([e]);
  }

  // 打开任务类型
  openTasktype(e){
    if(e){
      this.getTasktype();
    }
  }

  // 打开科室
  openDept(e){
    if(e){
      this.getDept();
    }
  }

  // 打开班次
  openSchedule(e){
    if(e){
      this.getTypeList();
    }
  }
}


