import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";

import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { NzMessageService } from 'ng-zorro-antd';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { startOfDay, endOfDay, format } from 'date-fns';
@Component({
  selector: "app-common-info",
  templateUrl: "./common-info.component.html",
  styleUrls: ["./common-info.component.less"],
})
export class CommonInfoComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private router: Router,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}

  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopData: any; //当前操作列
  currentHospital; //当前院区

  btnLoading: boolean = false; //提交按钮loading状态

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  modelName = ""; //模态框名称

  searchTimerSubject = new Subject(); //防抖
  showDropdown:boolean = false;

  dateRange: any = []; //发起时间

  ngOnInit() {
    //防抖
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1]);
    });
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getList(1);
    this.getStatus();
  }

  // 初始化增删改按钮
  coopBtns: any = {};

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

  // 搜索
  search() {
    this.getList(1);
  }
  // 重置
  reset() {
    this.searchDto = {};
    this.dateRange = [];
    this.getList(1);
  }

  // 表格数据
  searchDto: any = {};
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      businessHandover: {
        hosId: this.currentHospital.id,
        collectionUser: this.searchDto.collectionUser || undefined,
        applyDept: this.searchDto.applyDept || undefined,
        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,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "businessHandover", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list || [];
          this.listLength = data.totalNum;
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 防抖
  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 === 'department'){
      this.searchTimer(this.getDeptList, e);
    }else if(type === 'patient'){
      this.searchTimer(this.getDeliveryUserList, e);
    }
  }

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

  openChangeDept(flag){
    flag && this.setIsSelecting(false);
    flag && this.getDeptList();
  }

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

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

  // 获取送达人
  deliveryUserList: any = [];
  getDeliveryUserList(e = undefined) {
    let postData = {
      idx: 0,
      sum: 20,
      user: {
        hospital: { id: this.currentHospital.id },
        name: e,
      }
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "user", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.deliveryUserList = data.list || [];
      });
  }

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

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

  // 查看日志弹窗
  logPromptModalShow = false; //弹窗开关
  packId = ""; //查看记录携带id
  showLogs(data) {
    this.packId = data.id;
    this.logPromptModalShow = true;
  }
  // 关闭日志弹窗
  closeModelLog(e) {
    this.logPromptModalShow = JSON.parse(e).show;
  }

  // 查看
  detail(e, id) {
    e.stopPropagation();
    this.router.navigateByUrl(`/main/commonInfo/orderDetail/${id}`);
  }
}
