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

@Component({
  selector: "app-configuration-voluntarilyBuild",
  templateUrl: "./configuration-voluntarilyBuild.component.html",
  styleUrls: ["./configuration-voluntarilyBuild.component.less"],
})
export class ConfigurationVoluntarilyBuildComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private mainService: MainService,
    private fb: FormBuilder,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}
	@Input() voluntarilyTabList: any[] = [];
  coopData: any = {}; //当前操作列
	hosId:any;
	hospitals:any = [];
	isDeptLoading: boolean = false;

	currentHospital:any;
	malfunctionData:any = [];
	allUserGroup:any = [];
	userData:any = [];

  changeCommonInpSubject = new Subject();
	
  ngOnInit() {
		this.activeDictionaryKey = this.voluntarilyTabList[0];
		this.changeCommonInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[0] === 'category'){
        this.searchApplicationCategory(v[1]);
      }
    });

    // 优先级
    setTimeout(() => {
      this.tablePriorityHeight = document.querySelector('#priorityTable').clientHeight - document.querySelector('#priorityTable .list-template__top').clientHeight - 8 - document.querySelector('#priorityTable .thead').clientHeight;
    }, 100)
		this.hosId = this.tool.getCurrentHospital().id;
		this.currentHospital = this.tool.getCurrentHospital();
    this.getCommonFaultsList();
		this.searchApplicationCategory()
		this.getEmergencyDic();
		this.getGroupList();
  }
	
	activeDictionaryKey:any;
	clickDictionaryKey(item){
		this.activeDictionaryKey = item;
		if(item.key=='alarmConfig'){
			this.getCommonFaultsList();
		}
	}
	
	// 获取处理组
	groupList:any = [];
	getGroupList() {
	  let data = {
			idx: 0,
			sum: 99999,
			group2: {
				statisticalHosId: this.hosId,
				type:'3'
			}
		};
		this.mainService
			.getFetchDataList("simple/data", "group2", data)
			.subscribe((data) => {
				this.groupList = data.list || [];
			});
	}
	
	// 选择处理组
	changeGroup(e){
		this.validatePriorityForm.controls.userId.setValue(null);
		this.getUserList();
	}
	
	// 获取处理人
	userList:any = [];
	getUserList() {
	  let data = {
			idx: 0,
			sum: 99999,
			user: {
				groupdata: {
					id: this.validatePriorityForm.value.groupId
				}
			}
		};
		this.mainService
			.getFetchDataList("data", "user", data)
			.subscribe((data) => {
				this.userList = data.list || [];
			});
	}
	
	// 获取告警优先级
	emergencyData:any = [];
	getEmergencyDic() {
	  this.mainService.getDictionary("list", "alarm_urgency").subscribe((data) => {
	    this.emergencyData = data || [];
	  });
	}
	
  // 新增优先级弹框
  modelName = ""; //模态框名称
  modalPriority: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  addPriorityModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modalPriority = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hidePriorityModal() {
    this.modalPriority = false;
  }

  changeCommonInp(type, e) {
    this.changeCommonInpSubject.next([type, e]);
  }

	// 获取故障现象数据
  isLoading:boolean = false;
	searchApplicationCategory(keyWord?){
		let postData = {
		  category: {
        category: keyWord,
        selectType: "mutlQuery",
		    hierarchy: 3,
		  },
		};
    this.isLoading = true;
		this.mainService.incidentPost("listIncidentCategory", postData).subscribe(data => {
		  this.isLoading = false;
      if (data.status == 200) {
        this.malfunctionData = data.data || [];
      }
		})
	}

  // 编辑
  editPriority(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modalPriority = true;
    this.initForm();
    this.coopData = data;
    this.validatePriorityForm.controls.alarmUrgency.setValue(data.alarmUrgency.id);
    this.validatePriorityForm.controls.keywords.setValue(data.keywords?data.keywords:null);
    this.validatePriorityForm.controls.categoryId.setValue(data.categoryDTO?data.categoryDTO.id:null);
		this.validatePriorityForm.controls.groupId.setValue(data.groupDTO.id);
		if(data.groupDTO.id){
			this.getUserList()
			this.validatePriorityForm.controls.userId.setValue(data.userDTO?data.userDTO.id:null);
		}
		this.validatePriorityForm.controls.flag.setValue(data.flag);
  }

  // 新增/编辑表单提交
  btnLoading: boolean = false; //提交按钮loading状态
  submitPriorityForm(): void {
    for (const i in this.validatePriorityForm.controls) {
      this.validatePriorityForm.controls[i].markAsDirty();
      this.validatePriorityForm.controls[i].updateValueAndValidity();
    }
    if (this.validatePriorityForm.invalid) {
      return;
    }
    console.log(this.validatePriorityForm.value);
    this.btnLoading = true;
    let postData:any = {};
    if (this.add) {
      //增加
      postData = {
				alarmConfig:{
					alarmUrgency: {
						id: this.validatePriorityForm.value.alarmUrgency
					},
					keywords: this.validatePriorityForm.value.keywords || undefined,
					categoryId: this.validatePriorityForm.value.categoryId,
					groupId: this.validatePriorityForm.value.groupId,
					userId: this.validatePriorityForm.value.userId || undefined,
					flag: this.validatePriorityForm.value.flag,
				}
      };
    } else {
      //编辑
      postData = {
				alarmConfig:{
					...this.coopData,
					alarmUrgency: {
						id: this.validatePriorityForm.value.alarmUrgency
					},
					keywords: this.validatePriorityForm.value.keywords || undefined,
					categoryId: this.validatePriorityForm.value.categoryId,
					groupId: this.validatePriorityForm.value.groupId,
					userId: this.validatePriorityForm.value.userId || undefined,
					flag: this.validatePriorityForm.value.flag,
				}
      };
    }
    this.mainService
      .dataPost(this.add ? "addData": "updData", "alarmConfig", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hidePriorityModal();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          this.showPromptModal(msg, true, '');
        } else {
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 初始化新增form表单
  validatePriorityForm: FormGroup; //新增/编辑表单
  initForm() {
    this.validatePriorityForm = this.fb.group({
      alarmUrgency: [null, [Validators.required]],
      keywords: [null, []],
      categoryId: [null, [Validators.required]],
			groupId: [null, [Validators.required]],
			userId: [null, []],
			flag: [1, [Validators.required]],
    });
    console.log(this.validatePriorityForm.controls)
  }

  // 获取列表
  loading1:boolean = false;
  commonFaultsList: any[] = []; //表格数据
  tablePriorityHeight:number = 0;
  getCommonFaultsList() {
    let data = {
			idx: 0,
			sum: 99999,
			alarmConfig: {
				hosId: this.hosId
			},
		};
		this.loading1 = true;
		this.mainService
			.getFetchDataList("simple/data", "alarmConfig", data)
			.subscribe((data) => {
				this.loading1 = false;
				this.commonFaultsList = data.list || [];
			});
  }

  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;
    console.log(this.coopData);
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
		this.mainService
			.simplePost("rmvData", "alarmConfig", [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);
				}
			});
  }

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