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

import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { QuickOrderAcceptanceService } from './quick-order-acceptance.service';

@Component({
  selector: "app-quick-order-acceptance",
  templateUrl: "./quick-order-acceptance.component.html",
  styleUrls: ["./quick-order-acceptance.component.less"],
})
export class QuickOrderAcceptanceComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private tool: ToolService,
    private quickOrderAcceptanceService: QuickOrderAcceptanceService,
  ) {}

  listOfData: any[] = []; //表格数据

  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  department: any; //所属科室
  hosId: any; //院区（搜索）
  typeList: Array<any>; //快捷类型
  taskTypeList: Array<any>; //所有任务类型
  deptList: Array<any>; //所有科室
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示

  btnLoading: boolean = false; //提交按钮loading状态
  changeInpSubject = new Subject(); //防抖
  changeInpDeptSubject = new Subject(); //防抖

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

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getTasktype(v[0]);
    });
    //防抖
    this.changeInpDeptSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getDept(v[0]);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList(true);
  }

  // 搜索
  search() {
    this.getList(true);
  }
  // 表格数据
  loading1 = false;
  getList(isResetPageIndex = false) {
    isResetPageIndex && (this.pageIndex = 1);
    let data = {
      pageIndex: this.pageIndex,
      pageSize: this.pageSize,
      hosId: this.hosId,
    };
    this.loading1 = true;
    this.mapOfCheckedId = {};
    this.checkedDepIds = [];
    this.isAllDisplayDataChecked = false;
    this.quickOrderAcceptanceService
      .query(data)
      .subscribe((result) => {
        this.loading1 = false;
        result.list = result.list || [];
        result.list.forEach(v => {
          v.taskNames = v.taskTypeList.map(v => v.taskName).toString();
          v.deptNames = v.deptList.map(v => v.dept).toString();
        })
        this.listOfData = result.list;
        this.listLength = result.totalNum;
      });
  }

  // 获取任务类型列表
  getTasktype(keywords = '') {
    let hosId = this.tool.getCurrentHospital().id;
    this.isLoading = true;
    this.quickOrderAcceptanceService.queryTasktype({
      hosId,
      keywords,
    }).subscribe((res) => {
      this.isLoading = false;
      this.taskTypeList = res.list || [];
    });
  }

  // 获取科室列表
  getDept(keywords = '') {
    let hosId = this.tool.getCurrentHospital().id;
    this.isLoading = true;
    this.quickOrderAcceptanceService.queryDept({
      hosId,
      keywords,
    }).subscribe((res) => {
      this.isLoading = false;
      this.deptList = res.list || [];
    });
  }

  // 获取快捷类型
  getTypeList() {
    this.isLoading = true;
    this.quickOrderAcceptanceService.getDictionary("receiveRuleType").subscribe((res) => {
      this.isLoading = false;
      this.typeList = res || [];
    });
  }

  // 新增弹框
  showModal() {
    this.add = true;
    this.modal = true;
    this.initForm();
  }
  hideModal() {
    this.modal = false;
    this.initForm();
  }

  // 初始化新增form表单
  initForm() {
    if (this.add) {
      this.typeList = [];
      this.taskTypeList = [];
      this.deptList = [];
    }
    this.validateForm = this.fb.group({
      title: ['', [Validators.required]],
      taskTypeIds: [null, [Validators.required]],
      deptIds: [null, [Validators.required]],
      type: [null, [Validators.required]],
    });
  }
  // 表单提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty({ onlySelf: true });
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.btnLoading = true;
    if(this.add){
      this.quickOrderAcceptanceService
      .add({
        title: this.validateForm.value.title,
        taskTypeIds: this.validateForm.value.taskTypeIds,
        deptIds: this.validateForm.value.deptIds,
        type: {id: this.validateForm.value.type},
        hosId: this.hosId,
      })
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideModal();
        this.initForm();
        if (data.status == 200) {
          this.showPromptModal(this.add ? "新增" : "编辑", true, "");
        } else {
          this.showPromptModal(this.add ? "新增" : "编辑", false, data.msg);
        }
      });
    }else{
      this.quickOrderAcceptanceService
      .update({
        title: this.validateForm.value.title,
        taskTypeIds: this.validateForm.value.taskTypeIds,
        deptIds: this.validateForm.value.deptIds,
        type: {id: this.validateForm.value.type},
        coopData: this.coopData,
      })
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideModal();
        this.initForm();
        if (data.status == 200) {
          this.showPromptModal(this.add ? "新增" : "编辑", true, "");
        } else {
          this.showPromptModal(this.add ? "新增" : "编辑", false, data.msg);
        }
      });
    }
  }

  // 选中表格中科室
  mapOfCheckedId: { [key: string]: boolean } = {};
  checkedDepIds = []; //已选中科室id
  refreshStatus(): void {
    this.isAllDisplayDataChecked = this.listOfData.every(
      (item) => this.mapOfCheckedId[item.id]
    );
    let arr = [];
    for (var k in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[k]) {
        arr.push(Number(k));
      }
    }
    this.checkedDepIds = arr;
    console.log(this.checkedDepIds);
  }

  //表格整行选中
  selectedListData(id) {
    this.mapOfCheckedId[id] = !this.mapOfCheckedId[id];
    this.refreshStatus();
  }

  // 全选
  isAllDisplayDataChecked = false; //当前页是否全选
  checkAll(value: boolean): void {
    this.listOfData.forEach((item) => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  // 打印
  codes = []; //二维码
  printLoading: boolean = false; //批量打印按钮loading状态
  print(e, batch, id?) {
    e.stopPropagation();
    this.printLoading = true;
    this.quickOrderAcceptanceService
      .print({
        ids: batch ? this.checkedDepIds.toString() : id.toString()
      })
      .subscribe((data) => {
        this.codes = data.data;
        this.printLoading = false;
        setTimeout(() => {
          const printContent = document.getElementById("report");
          const WindowPrt = window.open("", "", "width=700,height=900");
          WindowPrt.document.write(printContent.innerHTML);
          WindowPrt.document.close();
          WindowPrt.focus();
          WindowPrt.print();
          WindowPrt.close();
        }, 100);
      });
  }

  // 编辑
  maskFlag: any = false;
  coopData = {};
  edit(data) {
    this.validateForm.controls.title.setValue(data.title);
    this.validateForm.controls.type.setValue(data.type ? data.type.id : null);
    this.validateForm.controls.taskTypeIds.setValue(data.taskTypeList ? data.taskTypeList.map(v => v.id) : null);
    this.validateForm.controls.deptIds.setValue(data.deptList ? data.deptList.map(v => v.id) : null);
    this.modal = true;
    this.add = false;
    this.coopId = data.id;
    this.coopData = data;
    this.getTasktype();
    this.getDept();
    this.getTypeList();
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    this.coopId = data.id;
    this.delModal = true;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    this.quickOrderAcceptanceService
      .delete({
        id: this.coopId
      })
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideDelModal();
        if (data.status == 200) {
          if (this.listOfData.length == 1 && this.pageIndex == Math.ceil(this.listLength / this.pageSize)) {
            this.listLength--;
            this.pageIndex = Math.ceil(this.listLength / this.pageSize);
          }
          this.showPromptModal("删除", true, "");
        } else {
          this.showPromptModal("删除", false, data.msg);
        }
      });
  }

  // 关闭删除模态框
  hideDelModal() {
    this.delModal = false;
  }

  // 展示信息提示框（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(true);
  }

  // 边输边搜节流阀
  isLoading = false;
  changeInp(e) {
    this.changeInpSubject.next([e]);
  }

  // 边输边搜节流阀
  changeDeptInp(e) {
    this.changeInpDeptSubject.next([e]);
  }

  // 打开任务类型
  openTasktype(e){
    if(e){
      this.getTasktype();
    }
  }

  // 打开科室
  openDept(e){
    if(e){
      this.getDept();
    }
  }

  // 打开班次
  openSchedule(e){
    if(e){
      this.getTypeList();
    }
  }
}


