import { Component, OnInit } from "@angular/core";
import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { format } from "date-fns";
@Component({
  selector: "app-specimen-search",
  templateUrl: "./specimen-search.component.html",
  styleUrls: ["./specimen-search.component.less"],
})
export class SpecimenSearchComponent implements OnInit {
  constructor(private mainService: MainService, private tool: ToolService) {}

  currentUserAccount: any = JSON.parse(localStorage.getItem("user")).user.account; //当前登录人账号
  searchCriteria = {
    //搜索条件
    scode: "",
    parent: "",
    hospital: null,
    department: null,
    speState: null,
    receiverName: null,
    dateRange: [],
    checkDept: null,
  };
  types = []; // 类型列表(搜索框)
  departmentSearch = []; // 院区下的科室列表(搜索框)
  userSearch = []; // 院区下的人员列表(搜索框)
  allHospital: any = []; //院区下拉框
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  checkOptionsOne: Array<any> = [
    { label: "服务中心收取", value: "0", checked: true },
  ];
  changeInpSubject = new Subject();
  changeInp2Subject = new Subject();
  ngOnInit() {
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.searchDepartment(v[0], v[1]);
    });
    this.changeInp2Subject.pipe(debounceTime(500)).subscribe((v) => {
      this.searchUser(v[0], v[1]);
    });
    this.getAllHospital();
  }
  // 表格筛选
  log(value: object[]): void {
    console.log(value);
    this.getList(1, this.sortCurrentKey, this.sortCurrentValue);
  }
  // 搜索类型
  isLoading1 = false;
  searchTypes() {
    this.isLoading1 = true;
    this.mainService.getDictionary("list", "speState").subscribe((res) => {
      this.isLoading1 = false;
      this.types = res;
    });
  }
  // 清空标本
  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  showDelModal(tipsMsg1: string) {
    this.delModal = true;
    this.tipsMsg1 = tipsMsg1;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认
  btnLoading: boolean = false; //提交按钮loading状态
  confirmDel() {
    this.btnLoading = true;
    this.mainService
      .coopDataM("api/emptySpecimenData", { hosId: 1, isEmpty: "ok" })
      .subscribe((data) => {
        this.btnLoading = false;
        this.delModal = false;
        if (data.status == 200) {
          this.showPromptModal("标本清空", true, "");
        } else {
          this.showPromptModal("标本清空", false, "");
        }
      });
  }
  // 展示信息提示框（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(0, this.sortCurrentKey, this.sortCurrentValue);
  }
  // 查看标本历史记录
  historyPromptModalShow = false; //标本历史记录弹窗开关
  scode = ""; //查看历史记录携带
  viewSpecimenHistory(data) {
    this.scode = data.scode;
    this.historyPromptModalShow = true;
  }
  // 关闭标本历史记录弹窗
  closeModelHistory(e) {
    this.historyPromptModalShow = JSON.parse(e).show;
  }
  // 日期选择
  startDate: string; //发起时间开始
  endDate: string; //发起时间结束
  changeDate(result?): void {
    if (!result) {
      this.startDate = this.endDate = "";
      return;
    }
    this.startDate =
      result[0].getFullYear() +
      "-" +
      (result[0].getMonth() + 1) +
      "-" +
      result[0].getDate() +
      " " +
      "00:00:00";
    this.endDate =
      result[1].getFullYear() +
      "-" +
      (result[1].getMonth() + 1) +
      "-" +
      result[1].getDate() +
      " " +
      "23:59:59";
  }
  // 重置
  reset() {
    this.searchCriteria = {
      //搜索条件
      scode: "",
      parent: "",
      hospital: this.allHospital[0] ? this.allHospital[0]["id"] + "" : null,
      department: null,
      speState: null,
      receiverName: null,
      dateRange: [],
      checkDept: null,
    };
    this.sortCurrentKey = "";
    this.sortCurrentValue = "";
    this.sortCurrent = {
      arrive_time: null,
    };
    this.getList(1, this.sortCurrentKey, this.sortCurrentValue);
  }
  // 选择院区
  changeHospital(id, type) {
    if (type === "search") {
      this.searchCriteria.department = null;
    }
  }
  // 打开搜索框
  changeSearch1(flag) {
    if (flag) {
      this.searchTypes();
    }
  }
  // 打开搜索框
  changeSearch(flag) {
    if (flag) {
      this.changeInp("no", "search");
    }
  }
  // 打开搜索框
  changeSearch2(flag) {
    if (flag) {
      this.changeInp2("no", "search");
    }
  }
  // 边输边搜节流阀
  isLoading = false;
  deptKey = "";
  changeInp(dept, type) {
    if (!dept) {
      return;
    }
    if (dept === "no") {
      dept = "";
    }
    this.deptKey = dept;
    this.isLoading = true;
    this.changeInpSubject.next([dept, type]);
  }
  // 搜索科室
  searchDepartment(dept, type) {
    let data = {
      department: {
        dept,
        hospital: {
          id: this.searchCriteria.hospital,
        },
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("data", "department", data)
      .subscribe((data) => {
        if (data.status == 200) {
          if (type === "search") {
            if (this.deptKey === dept) {
              this.isLoading = false;
              this.departmentSearch = data.list;
            }
          }
        }
      });
  }
  // 边输边搜节流阀
  userKey = "";
  changeInp2(keyword, type) {
    if (!keyword) {
      return;
    }
    if (keyword === "no") {
      keyword = "";
    }
    this.userKey = keyword;
    this.isLoading = true;
    this.changeInp2Subject.next([keyword, type]);
  }
  // 搜索科室
  searchUser(keyword, type) {
    let data = {
      user: {
        usertype: { id: 106 },
        name: keyword,
        hospital: {
          id: this.searchCriteria.hospital,
        },
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("data", "user", data)
      .subscribe((data) => {
        if (data.status == 200) {
          if (type === "search") {
            if (this.userKey === keyword) {
              this.isLoading = false;
              this.userSearch = data.list;
            }
          }
        }
      });
  }

  // 获取所有院区
  /**
   *
   *
   * @memberof RoundRobinComponent
   */
  getAllHospital() {
    this.allHospital = [this.tool.getCurrentHospital()];
    this.searchCriteria.hospital = this.tool.getCurrentHospital().id + "";
    this.getList(1, this.sortCurrentKey, this.sortCurrentValue);
    this.changeHospital(this.searchCriteria.hospital, "search");
  }

  // 表格数据
  loading1 = false;
  getList(type, field?: string, sort?: string) {
    console.log(this.searchCriteria.dateRange);
    if (type == 1) {
      this.pageIndex = 1;
    }
    let postData: any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      specimen: {
        receivedMark: this.checkOptionsOne[0].checked ? 1 : undefined,
        hosId: this.searchCriteria.hospital,
        sickRoom: this.searchCriteria.department
          ? {
              id: this.searchCriteria.department,
            }
          : undefined,
        checkDept: this.searchCriteria.checkDept
          ? {
              id: this.searchCriteria.checkDept,
            }
          : undefined,
        receiverName: this.searchCriteria.receiverName
          ? this.searchCriteria.receiverName
          : undefined,
        scode: !this.searchCriteria.scode
          ? undefined
          : this.searchCriteria.scode,
        keyWord: !this.searchCriteria.parent
          ? undefined
          : this.searchCriteria.parent,
        speState: this.searchCriteria.speState
          ? { id: this.searchCriteria.speState }
          : undefined,
      },
    };
    if (field && sort) {
      postData.specimen.orderBy = sort === "ascend" ? field : `${field} desc`;
    }
    if (this.searchCriteria.dateRange.length) {
      postData.specimen.startArriveTime =
        format(this.searchCriteria.dateRange[0], "yyyy-MM-dd ") + "00:00:00";
      postData.specimen.endArriveTime =
        format(this.searchCriteria.dateRange[1], "yyyy-MM-dd ") + "23:59:59";
    }
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "specimen", postData)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }
      });
  }

  // 列表排序
  sortCurrent = {
    arrive_time: null,
  };
  sortCurrentKey: string = "";
  sortCurrentValue: string | null = "";
  sort(e) {
    const { key, value } = e;
    this.sortCurrentKey = key;
    this.sortCurrentValue = value;
    this.getList(this.pageIndex, this.sortCurrentKey, this.sortCurrentValue);
  }
}
