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 } from 'date-fns';

@Component({
  selector: "app-inspect-and-patient-transport-config",
  templateUrl: "./inspect-and-patient-transport-config.component.html",
  styleUrls: ["./inspect-and-patient-transport-config.component.less"],
})
export class InspectAndPatientTransportConfigComponent implements OnInit {
  loading:boolean = false; //页面加载的loading
  btnLoading:boolean = false; //提交按钮的loading
  tabModalName:string = 'characteristics'; //当前选中的tab
  hosId = this.tool.getCurrentHospital().id; //当前院区
  // 检查预约时间是否精准填写-时间模式
  timeModes:any[] = [
    {id: 1, name: '每分钟'},
    {id: 10, name: '每10分钟'},
    {id: 30, name: '每30分钟'},
  ];
  // 是否开通送回病房
  accurateTimeFilling:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否自动清空患者标记
  batchInspectAutoClear:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否显示排队信息
  queuingInformation:any[] = [
    {label:'是否开启',value: 0}
  ];

  // 是否起点签到成功展示患者其他服务
  startShowAnotherService:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否终点签到成功展示患者其他服务
  endShowAnotherService:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否允许交接工单
  handoverOrder:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否开启结束服务
  finishService:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否允许追加服务
  addService:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 患者是否第三方接入
  isThirdOutpatient:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 急诊患者是否第三方接入
  isThirdEmergencyPatient:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 批量建立送回
  batchCreationAndReturn:any[] = [
    {label:'是否开启',value: 0}
  ];

  // 配置执行中扫科室批量签到
  batchSignExecutionDept:any[] = [
    {label:'是否开启',value: 0}
  ];

  // 批量建立送回
  batchSignEndDept:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 执行中-支持父子集科室同签
  batchSignExecutionParent:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 终点-支持父子集科室同签
  batchSignEndParent:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 隐藏陪检小扫描
  hideInspectScan:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否开启携带设备
  enableGoods:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否开启陪检方式
  enableTripType:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否开启护士端追加检查
  nurseAppendInspect:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否支持签到并转派
  signReassign:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 是否修改危重等级
  updatePatientIllness:any[] = [
    {label:'是否开启',value: 0}
  ];
	// 是否限制陪检人员评估后建单
	inspectUserAuditCreate:any[] = [
	  {label:'是否开启',value: 0}
	];
  // 是否开通非预约检查顺延
  inspectDelayOneDay:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 检查预约不进行工单合并
  // yyInspectMergeOrder:any[] = [
  //   {label:'是否开启',value: 0}
  // ];

  // 批量陪检配置方式
  batchInspectTypes:any[] = [
    { label: '预约陪检', value: 1, },
    { label: '陪检信息配置', value: 2, },
  ];
	
	// 默认预约间隔时长
	yytimeGapMinute:any;
	
  changeBatchSignExecutionDept(e){
    if(!e[0].checked){
      this.batchSignExecutionParent = [
        {label:'是否开启',value: 0}
      ];
    }
  }

  changeBatchSignEndDept(e){
    if(!e[0].checked){
      this.batchSignEndParent = [
        {label:'是否开启',value: 0}
      ];
    }
  }

