import { Component, OnInit } from "@angular/core";
import { MainService } from "../../../services/main.service";
import { ToolService } from 'src/app/services/tool.service';
import { NzMessageService } from 'ng-zorro-antd';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: "app-configuration-specimen",
  templateUrl: "./configuration-specimen.component.html",
  styleUrls: ["./configuration-specimen.component.less"],
})
export class ConfigurationSpecimenComponent implements OnInit {
  loading:boolean = false; //页面加载的loading
  btnLoading:boolean = false; //提交按钮的loading
  tabModalName:string = 'characteristics'; //当前选中的tab
  hosId = this.tool.getCurrentHospital().id; //当前院区
	
	// tab类型
	dictionaryKeyList:any[] = [
		{
			name:'检查标本',key:'examine'
		},
		{
			name:'病理标本',key:'pathology'
		}
	];
	
	// 是否支持根据手术新建申请单
	autoCreate:any[] = [
	  {label:'是否开启',value: 0}
	];
	
	// 是否是否支持门诊新增申请单
	outpatientCreatePathologyForm:any[] = [
	  {label:'是否开启',value: 0}
	];
	outpatientPathologyLabelSize:any; //门诊病理标签样式
	surgeryPathologyLabelSize:any //手术病理标签样式
	// 门诊支持离体并固定
	outpatientInVitroFixation:any[] = [
	  {label:'是否开启',value: 0}
	];
	
  // 扫描时指定科室不提醒勾选项
  deptNotAlert:any[] = [
    {label:'是否开启',value: 0}
  ];

  // 收取时需扫描二维码
  arriveScanCode:any[] = [
    {label:'是否开启',value: 0}
  ];

  // 必须扫描动态二维码
  arriveScanDynamicCode:any[] = [
    {label:'是否开启',value: 0}
  ];
	
	// 必须扫描动态二维码
	enterDynamicDigitalKey:any[] = [
	  {label:'是否开启',value: 0}
	];
	
  // 退回标本是否填写交接人
  returnSpecimenWhetherHandover:any[] = [
    {label:'是否开启',value: 0}
  ];

  // 显示接单签到按钮
  bigScanShowSignBtn:any[] = [
    {label:'是否开启',value: 0}
  ];

  // 支持待到达非本人
  bigScanArriveNotOwner:any[] = [
    {label:'是否开启',value: 0}
  ];

  // 显示建单并签到按钮
  bigScanShowCreateBtn:any[] = [
    {label:'是否开启',value: 0}
  ];

  // 默认扫描标本进入标本扫描页
  defaultScanSpe:any[] = [
    {label:'是否开启',value: 0}
  ];
	
	//申请单条码设置
	pathologyBarCode:any;
	
  // 配置
  configs:any = {};
  // 任务类型
  tasktype:any = {};
  searchTimerSubject = new Subject();
  constructor(private mainService: MainService,private tool: ToolService,private msg: NzMessageService) {}

