import { Component, OnInit, OnDestroy } from '@angular/core';
import { ToolService } from 'src/app/services/tool.service';
import { MainService } from 'src/app/services/main.service';
import { NzMessageService } from 'ng-zorro-antd';
import { startOfDay, endOfDay, format } from 'date-fns';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { Location } from '@angular/common';
import cloneDeep from 'lodash-es/cloneDeep'
import { ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-inspect-closed-loop-view',
  templateUrl: './inspect-closed-loop-view.component.html',
  styleUrls: ['./inspect-closed-loop-view.component.less']
})
export class InspectClosedLoopViewComponent implements OnInit, OnDestroy {

  constructor(
    private mainService: MainService,
    private tool: ToolService,
    private message: NzMessageService,
    private _location: Location,
    private route: ActivatedRoute,
  ) { }

  hosId:any = this.tool.getCurrentHospital().id; //当前院区
  deptDTO:any = this.tool.getCurrentUserDept(); //当前科室
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  searchDto: any = {};
  autoRefresh:boolean = false;
  autoRefreshSecond: number = 15;

  dateRange: any = []; //预约时间

  formatterPercent = (value: number) => `${value} 秒`;
  parserPercent = (value: string) => value.replace(' 秒', '');


  searchTimerSubject = new Subject(); //防抖

  // 初始化增删改按钮
  coopBtns: any = {};
  coopData: any = {}; //当前操作列
  btnLoading: boolean = false; //提交按钮loading状态

  ngOnInit() {
    //防抖
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1]);
    });

    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.init();
  }

  ngOnDestroy() {
    clearInterval(this.timer);
  }

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  showDelModal(
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    this.confirmDelType = type;
    this.delModal = true;
    this.coopData = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "tagBackDepartment") {
      let postData = {
        pilId: this.coopData.id,
      };
      //标记回科
      this.mainService
        .setPatientInspectBackDept(postData)
        .subscribe((data:any) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.state == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
    this.getList(1);
  }

  // 日期选择
  onCalendarChangeDate(dateArr){
    if(dateArr.length == 2){
      this.dateRange = [startOfDay(dateArr[0]), endOfDay(dateArr[1])];
    }
  }

  // 修改自动刷新时间
  timer;
  time: number = 15;
  changeAutoRefresh(flag){
    if(flag){
      this.time = this.autoRefreshSecond;
      console.log('this.time:', this.time)
      clearInterval(this.timer);
      this.timer = setInterval(() => {
        this.time--;
        console.log('this.time:', this.time)
        if(this.time === 0){
          this.time = this.autoRefreshSecond;
          this.search();
        }
      }, 1000);
    }else{
      clearInterval(this.timer);
    }
  }

  // 搜索
  search() {
    this.getList(1);
  }

  // 重置
  reset() {
    if(this.disableDept){
      this.searchDto = { deptId: this.searchDto.deptId };
    }else{
      this.searchDto = {};
    }
    this.dateRange = [];
    this.getList(1);
  }

  disableDept:boolean = false;
  init(){
    const queryParams = this.route.snapshot.queryParams.queryParams ? JSON.parse(this.route.snapshot.queryParams.queryParams) : undefined;
    if(queryParams){
      if(queryParams.department){
        this.searchDto.deptId = queryParams.department.id;
        this.departmentList = [queryParams.department];
        this.disableDept = true;
      }

      if(queryParams.stateValue){
        this.searchDto.stateValue = queryParams.stateValue.split(',');
      }
    }
    this.getStatusList();
    this.search();
  }

  // 防抖
  isLoading = false;
  isSelecting:boolean = false; // 是否在选中状态
  searchTimer(fun, e) {
    if (this.isSelecting) {
      this.isSelecting = false; // 重置标志
      return; // 跳过处理
    }
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e]);
  }

  // 搜索
  changeInp(type, e) {
    if(type === 'patient'){
      this.searchTimer(this.getPatientList, e);
    }else if(type === 'department'){
      this.searchTimer(this.getDepartmentList, e);
    }
  }

  // 设置标志
  setIsSelecting(flag){
    this.isSelecting = flag; // 设置标志
  }


  openChangePatient(flag){
    flag && this.setIsSelecting(false);
    flag && this.getPatientList();
  }

  // 获取患者
  patientList: any = [];
  getPatientList(e = undefined) {
    let postData = {
      idx: 0,
      sum: 20,
      patient: {
        hosId: this.hosId,
        keyWord: e,
      }
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "patient", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.patientList = data.list || [];
      });
  }

  openChangeDepartment(flag){
    flag && this.setIsSelecting(false);
    flag && this.getDepartmentList();
  }

  // 获取科室
  departmentList: any = [];
  getDepartmentList(e = undefined) {
    let postData = {
      idx: 0,
      sum: 20,
      department: {
        searchType: 1,// 简单查询
        hospital: { id: this.hosId },
        dept: e,
      }
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "department", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.departmentList = data.list || [];
      });
  }

  // 获取状态
  statusList: any = [];
  getStatusList() {
    this.mainService.getDictionary('list', 'patient_inspect_state').subscribe((data) => {
      this.statusList = data || [];
    });
  }

  loading1:boolean = false;

  // 表格数据
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      patientInspectLog: {
        startTime: this.dateRange.length ? format(this.dateRange[0], 'yyyy-MM-dd HH:mm:ss') : undefined,
        endTime: this.dateRange.length ? format(this.dateRange[1], 'yyyy-MM-dd HH:mm:ss') : undefined,
        hosId: this.hosId,
        deptId: this.searchDto.deptId || undefined,
        patientId: this.searchDto.patientId || undefined,
        state: this.searchDto.stateValue ? { value: this.searchDto.stateValue.toString() } : undefined,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "patientInspectLog", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          let list = data.list || [];
          list.forEach(v => {
            v.inspectNames = v.inspectList ? v.inspectList.map(v => v.inspectName).join('，') : '';
          })
          this.listOfData = list;
          this.listLength = data.totalNum;
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 返回
  goBack(){
    this._location.back();
  }

}