  timeMod:any;
  batchInspectAutoClearTime:any;
  // 交接方式
  // handoverMode:any;
  // handoverModes:any[] = [];
  // 核对方式
  // checkModes:any[] = [];
  // 签到方式
  checkInModes:any[] = [];
  // 多人模式支持
  multiplayerMode:any[] = [
    {label:'是否开启',value: 0}
  ];
  // 积分计算方式
  integralCalculationMethod:any = null;
  // 自动关单
  // automaticCustomsOrders:any[] = [];
  // 自动建单
  // autoCreateOrders:any[] = [
  //   {label:'是否开启',value: 0}
  // ];
  // 是否根据开通科室建单
  // autoDepts:any[] = [
  //   {label:'是否根据开通科室建单',value: 0}
  // ];
  // 配置
  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.getTaskTypes();
    // todo
    // this.getHandoverModes();
    // this.getCheckModes();
    this.getCheckInModes();
  }

  // 修改是否多人模式支持
  changeMultiplayerMode(e){
    console.log(e);
    if(!e[0].checked){
      this.integralCalculationMethod = null;
    }
  }
  // 修改检查预约时间是否精准填写
  changeAccurateTimeFilling(e){
    console.log(e);
    if(!e[0].checked){
      // todo
      this.timeMod = null;
    }
  }
  // 修改是否自动清空患者标记
  changeBatchInspectAutoClear(e){
    console.log(e);
    if(!e[0].checked){
      // todo
      this.batchInspectAutoClearTime = undefined;
    }
  }
  // 修改是否允许追加服务
  changeAddService(e){
    console.log(e);
    if(!e[0].checked){
      this.addServiceTaskIds = [];
    }
  }
  // 用户输入搜索
  isLoading: boolean = false;
  addServiceTaskIds:any[] = [];
  taskTypes:any[] = [];
  changeTasktype(e) {
    this.searchTimer(this.getTaskTypes, e);
  }
  // 边输入边搜索节流阀
  searchTimer(fun, e) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e]);
  }
  //获取患者其他服务任务类型
  getTaskTypes(e:string = '') {
    let postData:any = {
      idx: 0,
      sum: 9999,
      taskType: {
        taskName: e,
        simpleQuery: true,
        hosId: {
          id: this.hosId
        },
        associationType: {
          key: 'association_types',
          value: 'patientTransport'
        }
      }
    };
    this.isLoading = true;
    this.mainService.getFetchDataList("simple/data", "taskType", postData)
      .subscribe((result) => {
        this.isLoading = false;
        if (result.status == 200) {
          this.taskTypes = result.list || [];
        }
      });
  }
  //获取积分计算方式
  integralCalculationMethods:any = [];
  dLoading = false;
  getIntegralCalculationMethod() {
    this.dLoading = true;
    this.mainService
      .getDictionary("list", "integral_calculation_method")
      .subscribe((data) => {
        this.dLoading = false;
        this.integralCalculationMethods = data;
        this.getTaskType();
      });
  }
  // 切换tab
  tabModal(tabModalName:string){
    this.tabModalName = tabModalName;
  }
  // 修改是否自动建单
  // changeAutoCreateOrders(e){
  //   console.log(e);
  //   if(!e[0].checked){
  //     this.autoDepts[0].checked = false;
  //   }
  // }
  // 保存
  submitForm() {
    if(!this.tasktype.id){
      this.msg.create("warning", "请先配置患者陪检任务类型！");
      return;
    }
    if(this.multiplayerMode[0].checked && !this.integralCalculationMethod){
      this.msg.create("warning", "请选择积分计算方式！");
      return;
    }
    if(this.accurateTimeFilling[0].checked && !this.timeMod){
      this.msg.create("warning", "请选择精确时间模式！");
      return;
    }
    if(this.batchInspectAutoClear[0].checked && !this.batchInspectAutoClearTime){
      this.msg.create("warning", "请选择时分！");
      return;
    }
    if(this.addService[0].checked && !this.addServiceTaskIds.length){
      this.msg.create("warning", "请选择追加服务任务类型！");
      return;
    }
    if(!this.radioBatchInspectTypesValue){
      this.msg.create("warning", "请选择批量陪检配置方式！");
      return;
    }
		if(!this.yytimeGapMinute){
		  this.msg.create("warning", "请输入默认预约间隔时长！");
		  return;
		}
    // if(!this.handoverMode){
    //   this.msg.create("warning", "请选择交接方式！");
    //   return;
    // }
    // if(!this.radioCheckModesValue){
    //   this.msg.create("warning", "请选择核对方式！");
    //   return;
    // }
    let signTypeIds = this.checkInModes.filter(v => v.checked).map(v => v.value).toString();
    // let closeTypeIds = this.automaticCustomsOrders.filter(v => v.checked).map(v => v.value).toString();
    let postData:any = {
      ...this.configs,
      taskType: this.tasktype.id,
      hosId: this.hosId,
      multiplayerMode: this.multiplayerMode[0].checked ? 1 : 0,
      integralCalculationMethod: this.multiplayerMode[0].checked ? this.integralCalculationMethod : undefined,
      accurateTimeFilling: this.accurateTimeFilling[0].checked ? 1 : 0,
      batchInspectAutoClear: this.batchInspectAutoClear[0].checked ? 1 : 0,
      queuingInformation: this.queuingInformation[0].checked ? 1 : 0,

      startShowAnotherService: this.startShowAnotherService[0].checked ? 1 : 0,
      endShowAnotherService: this.endShowAnotherService[0].checked ? 1 : 0,
      handoverOrder: this.handoverOrder[0].checked ? 1 : 0,
      finishService: this.finishService[0].checked ? 1 : 0,
      isThirdOutpatient: this.isThirdOutpatient[0].checked ? 1 : 0,
      isThirdEmergencyPatient: this.isThirdEmergencyPatient[0].checked ? 1 : 0,
      batchCreationAndReturn: this.batchCreationAndReturn[0].checked ? 1 : 0,
      batchSignExecutionDept: this.batchSignExecutionDept[0].checked ? 1 : 0,
      batchSignEndDept: this.batchSignEndDept[0].checked ? 1 : 0,
      batchSignExecutionParent: this.batchSignExecutionParent[0].checked ? 1 : 0,
      batchSignEndParent: this.batchSignEndParent[0].checked ? 1 : 0,
      hideInspectScan: this.hideInspectScan[0].checked ? 1 : 0,
      enableGoods: this.enableGoods[0].checked ? 1 : 0,
      enableTripType: this.enableTripType[0].checked ? 1 : 0,
      nurseAppendInspect: this.nurseAppendInspect[0].checked ? 1 : 0,
      signReassign: this.signReassign[0].checked ? 1 : 0,
      updatePatientIllness: this.updatePatientIllness[0].checked ? 1 : 0,
			inspectUserAuditCreate: this.inspectUserAuditCreate[0].checked ? 1 : 0,
      inspectDelayOneDay: this.inspectDelayOneDay[0].checked ? 1 : 0,
      // yyInspectMergeOrder: this.yyInspectMergeOrder[0].checked ? 1 : 0,
      addService: this.addService[0].checked ? 1 : 0,
      addServiceTaskIds: this.addServiceTaskIds.length ? this.addServiceTaskIds.toString() : undefined,
      batchInspectType: this.radioBatchInspectTypesValue || undefined,
			yytimeGapMinute: this.yytimeGapMinute || undefined,

      timeMod: this.timeMod || undefined,
      batchInspectAutoClearTime: this.batchInspectAutoClearTime ? format(this.batchInspectAutoClearTime, 'yyyy-MM-dd HH:mm:ss') : undefined,
      // autoCreate: this.autoCreateOrders[0].checked ? 1 : 0,
      // autoDept: this.autoDepts[0].checked ? 1 : 0,
      // handoverType: {id: this.handoverMode},
      // checkType: {id: this.radioCheckModesValue},
      signTypeIds: signTypeIds || undefined,
      // closeTypeIds: closeTypeIds || undefined,
    };
    this.btnLoading = true;
    this.mainService
      .simplePost("addData", "taskTypeConfig", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        if (result.status == 200) {
          this.getConfig();
        }
      });
  }

  //获取交接方式
  // getHandoverModes() {
  //   this.mainService.getDictionary("list", "ttconfig_handover_type").subscribe((data) => {
  //     this.handoverModes = data;
  //     this.handoverMode = data[0].id;
  //   });
  // }
  //获取核对方式
  // getCheckModes() {
  //   this.mainService.getDictionary("list", "ttconfig_check_type").subscribe((data) => {
  //     this.checkModes = data.map(v => ({label:v.name, value: v.id}));
  //   });
  // }
  //获取签到方式
  getCheckInModes() {
    this.loading = true;
    this.mainService.getDictionary("list", "inspect_config_sign_type").subscribe((data) => {
      this.checkInModes = data.map(v => ({label:v.name, value: v.id}));
      // this.getAutomaticCustomsOrders();
      // this.getTaskType();
      this.getIntegralCalculationMethod();
    });
  }
  //获取自动关单
  // getAutomaticCustomsOrders() {
  //   this.mainService.getDictionary("list", "ttconfig_close_type").subscribe((data) => {
  //     this.automaticCustomsOrders = data.map(v => ({label:v.name, value: v.id}));
  //     this.getTaskType();
  //   });
  // }
  //获取任务类型
  getTaskType() {
    let postData = {
      idx: 0,
      sum: 10,
      taskType: {
        simpleQuery: true,
        hosId: {
          id: this.hosId
        },
        associationType: {
          key:"association_types",
          value: 'inspect'
        }
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskType", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.tasktype = result.list[0] || {};
          this.getConfig();
        }
      });
  }
  // 获取配置
  // radioCheckModesValue = '';
  radioBatchInspectTypesValue = '';
  getConfig() {
    this.loading = true;
    let postData = {
      idx: 0,
      sum: 10,
      taskTypeConfig: {
        taskTypeDTO: {
          hosId: {
            id: this.hosId
          },
          associationType: this.tasktype.associationType
        }
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskTypeConfig", postData)
      .subscribe((result) => {
        this.loading = false;
        if (result.status == 200) {
          this.configs = result.list[0] || {};
          // this.handoverMode = this.configs.handoverType?this.configs.handoverType.id:undefined;
          // this.radioCheckModesValue = this.configs.checkType.id;
          // this.autoCreateOrders[0].checked = this.configs.autoCreate == 1;
          // this.autoDepts[0].checked = this.configs.autoDept == 1;
					this.yytimeGapMinute = this.configs.yytimeGapMinute || undefined;
          this.radioBatchInspectTypesValue = this.configs.batchInspectType || undefined;
          if(this.configs.signTypeIds){
            let ids = this.configs.signTypeIds.split(',');
            this.checkInModes = this.checkInModes.map(v => ({...v, checked: ids.includes(v.value.toString())}));
          }
          this.multiplayerMode[0].checked = this.configs.multiplayerMode == 1;
          this.integralCalculationMethod = this.configs.integralCalculationMethod;
          this.accurateTimeFilling[0].checked = this.configs.accurateTimeFilling == 1;
          this.batchInspectAutoClear[0].checked = this.configs.batchInspectAutoClear == 1;
          this.timeMod = this.configs.timeMod || null;
          this.batchInspectAutoClearTime = this.configs.batchInspectAutoClearTime ? new Date(this.configs.batchInspectAutoClearTime) : undefined;
          this.queuingInformation[0].checked = this.configs.queuingInformation == 1;

          this.startShowAnotherService[0].checked = this.configs.startShowAnotherService == 1;
          this.endShowAnotherService[0].checked = this.configs.endShowAnotherService == 1;
          this.handoverOrder[0].checked = this.configs.handoverOrder == 1;
          this.finishService[0].checked = this.configs.finishService == 1;
          this.isThirdOutpatient[0].checked = this.configs.isThirdOutpatient == 1;
          this.isThirdEmergencyPatient[0].checked = this.configs.isThirdEmergencyPatient == 1;
          this.batchCreationAndReturn[0].checked = this.configs.batchCreationAndReturn == 1;
          this.batchSignExecutionDept[0].checked = this.configs.batchSignExecutionDept == 1;
          this.batchSignEndDept[0].checked = this.configs.batchSignEndDept == 1;
          this.batchSignExecutionParent[0].checked = this.configs.batchSignExecutionParent == 1;
          this.batchSignEndParent[0].checked = this.configs.batchSignEndParent == 1;
          this.hideInspectScan[0].checked = this.configs.hideInspectScan == 1;
          this.enableGoods[0].checked = this.configs.enableGoods == 1;
          this.enableTripType[0].checked = this.configs.enableTripType == 1;
          this.nurseAppendInspect[0].checked = this.configs.nurseAppendInspect == 1;
          this.signReassign[0].checked = this.configs.signReassign == 1;
          this.updatePatientIllness[0].checked = this.configs.updatePatientIllness == 1;
					this.inspectUserAuditCreate[0].checked = this.configs.inspectUserAuditCreate == 1;
					// this.yyInspectMergeOrder[0].checked = this.configs.yyInspectMergeOrder == 1;
          this.inspectDelayOneDay[0].checked = this.configs.inspectDelayOneDay == 1;
          // this.yyInspectMergeOrder[0].checked = this.configs.yyInspectMergeOrder == 1;
          this.addService[0].checked = this.configs.addService == 1;
          this.addServiceTaskIds = this.configs.addServiceTaskIds ? this.configs.addServiceTaskIds.split(',').map(v => +v) : [];


          // if(this.configs.closeTypeIds){
          //   let ids = this.configs.closeTypeIds.split(',');
          //   this.automaticCustomsOrders = this.automaticCustomsOrders.map(v => ({...v, checked: ids.includes(v.value.toString())}));
          // }
        }
      });
  }
}


