import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup, FormControl } from "@angular/forms";

import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { forkJoin, Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { NzMessageService } from "ng-zorro-antd";

@Component({
  selector: "app-share-specimen",
  templateUrl: "./share-specimen.component.html",
  styleUrls: ["./share-specimen.component.less"],
})
export class ShareSpecimenComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private tool: ToolService
  ) {}

  listOfData: any[] = []; //表格数据

  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  dept: any; //所属科室
  drugCode; //编号
  name; //名称
  userType: any; //用户类型
  hosId: any; //院区（搜索）
  userGroup; //所属组
  userGroup1; //所属组(搜索)
  userTypes: Array<any>; //所有用户类型
  alldepart: any = []; //所有所属科室
  alldepart1: any = []; //所有所属科室(搜索)
  hospitals1: any = []; //院区列表(搜索)
	drugTypeData: any = []; //药品类型
  allUserGroup: Array<any>; //所有用户组
  allUserGroup1: Array<any>; //用户组(搜索)
  allUserRole: Array<any>; //所有角色
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示

  btnLoading: boolean = false; //提交按钮loading状态
  wxRequired = false; //新增或编辑用户的时候，微信号是否必填
  changeInpSubject = new Subject(); //防抖
	searchParentDeptSubject = new Subject();
	specimenName:any = null;
	containPosition:any = null;
	placeList:any = [];
	systemList:any = [];
	apparatusList:any = [];
	specimenNameList:any = [];
	addressLoading:any = false;
	
  ngOnInit() {
    this.coopBtns = this.tool.initCoopBtns(this.route);
		this.hosId = this.tool.getCurrentHospital().id;
		this.searchParentDeptSubject.pipe(debounceTime(500)).subscribe((e) => {
			this.isDeptLoading = true;
			this.getDeparts(e[0])
		});
    this.initForm();
		this.getDeparts('');
		this.getList();
		this.getSourceData();
		this.getSysData();
  }

  // 初始化增删改按钮
  coopBtns: any = {};
  // 搜索
  search() {
    this.pageIndex = 1;
    this.getList();
  }
  // 重置
  reset() {
    this.pageIndex = 1;
    this.dept = null;
    this.containPosition = null;
		this.specimenName = null
    this.getList();
  }
	
  // 表格数据
  loading1 = false;
  getList() {
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      pathologySpecimenName: {
        deptId: this.dept,
				specimenName: this.specimenName,
        containPosition: this.containPosition
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("data", "pathologySpecimenName", data)
      .subscribe((data) => {
        this.loading1 = false;
        this.listOfData = data.list;
        this.listLength = data.totalNum;
      });
  }
	
	// 获取科室
	getDeparts(dept) {
	  let data:any = {
	    department: {
				dept,
	      hosIds: this.hosId,
	    },
	    idx: 0,
	    sum: 20,
	  };
	  this.mainService
	    .getFetchDataList("data", "department", data)
	    .subscribe((data) => {
				this.isDeptLoading = false
				this.hospitals1 = data.list
	    });
	}
	
	// 搜索科室
	isDeptLoading = false;
	changeInp(e,type) {
	  this.searchParentDeptSubject.next([e,type]);
	}
	
	// 获取标本-位置来源
	getSourceData(){
		this.mainService.getDictionary("list", "pathology_position").subscribe((res) => {
			this.placeList = res
		});
	}
	
	// 获取标本-系统
	getSysData(){
		let postData: any = {
		  idx: 0,
		  sum: 9999,
		  dictionaryTree: {
		    level: 1,
		    key: 'pathology_specimen',
		    deleted: 0,
		  },
		};
		this.mainService
		  .getFetchDataList("simple/data", "dictionaryTree", postData)
		  .subscribe((data) => {
		    this.systemList = data.list;
		  });
	
	}
	
	// 获取标本-器官
	getApparatusData(id,item,type){
		let postData: any = {
		  idx: 0,
		  sum: 9999,
		  dictionaryTree: {
		    level: 2,
				parent:id,
		    key: 'pathology_specimen',
		    deleted: 0,
		  },
		};
		this.mainService
		  .getFetchDataList("simple/data", "dictionaryTree", postData)
		  .subscribe((data) => {
				this.apparatusList = data.list;
				if(type=='edit'){
					this.validateForm.controls.organId.setValue(item.organ.id)
					setTimeout(_=>{
						this.loading1 = false
						this.modal = true
					},50)
				}
		  });
	}
	
	// 获取标本-标本名称
	getSpNameData(id,item,type){
		let postData: any = {
		  idx: 0,
		  sum: 9999,
		  dictionaryTree: {
		    level: 3,
				parent:id,
		    key: 'pathology_specimen',
		    deleted: 0,
		  },
		};
		this.addressLoading = true;
		postData.dictionaryTree.key = 'pathology_specimen'
		postData.dictionaryTree.parent = id
		postData.dictionaryTree.level = 3
		this.mainService.getFetchDataList("simple/data", "dictionaryTree", postData)
		.subscribe((data) => {
			this.addressLoading = false;
			this.specimenNameList = data.list;
			if(type=='edit'){
				this.validateForm.controls.specimenName.setValue(item.specimenName);
			}
		});
	}
	
	// 标本名称输入查询
	specimenNameChange(keyword){
		if(keyword!=''){
			const data = this.specimenNameList; 
			const results = data.filter(item => item.name.indexOf(keyword) !== -1)
			if(results){
				this.specimenNameList = results
			}else{
				this.getSpNameData(this.validateForm.value.organId,{},'select')
			}
		}else{
			this.getSpNameData(this.validateForm.value.organId,{},'select')
		}
	}
	
	// 点击其他位置
	clickExtra(e){
	  if(document.documentElement.contains(document.querySelector('.addressList')) && e.target !== document.querySelector('.addressFocus')){
	    this.isShowAddressList = false;
	  }
	}
	
	// 标本名称获取焦点
	isShowAddressList:boolean = false;
	focusAddress(){
	  this.isShowAddressList = true;
	  this.getSpNameData(this.validateForm.value.organId,{},'select')
	}
	
	// 选择标本名称
	selectAddress(name){
	  this.validateForm.controls.specimenName.setValue(name)
	  this.isShowAddressList = false;
	}
	
	// 编辑标本
	specimenDetailId:any = null;
	specimenEdit(e,item,index){
		this.specimenDetailId = item.id
		if(item.system && item.organ){
			this.getApparatusData(item.system.id,item,'edit')
			this.getSpNameData(item.organ.id,item,'edit')
		}else{
			this.getSpNameData(item.specimenId,item,'edit')
		}
	}
	
	// 选择系统
	systemChange(){
		if(this.validateForm.value.organId){
			this.validateForm.controls.organId.reset()
			this.validateForm.controls.organId.markAsPristine();
			this.validateForm.controls.organId.updateValueAndValidity()
		}
		this.getApparatusData(this.validateForm.value.systemId,{},'select')
	}
	
	// 选择器官
	apparatusChange(){
		if(this.validateForm.value.specimenName){
			this.validateForm.controls.specimenName.reset()
			this.validateForm.controls.specimenName.markAsPristine();
			this.validateForm.controls.specimenName.updateValueAndValidity()
		}
		this.getSpNameData(this.validateForm.value.organId,{},'select')
	}
	
  // 新增弹框
  showModal() {
    this.add = true;
		this.modal = true
    this.initForm();
  }
  hideModal() {
    this.modal = false;
    this.initForm();
  }
	
	// 新增/编辑选择是否包含位置
	radioChange(e:any){
		if(this.validateForm.value.containPosition==1){
			this.validateForm.addControl(
				'positionId',
				new FormControl('1', Validators.required)
			);
		}else{
			this.validateForm.removeControl('positionId')
		}
	}
	
  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
			deptId: [null, [Validators.required]],
			containPosition:['1', [Validators.required]],
      specimenName: [null, [Validators.required]],
      organId: [null, [Validators.required]],
      systemId: [null, [Validators.required]],
      positionId: [null, [Validators.required]],
    });
  }
	
  // 表单提交
  submitForm(): void {
    var that = this;
		for (const i in that.validateForm.controls) {
		  that.validateForm.controls[i].markAsDirty();
		  that.validateForm.controls[i].updateValueAndValidity();
		}
		if (that.validateForm.invalid) return;
    let data = {
			pathologySpecimenName:{
				...this.validateForm.value,
				id:0,
			}
    };
    if (!that.add) {
      data.pathologySpecimenName.id = that.coopId;
    }else{
			delete data.pathologySpecimenName.id
		}
		that.btnLoading = true;
    that.mainService
      .dataPost("addData", "pathologySpecimenName", data)
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideModal();
        that.initForm();
        if (data.status == 200) {
          that.showPromptModal(that.add ? "新增" : "编辑", true, "");
        } else {
          that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
        }
      });
  }

  // 编辑
  edit(data) {
		this.add = false
		this.loading1 = true
		this.coopId = data.id;
		if(data.containPosition==1){
			this.validateForm.addControl(
				'positionId',
				new FormControl('1', Validators.required)
			);
			this.validateForm.controls.positionId.setValue(data.position.id);
		}else{
			this.validateForm.removeControl('positionId')
		}
		this.validateForm.controls.deptId.setValue(data.dept.id);
    this.validateForm.controls.containPosition.setValue(data.containPosition + '');
    this.validateForm.controls.specimenName.setValue(data.specimenName);
		this.validateForm.controls.systemId.setValue(data.system.id)
		if(data.system && data.organ){
			this.getApparatusData(data.system.id,data,'edit')
			this.getSpNameData(data.organ.id,data,'edit')
		}
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    let that = this;
    that.coopId = data.id;
    that.delModal = true;
  }
	
	// 取消删除弹框
	cancelDel(){
		this.hideDelModal();
	}
	
  // 确认删除
  confirmDel() {
    let that = this;
    that.btnLoading = true;
    that.mainService
      .apiPublicData('rmvData', 'pathologySpecimenName', [this.coopId])
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideDelModal();
        if (data["status"] == 200) {
          that.showPromptModal("删除", true, "");
        } else {
          that.showPromptModal("删除", false, data["msg"]);
        }
      });
  }
	
	// 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
	showPromptModal(con, success, promptInfo?) {
	  this.promptModalShow = false;
	  this.promptContent = con;
	  this.ifSuccess = success;
	  this.promptInfo = promptInfo;
	  setTimeout(() => {
	    this.promptModalShow = true;
	  }, 100);
	  this.getList();
	}
	
  // 关闭删除模态框
  hideDelModal() {
    this.delModal = false;
  }
}