  ngOnInit():void {
    // todo
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1]);
    });
    this.getDeptList();
    this.getTaskType();
  }
	
	// 点击数据字典key
	activeDictionaryKey:any = 'examine';
	clickDictionaryKey(item){
	  this.activeDictionaryKey = item.key;
		if(item.key=='examine'){
			this.getDeptList();
			this.getTaskType();
		}else{
			this.getLabelDic()
			this.getTaskTypesId()
		}
	}
	
  // 扫描时指定科室不提醒勾选项
  changeDeptNotAlert(e){
    console.log(e);
    if(!e[0].checked){
      this.deptNotAlertIds = [];
    }
  }
  // 收取时需扫描二维码
  changeArriveScanCode(e){
    console.log(e);
    if(!e[0].checked){
      this.arriveScanDynamicCode[0].checked = false;
			this.enterDynamicDigitalKey[0].checked = false;
    }
  }
  // 用户输入搜索
  isLoading: boolean = false;
  deptNotAlertIds:any[] = [];
  deptList:any[] = [];
  changeDept(e) {
    this.searchTimer(this.getDeptList, e);
  }
  // 边输入边搜索节流阀
  searchTimer(fun, e) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e]);
  }
  openDeptList(flag){
    if(flag){
      this.getDeptList();
    }
  }
  //获取科室列表
  getDeptList(e:string = '') {
    let postData:any = {
      idx: 0,
      sum: 20,
      department: {
        searchType: 1,// 简单查询
        hospital: { id: this.hosId },
        dept: e,
      }
    };
    this.isLoading = true;
    this.mainService.getFetchDataList("simple/data", "department", postData)
      .subscribe((result) => {
        this.isLoading = false;
        if (result.status == 200) {
          this.deptList = result.list || [];
        }
      });
  }

  // 切换tab
  tabModal(tabModalName:string){
    this.tabModalName = tabModalName;
  }
	
	//病理标本保存
	submitPathologyForm(){
		let postData:any = {
		  id: this.configs.id,
		  taskType: this.taskTypeData.id,
		  hosId: this.hosId,
		  autoCreate: this.autoCreate[0].checked ? 1 : 0,
			outpatientCreatePathologyForm: this.outpatientCreatePathologyForm[0].checked ? 1 : 0,
			outpatientInVitroFixation: this.outpatientInVitroFixation[0].checked ? 1 : 0,
			pathologyBarCode : this.pathologyBarCode,
			outpatientPathologyLabelSize:{
				id:this.outpatientPathologyLabelSize
			},
			surgeryPathologyLabelSize:{
				id:this.surgeryPathologyLabelSize
			}, 
		};
		this.btnLoading = true;
		this.mainService
		  .simplePost("addData", "taskTypeConfig", postData)
		  .subscribe((result) => {
		    this.btnLoading = false;
		    if (result.status == 200) {
		      this.getConfig();
		    }
		  });
	}
	
  // 检查标本保存
  submitForm() {
    if(!this.tasktype.id){
      this.msg.create("warning", "请先配置患者陪检任务类型！");
      return;
    }
    if(this.deptNotAlert[0].checked && !this.deptNotAlertIds.length){
      this.msg.create("warning", "请选择科室！");
      return;
    }
    let postData:any = {
      id: this.configs.id,
      taskType: this.tasktype.id,
      hosId: this.hosId,
      deptNotAlert: this.deptNotAlert[0].checked ? 1 : 0,
      arriveScanCode: this.arriveScanCode[0].checked ? 1 : 0,
      arriveScanDynamicCode: this.arriveScanDynamicCode[0].checked ? 1 : 0,
			enterDynamicDigitalKey: this.enterDynamicDigitalKey[0].checked ? 1 : 0,
      returnSpecimenWhetherHandover: this.returnSpecimenWhetherHandover[0].checked ? 1 : 0,
      bigScanShowSignBtn: this.bigScanShowSignBtn[0].checked ? 1 : 0,
      bigScanArriveNotOwner: this.bigScanArriveNotOwner[0].checked ? 1 : 0,
      bigScanShowCreateBtn: this.bigScanShowCreateBtn[0].checked ? 1 : 0,
      defaultScanSpe: this.defaultScanSpe[0].checked ? 1 : 0,
      deptNotAlertIds: this.deptNotAlertIds.length ? this.deptNotAlertIds.toString() : undefined,
    };
    this.btnLoading = true;
    this.mainService
      .simplePost("addData", "taskTypeConfig", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        if (result.status == 200) {
          this.getConfig();
        }
      });
  }
	
	// 获取标本字典
	labelData:any = [];
	getLabelDic(){
		this.mainService.getDictionary("list", "pathology_label_size").subscribe((data) => {
			this.labelData = data
		});
	}
	
	// 获取任务类型（病理标本）
	taskTypeData:any;
	getTaskTypesId() {
		this.mainService.getDictionary("list", "ordinary_field").subscribe((data) => {
			this.taskTypeData = data.find(i=>i.value=='pathology')
			this.getConfig();
		});
	}
	
  //获取任务类型
  getTaskType() {
    this.loading = true;
    let postData = {
      idx: 0,
      sum: 10,
      taskType: {
        simpleQuery: true,
        hosId: {
          id: this.hosId
        },
        associationType: {
          key:"association_types",
          value: 'specimen'
        }
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskType", postData)
      .subscribe((result) => {
        this.loading = false;
        if (result.status == 200) {
          this.tasktype = result.list[0] || {};
          this.getConfig();
        }
      });
  }

  // 获取配置
  getConfig() {
    this.loading = true;
		let postData = null;
		if(this.activeDictionaryKey=='examine'){
			postData = {
			  idx: 0,
			  sum: 10,
			  taskTypeConfig: {
			    taskTypeDTO: {
			      hosId: {
			        id: this.hosId
			      },
			      associationType: this.tasktype.associationType
			    }
			  }
			};
		}else{
			postData = {
			  idx: 0,
			  sum: 10,
			  taskTypeConfig: {
					hosId:this.hosId,
					taskType:this.taskTypeData.id
			  }
			};
		}
    
    this.mainService
      .getFetchDataList("simple/data", "taskTypeConfig", postData)
      .subscribe((result) => {
        this.loading = false;
        if (result.status == 200) {
          this.configs = result.list[0] || {};
					if(this.activeDictionaryKey=='examine'){
						// 检查标本
						this.deptNotAlert[0].checked = this.configs.deptNotAlert == 1;
						this.arriveScanCode[0].checked = this.configs.arriveScanCode == 1;
						this.arriveScanDynamicCode[0].checked = this.configs.arriveScanDynamicCode == 1;
						this.enterDynamicDigitalKey[0].checked = this.configs.enterDynamicDigitalKey == 1;
						this.returnSpecimenWhetherHandover[0].checked = this.configs.returnSpecimenWhetherHandover == 1;
						this.bigScanShowSignBtn[0].checked = this.configs.bigScanShowSignBtn == 1;
						this.bigScanArriveNotOwner[0].checked = this.configs.bigScanArriveNotOwner == 1;
						this.bigScanShowCreateBtn[0].checked = this.configs.bigScanShowCreateBtn == 1;
						this.defaultScanSpe[0].checked = this.configs.defaultScanSpe == 1;
						this.deptNotAlertIds = this.configs.deptNotAlertIds ? this.configs.deptNotAlertIds.split(',').map(v => +v) : [];
						this.deptList = this.configs.deptNotAlertList || [];
					}else{
						// 病理标本
						this.autoCreate[0].checked = this.configs.autoCreate == 1;
						this.outpatientCreatePathologyForm[0].checked = this.configs.outpatientCreatePathologyForm == 1;
						this.outpatientInVitroFixation[0].checked = this.configs.outpatientInVitroFixation == 1;
						this.pathologyBarCode = this.configs.pathologyBarCode;
						this.outpatientPathologyLabelSize = this.configs.outpatientPathologyLabelSize.id; //门诊病理标签样式
						this.surgeryPathologyLabelSize = this.configs.surgeryPathologyLabelSize.id //手术病理标签样式
					}
        }
      });
  }
}
