import { Component, OnInit, ViewChild, Input } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { MainService } from "../../../services/main.service";
import { Validators, FormGroup, FormBuilder, FormControl } from '@angular/forms';
import { ToolService } from 'src/app/services/tool.service';
import { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';
import { NzMessageService } from 'ng-zorro-antd';
import { v4 as uuidv4, validate as uuidValidate } from 'uuid';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: "app-configuration-dictionary",
  templateUrl: "./configuration-dictionary.component.html",
  styleUrls: ["./configuration-dictionary.component.less"],
})
export class ConfigurationDictionaryComponent 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;
	changeCommonInpSubject = new Subject();
	hosId:any;
	
  ngOnInit() {
    this.activeDictionaryKey = this.dictionaryKeyList[0];
		this.hosId = this.tool.getCurrentHospital().id;
    this.getDictionaryList();
    this.initDictionaryForm();
		this.getHosList();
  }

  // 数据字典key列表
  @Input() dictionaryKeyList: any[] = [];

  // 点击数据字典key
  activeDictionaryKey:any;
  clickDictionaryKey(item){
    this.activeDictionaryKey = item;
		if(item.key=='business_type'){
			setTimeout(() => {
			  this.tablePriorityHeight = document.querySelector('#priorityTable').clientHeight - document.querySelector('#priorityTable .list-template__top').clientHeight - 8 - document.querySelector('#priorityTable .thead').clientHeight;
			}, 100)
			this.getCommonFaultsList();
		}else{
			this.getDictionaryList();
		}
  }

  btnLoading: boolean = false; //提交按钮loading状态
  // ------------------------------

  // 展示信息提示框（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(this.activeDictionaryKey.key=='business_type'){
			this.getCommonFaultsList();
		}else{
			this.getDictionaryList();
		}
  }

  coopData: any = {}; //当前操作列

  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() {
    this.btnLoading = true;
    if (this.confirmDelType === "delDictionary") {
      //删除-数据字典
      this.mainService
        .simplePost("rmvData", "dictionary", [this.coopData.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.mainService.clearDictionary();
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }

  // 初始化数据字典新增form表单
  validateDictionaryForm: FormGroup; //新增/编辑表单
  dictionaryList: any = [];
  initDictionaryForm() {
    this.validateDictionaryForm = this.fb.group({
      // name: [null, [Validators.required]],//键
      // value: [null, [Validators.required]],//值
      // orders: [null, [Validators.required]],//排序号
    });
    console.log(this.validateDictionaryForm.controls)
  }

  // 获取数据字典数据
  maskFlag: any = false;
	initTyepe:boolean = false;
  getDictionaryList() {
		this.initTyepe = false
    let postData = {
      idx: 0,
      sum: 9999,
      dictionary: {
        key: this.activeDictionaryKey.key,
      }
    }
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService.getFetchDataList('simple/data','dictionary',postData).subscribe(data => {
      this.message.remove(this.maskFlag);
      this.maskFlag = false;
      let list = data.list || [];
      if(list.length){
				if(this.activeDictionaryKey.key == 'alarm_urgency'){
					this.dictionaryList = list.map(v => {
					  return {
					    id: v.id,
					    name: v.name || null,
					    value: v.value || null,
					    orders: v.orders || null,
					    system: v.system || false,
							extra1: v.extra1 || null,
					  }
					});
				}else{
					this.dictionaryList = list.map(v => {
					  return {
					    id: v.id,
					    name: v.name || null,
					    value: v.value || null,
					    orders: v.orders || null,
					    system: v.system || false,
					  }
					});
				}
      }else{
				if(this.activeDictionaryKey.key == 'alarm_urgency'){
					this.dictionaryList = [
					  {
					    id: uuidv4(),
					    name: null,
					    value: null,
					    orders: null,
					    system: false,
							extra1: null,
					  }
					];
				}else{
					this.dictionaryList = [
					  {
					    id: uuidv4(),
					    name: null,
					    value: null,
					    orders: null,
					    system: false,
					  }
					];
				}
      }

      // 动态添加表单
      this.dictionaryList.forEach((obj, i) => {
        for (const key in obj) {
          if(key !== 'id' && key !== 'system'){
            if(this.activeDictionaryKey.key === 'incident_status' || this.activeDictionaryKey.key === 'incident_degree' || this.activeDictionaryKey.key === 'abo_type' || this.activeDictionaryKey.key === 'rh_type' || this.activeDictionaryKey.key === 'blood_unit' || this.activeDictionaryKey.key === 'blood_trans_type'){
              this.validateDictionaryForm.addControl(key + '_' + obj.id, new FormControl({value: obj[key], disabled: true}, [Validators.required]))
            }else if(this.activeDictionaryKey.key === 'alarm_urgency'){
              this.validateDictionaryForm.addControl(key + '_' + obj.id, new FormControl({value: obj[key], disabled: key === 'value' ? obj.system : false}, []))
            }else{
							this.validateDictionaryForm.addControl(key + '_' + obj.id, new FormControl({value: obj[key], disabled: key === 'value' ? obj.system : false}, [Validators.required]))
						}
          }
        }
      })
			setTimeout(_=>{
				this.initTyepe = true
			},1000)
    })
  }

  // 添加数据字典
  addField(i:number): void{
		let obj:any = {}
		if(this.activeDictionaryKey.key == 'alarm_urgency'){
			obj = {
			  id: uuidv4(),
			  name: null,
			  value: null,
			  orders: null,
			  system: false,
				extra1:null,
			};
		}else{
			obj = {
			  id: uuidv4(),
			  name: null,
			  value: null,
			  orders: null,
			  system: false,
			};
		}


    // 动态添加表单
    for (const key in obj) {
      console.log(key + '_' + obj.id)
      if(key !== 'id' && key !== 'system'){
				if(key !== 'extra1'){
					this.validateDictionaryForm.addControl(key + '_' + obj.id, new FormControl(null, [Validators.required]))
				}else{
					this.validateDictionaryForm.addControl(key + '_' + obj.id, new FormControl(null, []))
				}
      }
    }

    this.dictionaryList.splice(i + 1, 0, obj);
  }

  // 删除
  removeField(obj, i:number): void {
    if(uuidValidate(obj.id)){
      this.dictionaryList.splice(i, 1);
      this.dictionaryList = [...this.dictionaryList];
      // 动态删除表单
      for (const key in obj) {
        this.validateDictionaryForm.removeControl(key + '_' + obj.id);
      }
    }else{
      this.showDelModal(obj,'您确认要删除吗？','删除','delDictionary')
    }
  }

  // 保存数据字典
  saveDictionary(): void {
    for (const i in this.validateDictionaryForm.controls) {
      this.validateDictionaryForm.controls[i].markAsDirty();
      this.validateDictionaryForm.controls[i].updateValueAndValidity();
    }
    if (this.validateDictionaryForm.invalid) {
      return;
    }
    console.log(this.validateDictionaryForm.value);
    let postData:any = {};

    //增加
    postData = [];
    let rawValueObj = this.validateDictionaryForm.getRawValue();
    for (let i = 0; i < this.dictionaryList.length; i++) {
      postData.push({
        id: uuidValidate(this.dictionaryList[i].id) ? undefined : this.dictionaryList[i].id,
        name: rawValueObj['name_' + this.dictionaryList[i].id],
        value: rawValueObj['value_' + this.dictionaryList[i].id],
        orders: rawValueObj['orders_' + this.dictionaryList[i].id],
				extra1: this.activeDictionaryKey.key == 'alarm_urgency' ? rawValueObj['extra1_' + this.dictionaryList[i].id]: undefined,
        system: uuidValidate(this.dictionaryList[i].id) ? false : this.dictionaryList[i].system,
        key: this.activeDictionaryKey.key,
      })
    }

    this.btnLoading = true;
    this.mainService
      .simplePost("addListData", "dictionary", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        if (result.status == 200) {
          this.mainService.clearDictionary();
          this.showPromptModal('保存', true, '');
        } else {
          this.showPromptModal('保存', false, result.msg || '');
        }
      });
  }
	
	// 获取院区
	hospitalList:any = [];
	getHosList() {
	  let data = {
			idx: 0,
			sum: 99999,
		};
		this.mainService
			.getFetchDataList("data", "hospital", data)
			.subscribe((data) => {
				this.hospitalList = data.list || [];
			});
	}
	
	// 选择院区
	taskTypeList:any = [];
	changeHos(e){
		this.validatePriorityForm.controls.taskTypeIds.setValue(null);
		this.getTsakTypeList('add');
	}
	
	// 获取任务类型
	userList:any = [];
	getTsakTypeList(type, obj?) {
	  let data = {
	  	idx: 0,
	  	sum: 99999,
			taskType:{
				simpleQuery:true,
				hosIds: this.validatePriorityForm.value.hosId
			}
	  };
	  this.mainService
	  	.getFetchDataList("configuration", "taskType", data)
	  	.subscribe((data) => {
	  		this.taskTypeList = data.list || [];
				if(type=='edit'){
					this.validatePriorityForm.controls.taskTypeIds.setValue(obj);
				}
	  	});
	}
	
	// 新增优先级弹框
	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;
	// 编辑
	edit(data) {
	  this.modelName = "编辑";
	  this.add = false;
	  this.modalPriority = true;
	  this.initForm();
	  this.coopData = data;
	  this.validatePriorityForm.controls.hosId.setValue(data.hospitalDTO.id);
	  this.validatePriorityForm.controls.businessName.setValue(data.businessName?data.businessName:null);
	  this.validatePriorityForm.controls.businessCode.setValue(data.businessCode);
		let taskType = data.taskTypeIds.split(',')
		taskType = taskType.map(i=>{
			return parseInt(i)
		})
		this.getTsakTypeList('edit', taskType);
	}
	
	// 新增/编辑表单提交
	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 = {
				businessTaskType:{
					hosId: this.validatePriorityForm.value.hosId,
					businessName: this.validatePriorityForm.value.businessName || undefined,
					businessCode: this.validatePriorityForm.value.businessCode,
					taskTypeIds: this.validatePriorityForm.value.taskTypeIds.toString(),
				}
	    };
	  } else {
	    //编辑
	    postData = {
				businessTaskType:{
					...this.coopData,
					hosId: this.validatePriorityForm.value.hosId,
					businessName: this.validatePriorityForm.value.businessName || undefined,
					businessCode: this.validatePriorityForm.value.businessCode,
					taskTypeIds: this.validatePriorityForm.value.taskTypeIds.toString(),
				}
	    };
	  }
	  this.mainService
	    .dataPost(this.add ? "addData": "updData", "businessTaskType", 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]],
	    businessName: [null, [Validators.required]],
	    businessCode: [null, [Validators.required]],
			taskTypeIds: [null, [Validators.required]],
	  });
	}
	
	// 获取列表
	loading1:boolean = false;
	commonFaultsList: any[] = []; //表格数据
	tablePriorityHeight:number = 0;
	getCommonFaultsList() {
	  let data = {
			idx: 0,
			sum: 99999,
			// businessTaskType: {
			// 	hosId: this.hosId
			// },
		};
		this.loading1 = true;
		this.mainService
			.getFetchDataList("simple/data", "businessTaskType", data)
			.subscribe((data) => {
				this.loading1 = false;
				data.list.forEach(i=>{
					i.taskTypeName = i.taskTypeDTOS.map(i=>{
						return i.taskName
					}).toString()
				})
				this.commonFaultsList = data.list || [];
			});
	}
	
	// 删除业务类型
	showBusinessModal(data){
		this.coopData = data
		this.delBusinessModal = true;
	}
	
	// 隐藏删除框
	delBusinessModal:boolean = false;
	hideBusinessModal() {
	  this.delBusinessModal = false;
	}
	// 确认删除
	confirmBusiness() {
	  this.btnLoading = true;
		this.mainService
			.simplePost("rmvData", "businessTaskType", [this.coopData.id])
			.subscribe((data) => {
				this.btnLoading = false;
				this.delBusinessModal = false;
				if (data.status == 200) {
					this.showPromptModal(this.tipsMsg2, true, "");
				} else {
					this.showPromptModal(this.tipsMsg2, false, data.msg);
				}
			});
	}
}
