import { Component, OnInit, ViewChild } 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 { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';
import { NzMessageService } from "ng-zorro-antd";

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

  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef3", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef3: OverlayScrollbarsComponent;

  coopData: any = {}; //当前操作列
  currentHospital; //当前院区
  // 部门设置、全院设置
  hospitalConfig:any = 2;
  hospitalConfigList:any = [
    // { id: 1, name: '部门设置',},
    { id: 2, name: '全院设置',},
  ];
	hosId:any;
  debounceSubject = new Subject(); //防抖

  ngOnInit() {
    this.debounceSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[0]){
        this.getCategoryList(v[0], v[1].id);
      }
    });

    this.currentHospital = this.tool.getCurrentHospital();
		this.hosId = this.tool.getCurrentHospital().id;
    this.getCategoryList(1);
    this.getScores();
  }


	// 监听单位输入
	workUnitshow:boolean = false;
	handleInput(event: KeyboardEvent){
		const input = event.target as HTMLInputElement;
		if (input.value.length>2) {
			this.workUnitshow = true
		} else{
			this.workUnitshow = false
		}
	}

  // 获取积分
  scoreList: any = [];
  getScores() {
    let postData = {
      dictionary: {
        key: "incident_category_score"
      },
      idx: 0,
      sum: 99999,
    };
    this.mainService
      .getFetchDataList("simple/data", "dictionary", postData)
      .subscribe((data) => {
        this.scoreList = data.list || [];
      });
  }

  // 点击故障现象
  activeCategory1:any = {};
  activeCategory2:any = {};
  activeCategory3:any = {};
  clickCategory(item, type:number){
		this.coopType = type
    switch(type){
      case 1:
        this.categoryList2 = [];
        this.categoryList3 = [];
        this.activeCategory2 = {};
        this.activeCategory3 = {};
        break;
      case 2:
        this.categoryList3 = [];
        this.activeCategory3 = {};
        break;
    }
    this['activeCategory' + type] = item;
    console.log(this['activeCategory' + type])
    switch(type){
      case 1:
        this.categoryLoading2 = true;
        this.loading1 = true;
        this.debounceSubject.next([2, item]);
        break;
      case 2:
        this.categoryLoading3 = true;
        this.loading1 = true;
        this.debounceSubject.next([3, item]);
        break;
    }
  }

	// 取消删除弹框
	cancelDel(){
		this.hideDelModal();
	}

	// 确认删除
	confirmDel() {
	  let that = this;
	  that.btnLoading = true;
		let delId = null
		console.log(222,this.coopType)
		if(this.coopType==1){
			delId = this.activeCategory1.id
		}else{
			delId = this.activeCategory2.id
		}
	  that.mainService
	    .coopTypeConfig('rmvData', 'workHourManagement', [delId])
	    .subscribe((data) => {
	      that.btnLoading = false;
	      that.hideDelModal();
				if(this.coopType==1){
					this.categoryList2 = []
				}
	      if (data["status"] == 200) {
	        that.showPromptModal("删除", true, "");
	      } else {
	        that.showPromptModal("删除", false, data["msg"]);
	      }
	    });
	}

	// 关闭删除模态框
	hideDelModal() {
	  this.delModal = false;
	}
	
	// 日志列表
	listLogOfData: any[] = []; //日志数据
	pageLogIndex: number = 1; //日志当前页码
	pageLogSize: number = 10; //日志每页展示条数
	listLogLength: number = 10; //日志总数据量
	loading2:boolean = false;
	getLogList(type) {
	  if (type == 1) {
	    this.pageLogIndex = 1;
	  }
	  let postData = {
	  	idx: this.pageLogIndex - 1,
	  	sum: this.pageLogSize,
	  	workHourManagementLog: {
	  		workHourId: this.itemData.id,
	  	},
	  };
	  this.loading2 = true;
	  this.mainService
	    .getFetchDataList("simple/data", "workHourManagementLog", postData)
	    .subscribe((data) => {
	      this.loading2 = false;
	      if (data.status == 200) {
					this.logModal = true
	        this.listLogOfData = data.list;
	        this.listLogLength = data.totalNum;
	      }else{
	        this.message.error(data.msg || "请求数据失败");
	      }
	    });
	}
	
	// 启用/停用工时
	operationModal: boolean = false; 
	operationContent: string = null; 
	operation(type:number){
		if(type==1){
			let msg = this.activeCategory1.disableType==1?'停用':'启用'
			if(this.activeCategory1.disableType==1){
				this.operationContent = `您确认${msg}大类工时吗？${msg}后所有小类同时${msg}`
			}else{
				this.operationContent = `您确认${msg}大类工时吗？`
			}
		}else{
			let msg = this.activeCategory2.disableType==1?'停用':'启用'
			this.operationContent = `您确认${msg}小类工时吗？`
		}
		this.coopType = type;
		this.operationModal = true
	}
	
	hideOperationModal(){
		this.operationModal = false
	}
	
	// 取消启用/停用弹框
	cancelOperation(){
		this.hideOperationModal();
	}
	
	// 确认启用/停用
	confirmOperation() {
	  let that = this;
		let disableType = null
	  that.btnLoading = true;
		if(this['activeCategory' + this.coopType].disableType==1){
			disableType = 0
		}else{
			disableType = 1
		}
		let postData = {
		  workHourManagement: {
				...this['activeCategory' + this.coopType],
				disableType:disableType,
				upType: 'disable'
		  }
		}
	  that.mainService
	    .coopData('updData', 'workHourManagement', postData)
	    .subscribe((data) => {
	      that.btnLoading = false;
				if(disableType==1){
					this['activeCategory' + this.coopType].disableType = 1
				}else{
					this['activeCategory' + this.coopType].disableType = 0
				}
	      that.hideOperationModal();
				if(this.coopType==1){
					this.categoryList2 = []
				}
	      if (data["status"] == 200) {
	        that.showPromptModal("操作", true, "");
	      } else {
	        that.showPromptModal("操作", false, data["msg"]);
	      }
	    });
	}
	
	// 查看日志
	itemData:any = {};
	logModal:boolean = false;
	addLogModal(type){
		this.itemData = this['activeCategory' + type];
		console.log(this['activeCategory' + type])
		this.getLogList(1)
	}
	
	// 关闭日志
	hideModal() {
	  this.logModal = false;
	}
	
  // 获取工时
  loading1:boolean = false;
  tableCategoryHeight:number = 0;
  categoryList1: any[] = [];
  categoryList2: any[] = [];
  categoryList3: any[] = [];
  categoryLoading1:boolean = false;
  categoryLoading2:boolean = false;
  categoryLoading3:boolean = false;
  getCategoryList(type:number, parentId = 0, isEdit = false, isOnly = false) {
    setTimeout(() => {
      this['categoryLoading' + type] = true;
    }, 0)
    let postData = {
			idx: 0,
			sum: 99999,
			workHourManagement: {
				hosId: this.hosId,
				treeLevel: type,
        quoteOther: 0,
				parent: type === 1 ? null : { id: parentId }
			}
    };
		this.mainService
		  .getFetchDataList("data", "workHourManagement", postData)
		  .subscribe((res) => {
		    this['categoryLoading' + type] = false;
		    this['categoryList' + type] = res.list || [];
        console.log(this['activeCategory' + type])
        if(isEdit){
          this['activeCategory' + type] = this['categoryList' + type].find(v => v.id == this['activeCategory' + type].id);
        }

        if(isOnly){
          this['activeCategory' + type] = this['categoryList' + type].find(v => v.id == this.validateCategoryForm.value.parent);
        }
		  });
  }

  // 新增故障现象弹框
  modelName = ""; //模态框名称
  add: boolean; //true:新增；false:编辑
  modalCategory: boolean = false; //新增/编辑模态框
  coopType: number = 0;
  addCategoryModal(type:number) {
    this.coopType = type;
    this.modelName = "新增";
    this.add = true; //新增
    this.modalCategory = true;
    this.initCategoryForm();
  }
  isLoading:boolean = false;
  // 编辑
  editCategoryModal(type:number) {
    this.coopType = type;
    this.modelName = "编辑";
    this.add = false; //编辑
    this.modalCategory = true;
    this.initCategoryForm();
    if(type == 1){
      this.requiredChange('parent', false);
    }else if(type == 2){
      this.requiredChange('parent', true);
    }
    console.log(this['activeCategory' + type])
    this.validateCategoryForm.controls.parent.setValue(this['activeCategory' + type].parent ? this['activeCategory' + type].parent.id : null);
    this.validateCategoryForm.controls.workName.setValue(this['activeCategory' + type].workName);
    this.validateCategoryForm.controls.workUnit.setValue(this['activeCategory' + type].workUnit);
    this.validateCategoryForm.controls.wage.setValue(this['activeCategory' + type].wage);
    this.validateCategoryForm.controls.integral.setValue(this['activeCategory' + type].integral ? this['activeCategory' + type].integral.id : null);
  }

  requiredChange(field: string, required: boolean): void {
    if (!required) {
      this.validateCategoryForm.get(field)!.clearValidators();
      this.validateCategoryForm.get(field)!.markAsPristine();
    } else {
      this.validateCategoryForm.get(field)!.setValidators(Validators.required);
      this.validateCategoryForm.get(field)!.markAsDirty();
    }
    this.validateCategoryForm.get(field)!.updateValueAndValidity();
  }

	// 删除工时
	delModal: boolean = false; //删除模态框
	delContent: string = null; //删除模态框
	delCategoryModal(type:number){
		if(type==1){
			this.delContent = '此操作会删除当前大类下的小类,确定要删除吗？'
		}else{
			this.delContent = '确定要删除吗？'
		}
		this.coopType = type;
		this.delModal = true
	}

  //关闭新增/编辑弹框
  hideCategoryModal() {
    this.modalCategory = false;
  }

  // 初始化新增form表单
  validateCategoryForm: FormGroup; //新增/编辑表单
  initCategoryForm() {
    this.validateCategoryForm = this.fb.group({
      parent: [null],//工时大类
      workName: [null, [Validators.required]],//名称
			workUnit: [null, [Validators.required]],//单位
			wage: [null, [Validators.required]],//工价
			integral: [null, [Validators.required]],//工时积分
    });
  }


  // 新增/编辑表单提交
  btnLoading: boolean = false; //提交按钮loading状态
  submitCategoryForm(): void {
    for (const i in this.validateCategoryForm.controls) {
      this.validateCategoryForm.controls[i].markAsDirty();
      this.validateCategoryForm.controls[i].updateValueAndValidity();
    }
    if (this.validateCategoryForm.invalid) {
      return;
    }
		if(this.workUnitshow){
			this.message.error('单位长度不能多于2位')
			return;
		}
    console.log(this.validateCategoryForm.value);
    this.btnLoading = true;
    // -----------------------------------
    let postData:any;
    if(this.add){
      postData = {
        workHourManagement: {
          ...this.validateCategoryForm.value,
          integral:{
            id:this.validateCategoryForm.value.integral
          },
          hosId: this.hosId,
          treeLevel: this.coopType,
          parent: this.coopType === 1 ? undefined : this['activeCategory' + (this.coopType - 1)],
        }
      }
    }else{
      postData = {
        workHourManagement: {
          ...this['activeCategory' + this.coopType],
          ...this.validateCategoryForm.value,
          integral:{
            id:this.validateCategoryForm.value.integral
          },
          hosId: this.hosId,
          treeLevel: this.coopType,
          parent: { id: this.validateCategoryForm.value.parent },
        }
      }
    }

		this.mainService
			.coopData(this.add ? "addData" : "updData", "workHourManagement", postData)
			.subscribe((data) => {
				this.btnLoading = false;
				if (data.status == 200) {
					this.modalCategory = false
					this.showPromptModal(this.add ? "新增" : "编辑", true, "");
				} else {
					this.showPromptModal(this.add ? "新增" : "编辑", false, data.msg);
				}
			});
    // -----------------------------------
  }

  // 初始化新增form表单
  validateConfigForm: FormGroup; //新增/编辑表单
  initConfigForm() {
    this.validateConfigForm = this.fb.group({
      hosId: [null, [Validators.required]],//院区
      dutyId: [null, [Validators.required]],//责任部门
      priority: [null, [Validators.required]],//优先级
      score: [null, [Validators.required]],//积分
      userGroup: [1, [Validators.required]],//分配方式
      userId: [null],//维修人
      groupId: [null, [Validators.required]],//维修组
    });
    console.log(this.validateConfigForm.controls)
  }

	// 获取当前选中的故障现象索引
	get currentCategoryIndex(){
	  if(this.activeCategory3.id){
	    return 3;
	  }
	  if(this.activeCategory2.id){
	    return 2;
	  }
	  if(this.activeCategory1.id){
	    return 1;
	  }
	}

  // 展示信息提示框（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);
    if(con === '编辑'){
      if(success){
        if(this.coopType === 1){
          this.getCategoryList(1, 0, true);
        }else if(this.coopType === 2){
          this.getCategoryList(1, 0, false, true);
          this.getCategoryList(2, this.validateCategoryForm.value.parent, true);
        }
      }
    }else{
      if(this.coopType !== 0){
        this.getCategoryList(this.coopType, this.coopType === 1 ? undefined : this['activeCategory' + (this.coopType - 1)].id);
      }else{
        this.getCategoryList(this.currentCategoryIndex, this.currentCategoryIndex === 1 ? undefined : this['activeCategory' + (this.currentCategoryIndex - 1)].id);
      }
      if(this.activeCategory2.id || this.activeCategory1.id){
        this.getCategoryList(this.activeCategory2.id || this.activeCategory1.id);
      }
    }
  }
}
