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

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

  coopData: any = {}; //当前操作列
  currentHospital; //当前院区
	maintainDept:any=[];
	@Input() hospitalTabList: any[] = [];
	changeCommonInpSubject = new Subject();
	
  ngOnInit() {
		this.activeDictionaryKey = this.hospitalTabList[0];
		this.maintainDept = this.tool.getUserInfoPermission().dutyList
    this.currentHospital = this.tool.getCurrentHospital();
		this.changeCommonInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  if(v[0] === 'category'){
		    this.searchApplicationCategory(v[1]);
		  }
		});
		this.getDicType();
		this.searchApplicationCategory();
  }
	
	activeDictionaryKey:any;
	clickDictionaryKey(item){
	  this.activeDictionaryKey = item;
	  this.getList();
	}
	
	// 获取评价字典
	dicData:any=[];
	alarmData:any = [];
	getDicType(){
		this.mainService.getDictionary("list", "incident_degree").subscribe((data) => {
			this.dicData = data
			this.getList();
		});
		
		this.mainService.getDictionary("list", "alarm_urgency").subscribe((data) => {
			this.alarmData = data
		});
	}
	
	itsmQuoteOtherDeptWorkHourType:any;
	itsmQuoteOtherDeptConsumableType:any;
	radioChange(data){
		console.log(123,data)
		if(data.key=='itsmParentConsumable' && data.value==1){
			let item = this.hospitalList.find(i=>i.key == 'itsmQuoteOtherDeptConsumable')
			item.show = true
			item.value = '0'
			this.itsmQuoteOtherDeptConsumableType = false
			let item2 = this.hospitalList.find(i=>i.key == 'itsmConsumableQuoteDept')
			item2.value = null
			
		}else if(data.key=='itsmParentConsumable' && data.value==0){
			let item = this.hospitalList.find(i=>i.key == 'itsmQuoteOtherDeptConsumable')
			item.show = false
		}
		
		if(data.key=='itsmQuoteOtherDeptWorkHour' && data.value==1){
			this.itsmQuoteOtherDeptWorkHourType = true
		}else if(data.key=='itsmQuoteOtherDeptWorkHour' && data.value==0){
			this.itsmQuoteOtherDeptWorkHourType = false
			let item = this.hospitalList.find(i=>i.key == 'itsmWorkHourQuoteDept')
			item.value = null
		}
		
		if(data.key=='itsmQuoteOtherDeptConsumable' && data.value==1){
			this.itsmQuoteOtherDeptConsumableType = true
		}else if(data.key=='itsmQuoteOtherDeptConsumable' && data.value==0){
			this.itsmQuoteOtherDeptConsumableType = false
			let item = this.hospitalList.find(i=>i.key == 'itsmConsumableQuoteDept')
			item.value = null
		}
		
		if(data.key=='itsmSimpleHandle' && data.value==1){
			let item = this.hospitalList.find(i=>i.key == 'itsmWriteSolution')
			item.show = false
		}else if(data.key=='itsmSimpleHandle' && data.value==0){
			let item = this.hospitalList.find(i=>i.key == 'itsmWriteSolution')
			item.show = true
		}
	}
	
	changeSelect(data){
		
	}
	
	// 获取故障现象数据
	isLoading:boolean = false;
	malfunctionData:any = [];
	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 || [];
	    }
		})
	}
	
	// 是否开启告警自动建单
	alarmAutoSwitch:boolean = false;
	radioAutoChange(data){
		if(data.key=='itsmAlarmAutoCreate' && data.value==1){
			this.alarmAutoSwitch = true
		}else if(data.key=='itsmAlarmAutoCreate' && data.value==0){
			this.alarmAutoSwitch = false
			this.hospitalList[1].value = null
			this.hospitalList[2].value = null
		}
	}
	
	changeCommonInp(type, e) {
	  this.changeCommonInpSubject.next([type, e]);
	}
	
  // 新增/编辑表单提交
  btnLoading: boolean = false; //提交按钮loading状态
  submitMessageForm(): void {
    this.btnLoading = true;
		for(let i of this.hospitalList){
			if(i.key=='itsmUserBadEvaluationRange' || i.key=='itsmCallbackBadEvaluationRange'){
				i.value = i.value.join(',')
			}
		}
		if(this.activeDictionaryKey.key=='alarm'){
			if(this.hospitalList[0].value==1){
				this.hospitalList[2].value = this.hospitalList[2].value.join(',')
			}
		}
		setTimeout(_=>{
			this.mainService
			  .simplePost("addListData", "hospitalConfig", this.hospitalList)
			  .subscribe((result) => {
			    this.btnLoading = false;
			    let msg = "保存";
			    if (result.status == 200) {
			      this.showPromptModal(msg, true, '');
			    } else {
			      this.showPromptModal(msg, false, result.msg);
			    }
			  });
		},50)
  }

  // 获取列表
  loading1:boolean = false;
  hospitalList:any[] = [];
  getList() {
    let data = {
      idx: 0,
      sum: 9999,
      hospitalConfig: {
        hosId: this.currentHospital.id,
        model: 'itsm',
				value2: this.activeDictionaryKey.key
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "hospitalConfig", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
					data.list.forEach(i =>{
					  i.show = false
					})
					let newData = data.list
					for(let i of newData){
						if(i.key=='itsmParentConsumable' && i.value==1){
							let item = newData.find(i=>i.key == 'itsmQuoteOtherDeptConsumable')
							item.show = true
							item.value = '0'
							this.itsmQuoteOtherDeptConsumableType = false
							let item2 = newData.find(i=>i.key == 'itsmConsumableQuoteDept')
							item2.value = null
						}else if(i.key=='itsmParentConsumable' && i.value==0){
							let item = newData.find(i=>i.key == 'itsmQuoteOtherDeptConsumable')
							item.show = false
						}
						
						if(i.key=='itsmQuoteOtherDeptWorkHour' && i.value==1){
							this.itsmQuoteOtherDeptWorkHourType = true
							let item = newData.find(i=>i.key == 'itsmWorkHourQuoteDept')
							item.value = Number(item.value)
						}else if(i.key=='itsmQuoteOtherDeptWorkHour' && i.value==0){
							this.itsmQuoteOtherDeptWorkHourType = false
						}
						
						if(i.key=='itsmQuoteOtherDeptConsumable' && i.value==1){
							this.itsmQuoteOtherDeptConsumableType = true
							let item = newData.find(i=>i.key == 'itsmConsumableQuoteDept')
							item.value = Number(item.value)
						}else if(i.key=='itsmQuoteOtherDeptConsumable' && i.value==0){
							this.itsmQuoteOtherDeptConsumableType = false
						}
						
						if(i.key=='itsmUserEvaluation' || i.key=='itsmCallbackEvaluation' || i.key=='itsmAlarmDefaultCategory'){
							if(i.value){
								i.value = Number(i.value)
							}
						}
						
						if(i.key=='itsmUserBadEvaluationRange' || i.key=='itsmCallbackBadEvaluationRange' || i.key=='itsmAlarmUrgentRange'){
							if(i.value){
								let arr = i.value.split(',')
								arr = arr.map(i=>i = parseInt(i))
								i.value = arr
							}
						}
						
						if(i.key=='itsmSimpleHandle' && i.value==1){
							let item = newData.find(i=>i.key == 'itsmWriteSolution')
							item.show = false
						}else if(i.key=='itsmSimpleHandle' && i.value==0){
							let item = newData.find(i=>i.key == 'itsmWriteSolution')
							item.show = true
						}
						
						if(i.key=='itsmAlarmAutoCreate' && i.value==1){
							this.alarmAutoSwitch = true
						}else if(i.key=='itsmAlarmAutoCreate' && i.value==0){
							this.alarmAutoSwitch = false 
							let item1 = newData.find(i=>i.key == 'itsmAlarmUrgentRange')
							if(item1.value){
								item1.value = null
							}
							let item2 = newData.find(i=>i.key == 'itsmAlarmDefaultCategory')
							if(item2.value){
								item2.value = null
							}
						}
					}

          this.hospitalList = newData || [];
        }else{
          this.message.error(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.getList();
  }
}
