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-custom-business",
  templateUrl: "./configuration-custom-business.component.html",
  styleUrls: ["./configuration-custom-business.component.less"],
})
export class ConfigurationCustomBusinessComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private mainService: MainService,
    private fb: FormBuilder,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}
	@Input() customBusinessList: 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.customBusinessList[0];
		this.changeCommonInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getDept('add', {}, v);
    });

    // 优先级
    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.getHosList();
  }
	
	activeDictionaryKey:any;
	clickDictionaryKey(item){
		this.activeDictionaryKey = item;
		if(item.key=='one_connect'){
			this.getCommonFaultsList();
		}
	}
	
	// 获取院区
	hospitalList:any = [];
	connectList:any = [];
	getHosList() {
	  let data = {
			idx: 0,
			sum: 99999,
		};
		this.mainService
			.getFetchDataList("data", "hospital", data)
			.subscribe((data) => {
				this.hospitalList = data.list || [];
			});
			
		this.mainService.getDictionary("list", "business_handover_type").subscribe((data) => {
		  this.connectList = data || [];
		});
	}
	
	// 选择院区
	taskTypeList:any = [];
	changeHos(type, data?){
		this.validatePriorityForm.controls.associationDept.setValue(null);
		this.validatePriorityForm.controls.taskType.setValue(null);
		this.getDept(type, data, '');
		this.getTsakTypeList(type, data);
	}
	
	// 获取任务类型
	userList:any = [];
	getTsakTypeList(type, obj?) {
	  let query = {
	  	idx: 0,
	  	sum: 99999,
			taskType:{
				simpleQuery:true,
				hosIds: this.validatePriorityForm.value.hosId
			}
	  };
	  this.mainService
	  	.getFetchDataList("configuration", "taskType", query)
	  	.subscribe((data) => {
	  		this.taskTypeList = data.list.filter(i=>i.associationType.value == 'other');
				if(type=='edit'){
					this.validatePriorityForm.controls.taskType.setValue(obj.taskType);
				}
	  	});
	}
	
	// 获取科室
	deptData:any = [];
	getDept(type, obj:any = {}, dept?) {
		if(!this.validatePriorityForm.value.hosId){
			return
		}
	  let query = {
	  	idx: 0,
	  	sum: 20,
	  	department:{
	  		hospital: {
					id: this.validatePriorityForm.value.hosId
				},
				dept: dept
	  	}
	  };
	  this.mainService
	  	.getFetchDataList("data", "department", query)
	  	.subscribe((data) => {
				this.isLoading = false;
	  		this.deptData = data.list || [];
				if(type == 'edit'){
					let item = this.deptData.find(i=>i.id == obj.associationDeptDTO.id)
					if(!item){
						this.deptData.push({
							dept: obj.associationDeptDTO.dept,
							id: obj.associationDeptDTO.id
						})
					}
					this.validatePriorityForm.controls.associationDept.setValue(obj.associationDeptDTO.id);
				}
	  	});
	}
	
  // 新增优先级弹框
  modelName = ""; //模态框名称
  modalPriority: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  addPriorityModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modalPriority = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hidePriorityModal() {
    this.modalPriority = false;
  }

	isLoading:boolean = false;
	// 搜索科室
  changeCommonInp( e) {
		this.isLoading = true
    this.changeCommonInpSubject.next(e);
  }

  // 编辑
  editPriority(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modalPriority = true;
    this.initForm();
    this.coopData = data;
    this.validatePriorityForm.controls.hosId.setValue(data.hosId);
    this.validatePriorityForm.controls.orders.setValue(data.orders);
    this.validatePriorityForm.controls.handoverName.setValue(data.handoverName);
		this.validatePriorityForm.controls.handoverType.setValue(data.handoverType.id);
		this.changeHos('edit', data)
	}

  // 新增/编辑表单提交
  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 = {
				businessHandoverConfig:{
					hosId: this.validatePriorityForm.value.hosId,
					orders: this.validatePriorityForm.value.orders || undefined,
					handoverName: this.validatePriorityForm.value.handoverName,
					associationDept: this.validatePriorityForm.value.associationDept || undefined,
					handoverType: {
						id: this.validatePriorityForm.value.handoverType
					},
					taskType: this.validatePriorityForm.value.taskType,
				}
      };
    } else {
      //编辑
      postData = {
				businessHandoverConfig:{
					...this.coopData,
					hosId: this.validatePriorityForm.value.hosId,
					orders: this.validatePriorityForm.value.orders || undefined,
					handoverName: this.validatePriorityForm.value.handoverName,
					associationDept: this.validatePriorityForm.value.associationDept || undefined,
					handoverType: {
						id: this.validatePriorityForm.value.handoverType
					},
					taskType: this.validatePriorityForm.value.taskType,
				}
      };
    }
    this.mainService
      .dataPost(this.add ? "addData": "updData", "businessHandoverConfig", 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({
      hosId: [null, [Validators.required]],
      orders: [null, [Validators.required]],
      handoverName: [null, [Validators.required]],
			associationDept: [null, [Validators.required]],
			handoverType: [null, [Validators.required]],
			taskType: [null, [Validators.required]],
    });
		this.deptData = [];
		this.taskTypeList = [];
    console.log(this.validatePriorityForm.controls)
  }

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