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-operation-config",
  templateUrl: "./operation-config.component.html",
  styleUrls: ["./operation-config.component.less"],
})
export class OperationConfigComponent 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}
  ];
	// 是否开启病理申请单
	isPathologyForm:any[] = [
	  {label:'是否开启',value: 0}
	];
	// 是否开启速冻标本自动建单
	isFrozenSpecimen:any[] = [
	  {label:'是否开启',value: 0}
	];
	// 是否根据首台标识
	firstOperation:any[] = [
	  {label:'是否开启',value: 0}
	];
	// 限定时间
	firstOperationLimitTime: Date | null = null;
  // 建单时间
  autoTime:Date | null = null;
  tasktype1Id:any;
  tasktype2Id:any;
  cleanTypeId:any;
  // 配置
  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);
  }

  // 切换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.tasktypeId){
      this.msg.create("warning", "请选择接手术关联任务类型！");
      return;
    }
    if(!this.recoveryDeptId){
      this.msg.create("warning", "请选择苏醒室科室！");
      return;
    }
    if(this.autoCreateOrders[0].checked && !this.autoTime){
      this.msg.create("warning", "请选择建单时间！");
      return;
    }
    if(this.autoSendWard[0].checked && !this.tasktype1Id){
      this.msg.create("warning", "请选择送回病房任务类型！");
      return;
    }
    if(this.autoSendAwakeningRoom[0].checked && !this.tasktype2Id){
      this.msg.create("warning", "请选择送回苏醒室任务类型！");
      return;
    }
    if(this.autoRemandClean[0].checked && !this.cleanTypeId){
      this.msg.create("warning", "请选择手术清洁任务类型！");
      return;
    }
    let editData:any = {
      hosId: this.hosId,
      taskType: this.tasktypeId || undefined,
      recoveryDeptId: this.recoveryDeptId || undefined,
      ordinaryField: this.surgeryField,
      autoCreate: this.autoCreateOrders[0].checked ? 1 : 0,
      createTime: this.autoTime ? format(startOfMinute(this.autoTime), "yyyy-MM-dd HH:mm:ss") : undefined,
      remandClinical: this.autoSendWard[0].checked ? 1 : 0,
      clinicalTypeId: this.tasktype1Id || undefined,
      remandRecovery: this.autoSendAwakeningRoom[0].checked ? 1 : 0,
      recoveryTypeId: this.tasktype2Id || undefined,
      remandClean: this.autoRemandClean[0].checked ? 1 : 0,
      surgeryBegin: this.surgeryBegin[0].checked ? 1 : 0,
			isPathologyForm: this.isPathologyForm[0].checked ? 1 : 0,
			isFrozenSpecimen: this.isFrozenSpecimen[0].checked ? 1 : 0,
      cleanTypeId: this.cleanTypeId || undefined,
			firstOperation: this.firstOperation[0].checked ? 1 : 0,
			firstOperationLimitTime: this.firstOperationLimitTime ? format(startOfMinute(this.firstOperationLimitTime), 'yyyy-MM-dd HH:mm:ss') : undefined
    };
    let postData = Object.assign({}, this.configs, editData);
    console.log(postData);
    this.btnLoading = true;
    this.mainService
      .simplePost("addData", "taskTypeConfig", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        if (result.status == 200) {
          this.getConfig();
        }
      });
  }

  // 用户输入搜索任务类型
  isLoading: boolean = false;
  changeTasktype(e, type) {
    this.searchTimer(this.getTaskTypes, e, false, type);
  }

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

  // 边输入边搜索节流阀
  searchTimer(fun, e, isFirst, type?) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e, isFirst, type]);
  }

  //获取接手术关联任务类型
  // 1 患者其他服务
  // 2 其他临床服务
  getTaskTypes(e:string = '', isFirst:boolean = false, type:number = 1) {
    isFirst && (this.loading = true);
    let postData:any = {
      idx: 0,
      sum: 10,
      taskType: {
        taskName: e,
        simpleQuery: true,
        hosId: {
          id: this.hosId
        }
      }
    };
    if(type === 1){
      postData.taskType.associationType = {
        key: 'association_types',
        value: 'patientTransport'
      }
    }else if(type === 2){
      postData.taskType.associationType = {
        key: 'association_types',
        value: 'other'
      }
    }
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "taskType", postData)
      .subscribe((result) => {
        this.isLoading = false;
        if (result.status == 200) {
          if(type === 1){
            this.taskTypes1 = result.list || [];
          }else if(type === 2){
            this.taskTypes2 = result.list || [];
          }
          isFirst && this.getDeptType(true);
        }
      });
  }

  //获取所有科室类型
  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;
    this.mainService
      .getDictionary("list", "ordinary_field")
      .subscribe((data) => {
        this.surgeryField = data.find(v => v.value == 'surgery');
        if(this.surgeryField){
          let postData = {
            idx: 0,
            sum: 10,
            taskTypeConfig: {
              hosId: this.hosId,
              ordinaryField: this.surgeryField
            }
          };
          this.mainService
            .getFetchDataList("simple/data", "taskTypeConfig", postData)
            .subscribe((result) => {
              this.loading = false;
              if (result.status == 200) {
                this.configs = result.list[0] || {};

                // 接手术关联任务类型
                this.tasktypeId = this.configs.taskTypeDTO ? this.configs.taskTypeDTO.id : null;
                if(this.tasktypeId && this.configs.taskTypeDTO){
                  let isInArr = this.taskTypes1.some(v => v.id == this.tasktypeId);
                  if(!isInArr){
                    this.taskTypes1.unshift(this.configs.taskTypeDTO);
                  }
                }

                // 苏醒室科室
                this.recoveryDeptId = this.configs.recoveryDeptId || null;
                if(this.recoveryDeptId && this.configs.recoveryDeptDTO){
                  let isInArr = this.recoveryDepts.some(v => v.id == this.recoveryDeptId);
                  if(!isInArr){
                    this.recoveryDepts.unshift(this.configs.recoveryDeptDTO);
                  }
                }

                this.autoCreateOrders[0].checked = this.configs.autoCreate == 1;
                this.autoTime = this.configs.createTime ? new Date(this.configs.createTime) : null;
                this.autoSendWard[0].checked = this.configs.remandClinical == 1;

                // 送回病房科室
                this.tasktype1Id = this.configs.clinicalTypeId || null;
                if(this.tasktype1Id && this.configs.clinicalTypeDTO){
                  let isInArr = this.taskTypes1.some(v => v.id == this.tasktype1Id);
                  if(!isInArr){
                    this.taskTypes1.unshift(this.configs.clinicalTypeDTO);
                  }
                }
                this.autoSendAwakeningRoom[0].checked = this.configs.remandRecovery == 1;

                // 送回苏醒室科室
                this.tasktype2Id = this.configs.recoveryTypeId || null;
                if(this.tasktype2Id && this.configs.recoveryType){
                  let isInArr = this.taskTypes1.some(v => v.id == this.tasktype2Id);
                  if(!isInArr){
                    this.taskTypes1.unshift(this.configs.recoveryType);
                  }
                }

                this.autoRemandClean[0].checked = this.configs.remandClean == 1;

                // 关联手术清洁
                this.cleanTypeId = this.configs.cleanTypeId || null;
                if(this.cleanTypeId && this.configs.cleanType){
                  let isInArr = this.taskTypes2.some(v => v.id == this.cleanTypeId);
                  if(!isInArr){
                    this.taskTypes2.unshift(this.configs.cleanType);
                  }
                }

                this.surgeryBegin[0].checked = this.configs.surgeryBegin == 1;
								this.isPathologyForm[0].checked = this.configs.isPathologyForm == 1;
								this.isFrozenSpecimen[0].checked = this.configs.isFrozenSpecimen == 1;
								this.firstOperation[0].checked = this.configs.firstOperation == 1;
								this.firstOperationLimitTime = this.configs.firstOperationLimitTime ? new Date(this.configs.firstOperationLimitTime) : null;
							}
            });
        }else{
          this.loading = false;
        }
      });
  }
}


