import { Component, OnInit } from "@angular/core";
import { MainService } from 'src/app/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';
import { format, startOfMinute } from 'date-fns';

@Component({
  selector: "app-acc-examine-set",
  templateUrl: "./acc-examine-set.component.html",
  styleUrls: ["./acc-examine-set.component.less"],
})
export class AccExamineSetComponent implements OnInit {
  loading:boolean = false; //页面加载的loading
  btnLoading:boolean = false; //提交按钮的loading
  tabModalName:string = 'characteristics'; //当前选中的tab
  surgeryField = null; //手术关联业务
  hosId = this.tool.getCurrentHospital().id; //当前院区
  // 接手术关联任务类型
  tasktypeId:any;
  taskTypes1:any[] = [];
  taskTypes2:any[] = [];
  // 苏醒室科室
  recoveryDeptId:any;
  recoveryDepts:any[] = [];
  // 自动建单
  autoCreateOrders:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否开通送回病房
  autoSendWard:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否开通送回苏醒室
  autoSendAwakeningRoom:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否开通关联手术清洁建单
  autoRemandClean:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否开启手术即将开始通知
  surgeryBegin:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 建单时间
  autoTime:Date | null = null;
  tasktype1Id:any;
  tasktype2Id:any;
  cleanTypeId:any;
	associationTypeIds:any;
	questionnaireManagementData:any; //调查问卷数据
	questionnaireIds:Number; //问卷参数
	intervalTime:string = ''; //间隔时间参数
	taskTypeIds:any = []; //任务类型参数
	editId:'';
	targetData:any = [];
	stateData:any = [];
	// 间隔时间数据
	timeData:any[] = [
	  {label:'10',value: 10},
		{label:'15',value: 15},
		{label:'30',value: 30},
		{label:'60',value: 60}
	];
  // 配置
  configs: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], v[2], v[3]);
    });
    // this.getTaskTypes('', true, 1);
    // this.getTaskTypes('', false, 2);
		this.getRelevanceType()
  }

  // 切换tab
  tabModal(tabModalName:string){
    this.tabModalName = tabModalName;
  }
  // 修改是否自动建单
  changeAutoCreateOrders(e){
    console.log(e);
    if(!e[0].checked){
      // todo
      this.autoTime = null;
    }
  }

  // 修改是否开通送回病房
  changeAutoSendWard(e){
    console.log(e);
    if(!e[0].checked){
      // todo
      this.tasktype1Id = null;
    }
  }

  // 修改是否开通送回苏醒室
  changeAutoSendAwakeningRoom(e){
    console.log(e);
    if(!e[0].checked){
      // todo
      this.tasktype2Id = null;
    }
  }

  // 修改是否开通关联手术清洁建单
  changeAutoRemandClean(e){
    console.log(e);
    if(!e[0].checked){
      // todo
      this.cleanTypeId = null;
    }
  }

  // 保存
  submitForm() {
    if(!this.questionnaireIds){
      this.msg.create("warning", "请选择调查问卷！");
      return;
    }
    if(this.taskTypeIds.length==0){
      this.msg.create("warning", "请选择任务类型！");
      return;
    }
    if(this.intervalTime==''){
      this.msg.create("warning", "请选择间隔时间！");
      return;
    }
		let taskArr = JSON.parse(JSON.stringify(this.taskTypeIds))
    let editData = {
			// questionnaireConfig:{
				id:'',
				hosId: this.hosId,
				questionnaireIds:this.questionnaireIds,//问卷参数
				intervalTime:this.intervalTime, //间隔时间参数
				taskTypeIds:taskArr.join(',') //任务类型参数
			// }
    };
		if(this.editId){
			editData.id = this.editId
		}else{
			delete editData.id 
		}
    this.btnLoading = true;
    this.mainService
      .simplePost("addData", "questionnaireConfig", editData)
      .subscribe((result) => {
        this.btnLoading = false;
        if (result.status == 200) {
          this.getConfig();
        }
      });
  }
	
	// 调查问卷搜索
	changequestionnaire(e) {
		this.searchTimer(this.getOneQuestionnaireManagement, e, false)
	}
	
  // 用户输入搜索任务类型
  isLoading: boolean = false;
  changeTasktype(e) {
    this.searchTimer(this.getTaskTypes, e, false);
  }

  changeRecoveryDepts(e) {
    this.searchTimer(this.getRecoveryDepts, e, false);
  }

  // 边输入边搜索节流阀
  searchTimer(fun, e, isFirst, type?) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e, isFirst, type]);
  }
	
	// 获取关联任务类型
	getRelevanceType(){
		this.associationTypeIds=[]
		this.mainService.getDictionary("list", "association_types").subscribe((data) => {
			for( let t of data){
				if(t.value=='patientTransport' || 
				t.value=='other' || t.value=='inspect'){
					this.associationTypeIds.push(t)
				}
			}
			this.getTaskTypes('', true, 1)
			this.getState()
		});
	}
	
	// 获取问卷状态
	getState(){
		this.mainService.getDictionary("list", "survey_state").subscribe((data) => {
			this.stateData = data
			this.getQuestionnaireTarget()
		});
	}
	
	// 获取问卷调查目标
	getQuestionnaireTarget(){
		this.mainService.getDictionary("list", "survey_target").subscribe((data) => {
			this.targetData = data
			this.getOneQuestionnaireManagement()
		});
	}
	
	// 获取问卷数据
	getOneQuestionnaireManagement(e:string = '', isFirst:boolean = false,){
		let targetId = this.targetData.find(i=>i.value==4)
		let stateId = this.stateData.find(i=>i.value==2)
		let query = {
			idx: 0,
			questionnaireManagement: {
				title:e,
				hosId: this.hosId,
				surveyTarget:{ //问卷调查目标
					id:targetId.id
				},
				state:{ //问卷状态
					id:stateId.id
				}
			},
			hosId: this.hosId,
			sum: 10
		}
		isFirst && (this.loading = true);
		this.isLoading = true;
	  this.mainService.getFetchDataList('api', "questionnaireManagement", query).subscribe(res=>{
	    if(res.status == 200){
				this.isLoading = false;
	      this.questionnaireManagementData = res.list;
	    }
	  })
	}
	
  //获取接手术关联任务类型
  // 1 患者其他服务
  // 2 其他临床服务
  getTaskTypes(e:string = '', isFirst:boolean = false, type:number = 1) {
		let ids = []
		for(let i of this.associationTypeIds){
			ids.push(i.id)
		}
    isFirst && (this.loading = true);
    let postData:any = {
      idx: 0,
      sum: 9999,
      taskType: {
        taskName: e,
        simpleQuery: true,
				associationTypeIds:ids.join(','),
        hosId: {
          id: this.hosId
        }
      }
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "taskType", postData)
      .subscribe((result) => {
        this.isLoading = false;
        if (result.status == 200) {
          this.taskTypes1 = result.list || [];
          isFirst && this.getConfig();
        }
      });
  }

  //获取所有科室类型
  allDeptTypes:any[] = [];
  getDeptType(isFirst:boolean = false) {
    isFirst && (this.loading = true);
    this.mainService
      .getDictionary("list", "dept_type")
      .subscribe((result) => {
        this.allDeptTypes = result;
        isFirst && this.getRecoveryDepts('', true);
      });
  }

  //获取所有科室
  getRecoveryDepts(e:string = '', isFirst:boolean = false) {
    isFirst && (this.loading = true);
    let recovery = this.allDeptTypes.find(v => v.value === 'recovery');
    let postData = {
      idx: 0,
      sum: 10,
      department: {
        dept: e,
        hospital: {
          id: this.hosId
        },
        type: recovery || undefined
      }
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((result) => {
        this.isLoading = false;
        if (result.status == 200) {
          this.recoveryDepts = result.list || [];
          isFirst && this.getConfig();
        }
      });
  }
  // 获取配置
  getConfig() {
    this.loading = true;
    let postData = {
      idx: 0,
      sum: 10,
      questionnaireConfig: {
        hosId: this.hosId,
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "questionnaireConfig", postData)
      .subscribe((result) => {
        this.loading = false;
        if (result.status == 200) {
    			let data = result.list[0] || {};
					this.editId = data.id
					let questionData = data.questionnaireDTOS.map(i=>{
						return i.id
					})
    			this.questionnaireIds = Number(questionData.join(',')) //调查问卷
    			this.intervalTime = data.intervalTime //间隔时间
    			this.taskTypeIds = data.taskTypeDTOS.map(i=>{ //任务类型
						return i.id
					}) 
        }
      });
  }
}


