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 { DepartmentDistanceService } from './department-distance.service';

@Component({
  selector: "app-department-distance",
  templateUrl: "./department-distance.component.html",
  styleUrls: ["./department-distance.component.less"],
})
export class DepartmentDistanceComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private tool: ToolService,
    private departmentDistanceService: DepartmentDistanceService,
  ) {}

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

  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  department: any; //所属科室
  hosId: any; //院区（搜索）
  deptList: Array<any>; //所有班次
  taskTypeList: 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(); //防抖
  changeScheduleSubject = new Subject(); //防抖

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

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getOtherTasktype(v[0]);
    });
    //防抖
    this.changeScheduleSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getDeptList(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.departmentDistanceService
      .query(data)
      .subscribe((result) => {
        this.loading1 = false;
        result.list = result.list || [];
        result.list.forEach(v => {
          v.taskNames = v.taskTypeList.map(v => v.taskName).toString();
        })
        this.listOfData = result.list;
        this.listLength = result.totalNum;
      });
  }

  // 获取任务类型列表-其他临床服务
  getOtherTasktype(keywords = '') {
    let hosId = this.tool.getCurrentHospital().id;
    this.isLoading = true;
    this.departmentDistanceService.queryOtherTasktype({
      hosId,
      keywords,
    }).subscribe((res) => {
      this.isLoading = false;
      this.taskTypeList = res.list || [];
    });
  }

  // 获取科室
  getDeptList(keywords = '') {
    let hosId = this.tool.getCurrentHospital().id;
    this.isLoading = true;
    let postData = {
      idx: 0,
      sum: 9999,
      department: {
        searchType: 1,// 简单查询
        dept: keywords,
        cascadeHosId: hosId,
      }
    };
    this.departmentDistanceService.getDepartments(postData).subscribe((res) => {
      this.isLoading = false;
      this.deptList = res.list || [];
    });
  }

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

  // 初始化新增form表单
  initForm() {
    if (this.add) {
      this.deptList = [];
      this.taskTypeList = [];
    }
    this.validateForm = this.fb.group({
      grade: [0, [Validators.required]],
      deptId: [null, [Validators.required]],
      taskTypeIds: [null, [Validators.required]],
      start: [null, [Validators.required]],
      end: [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.departmentDistanceService
      .add({
        grade: this.validateForm.value.grade,
        deptId: this.validateForm.value.deptId,
        taskTypeIds: this.validateForm.value.taskTypeIds.toString(),
        start: this.validateForm.value.start,
        end: this.validateForm.value.end,
        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.departmentDistanceService
      .update({
        ...this.coopData,
        grade: this.validateForm.value.grade,
        deptId: this.validateForm.value.deptId,
        taskTypeIds: this.validateForm.value.taskTypeIds.toString(),
        start: this.validateForm.value.start,
        end: this.validateForm.value.end,
      })
      .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);
        }
      });
    }
  }

  // 编辑
  maskFlag: any = false;
  coopData = {};
  edit(data) {
    this.validateForm.controls.grade.setValue(data.grade);
    this.validateForm.controls.deptId.setValue(data.deptId);
    this.validateForm.controls.taskTypeIds.setValue(data.taskTypeList ? data.taskTypeList.map(v => v.id) : null);
    this.validateForm.controls.start.setValue(data.start);
    this.validateForm.controls.end.setValue(data.end);
    this.modal = true;
    this.add = false;
    this.coopId = data.id;
    this.coopData = data;
    this.getOtherTasktype();
    this.getDeptList();
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    this.coopId = data.id;
    this.delModal = true;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    this.departmentDistanceService
      .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]);
  }

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

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

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


