import { Component, OnInit } 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-deptUser",
  templateUrl: "./configuration-deptUser.component.html",
  styleUrls: ["./configuration-deptUser.component.less"],
})
export class ConfigurationDeptUserComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private mainService: MainService,
    private fb: FormBuilder,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}

  coopData: any = {}; //当前操作列
	pageIndex: number = 1; //页码
	listLength: number = 10; //总条数
	pageSize: number = 10; //每页条数
	hosId:any;
	hospitals:any = [];
	isDeptLoading: boolean = false;
	searchParentDeptSubject = new Subject();
	searchParentUserSubject = new Subject();
	currentHospital:any;
	malfunctionData:any = [];
	allUserGroup:any = [];
	userData:any = [];

  formatterMinute = (value: number) => `${value} 分钟`;
  parserMinute = (value: string) => value.replace(' 分钟', '');

  ngOnInit() {
		this.searchParentDeptSubject.pipe(debounceTime(500)).subscribe((e) => {
			this.isDeptLoading = true;
			this.getDeparts(e);
		});
		this.searchParentUserSubject.pipe(debounceTime(500)).subscribe((e) => {
			// this.isDeptLoading = true;
			// this.getUser(e);
		});

    // 优先级
    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.getPriorityList();
		this.getMalfunction()
		this.getDeparts('')
		// this.getUser('');
		this.getGrop()
  }

  // 新增优先级弹框
  modelName = ""; //模态框名称
  modalPriority: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  addPriorityModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modalPriority = true;
    this.initPriorityForm();
  }
  //关闭新增/编辑弹框
  hidePriorityModal() {
    this.modalPriority = false;
  }

	changeInp(e) {
	  this.searchParentDeptSubject.next(e);
	}

	changeInp3(e){
		this.searchParentUserSubject.next(e);
	}

	// 获取所有科室
	getDeparts(dept) {
	  var that = this;
	  let data = {
	    department: {
	      dept,
				cascadeHosId: this.currentHospital.id,
	    },
	    idx: 0,
	    sum: 9999,
	  };
		that.mainService
		  .getFetchDataList("data", "department", data)
		  .subscribe((data) => {
				setTimeout(_=>{
					this.hospitals = data.list
					that.isDeptLoading = false;
				},100)
		  });
	}

	// 获取故障现象数据
	getMalfunction(){
    let { hospital, type } = this.tool.getHospitalOrDuty();
		if(type === 'hospital' || type === 'department'){
		  this.malfunctionData = [];
		  return;
		};
		let postData = {
			hasThird: 'true',
		  category: {
		    dutyIds: type === 'duty' ? hospital.id.toString()  : undefined,
		  },
		};
		this.mainService.incidentPost("listIncidentCategory", postData).subscribe(res => {
		  let incidentCategoryList = res.data || [];
		  incidentCategoryList = incidentCategoryList.map(v => ({...v, parentId: v.parent ? v.parent.id : undefined, title: v.category, key: v.id, isLeaf: false}));
		  let arr = this.tool.tranListToTreeDataLeaf(incidentCategoryList, undefined, "parentId");
			for(let i of arr){
				for(let t of i.children){
					for(let x of t.children){
						this.malfunctionData.push({
							name:x.mutiCategory,
							id:x.id
						})
					}
				}
			}
		})
	}

	// 选择处理组
	changeGroup(e){
		this.validatePriorityForm.controls.handleUser.setValue(null)
		this.getUser(e)
	}

	// 获取处理组
	getGrop(){
		let groupData = {
		  group2: {
		    hospitals: this.hosId,
		    type:3
		  },
		  idx: 0,
		  sum: 9999,
		};
		this.mainService
		  .getFetchDataList("data", "group2", groupData)
		  .subscribe((data) => {
		    this.allUserGroup = data.list;
		  });
	}

	// 获取处理人
	getUser(groupId){
		let data = {
			idx: 0,
			sum: 9999,
			user: {
				// name:name,
				groupdata:{id:groupId || ""},
        roleCodes: 'first-line support',
        engineer: 1,
			},
		};
		this.mainService
			.getFetchDataList("data", "user", data)
			.subscribe((data) => {
				setTimeout(_=>{
					this.isDeptLoading = false
					this.userData = data.list;
				},100)
			});
	}

  // 编辑
  editPriority(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modalPriority = true;
    this.initPriorityForm();
    this.coopData = data;
		let deptArr = []
		for(let i of data.deptList){
			deptArr.push(i.id)
		}
    this.validatePriorityForm.controls.department.setValue(deptArr);
		if(data.handleGroupDTO){
			this.validatePriorityForm.controls.handleGroup.setValue(data.handleGroupDTO.id);
			this.getUser(data.handleGroupDTO.id)
		}
		this.validatePriorityForm.controls.binding.setValue(data.handleUserDTO?'1':'0')
		if(data.handleUserDTO){
			this.validatePriorityForm.controls.handleUser.setValue(data.handleUserDTO.id);
		}
		if(data.categoryList){
			let malfunction = []
			for(let i of data.categoryList){
				malfunction.push(i.id)
			}
			this.validatePriorityForm.controls.malfunction.setValue(malfunction)
			// let arr = []
			// for(let i of this.coopData.categoryList){
			// 	arr.push(this.tool.tranListToTreeDataFindIdsLeaf(this.malfunctionData,i.id))
			// }
			// this.validatePriorityForm.controls.malfunction.setValue(arr);
		}
  }

  // 新增/编辑表单提交
  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 = {};
		let malfunction = this.validatePriorityForm.value.malfunction?this.validatePriorityForm.value.malfunction:[]
    if (this.add) {
      //增加
      postData = {
				deptIds:this.validatePriorityForm.value.department.join(','), //科室
				categoryIds: malfunction.join(','),//故障
				handleGroup: this.validatePriorityForm.value.handleGroup,//处理组
				handleUser: this.validatePriorityForm.value.handleUser,//处理人
				hosId:this.hosId
      };
    } else {
      //编辑
      postData = {
				...this.coopData,
				deptIds:this.validatePriorityForm.value.department.join(','), //科室
				categoryIds: malfunction.join(','),//故障
				handleGroup: this.validatePriorityForm.value.handleGroup,//处理组
				handleUser: this.validatePriorityForm.value.handleUser,//处理人
				hosId:this.hosId
      };
    }
    this.mainService
      .simplePost("addData", "incidentAssignManager", 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);
        }
      });
  }

	changeRadio(e){
		if(this.validatePriorityForm.value.binding=='1'){
			this.validatePriorityForm = this.fb.group({
			  department: [this.validatePriorityForm.value.department, [Validators.required]],//科室
			  malfunction: [this.validatePriorityForm.value.malfunction, []],//故障
			  handleGroup: [this.validatePriorityForm.value.handleGroup, [Validators.required]],//处理组
				binding:['1',[Validators.required]],//是否绑定人员
			  handleUser: [this.validatePriorityForm.value.handleUser, [Validators.required]],//处理人
			});
		}else{
			this.validatePriorityForm = this.fb.group({
			  department: [this.validatePriorityForm.value.department, [Validators.required]],//科室
			  malfunction: [this.validatePriorityForm.value.malfunction, []],//故障
			  handleGroup: [this.validatePriorityForm.value.handleGroup, [Validators.required]],//处理组
				binding:['0',[Validators.required]],//是否绑定人员
			  handleUser: [null, []],//处理人
			});
		}
	}

  // 初始化新增form表单
  validatePriorityForm: FormGroup; //新增/编辑表单
  initPriorityForm() {
    this.validatePriorityForm = this.fb.group({
      department: [null, [Validators.required]],//科室
      malfunction: [null, []],//故障
      handleGroup: [null, [Validators.required]],//处理组
			binding:['0',[Validators.required]],//是否绑定人员
      handleUser: [null, []],//处理人
    });
    console.log(this.validatePriorityForm.controls)
  }

  // 获取列表
  loading1:boolean = false;
  priorityList: any[] = []; //表格数据
  tablePriorityHeight:number = 0;
  getPriorityList() {
    let data = {
			idx: this.pageIndex - 1,
			sum: this.pageSize,
			incidentAssignManager: {
				hosId: this.hosId || "" ,
			},
		};
		this.loading1 = true;
		this.mainService
			.getFetchDataList("data", "incidentAssignManager", data)
			.subscribe((data) => {
				this.loading1 = false;
				for(let i of data.list){
					i.dept = i.deptList.map(t=>{
						return t.dept
					})
					if(i.categoryList){
						i.category = i.categoryList.map(t=>{
							return t.mutiCategory
						})
						i.category= i.category.join('、')
					}
					i.dept = i.dept.join('、')
				}
				this.priorityList = data.list
				console.log(8888,this.priorityList)
				this.listLength = data.totalNum;
			});
  }

  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() {
		let ids = this.coopData.ids.split(',')
    this.btnLoading = true;
		//删除-优先级
		this.mainService
			.simplePost("rmvData", "incidentAssignManager", ids)
			.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.getPriorityList();
  }
}
