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 { forkJoin, Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { NzMessageService } from "ng-zorro-antd";
@Component({
  selector: "app-check-dept-exception",
  templateUrl: "./check-dept-exception.component.html",
  styleUrls: ["./check-dept-exception.component.less"],
})
export class CheckDeptExceptionComponent implements OnInit {
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private router: Router,
    private tool: ToolService
  ) {}

  userInfo: any = JSON.parse(localStorage.getItem("user")) || {}; //登录用户信息

  searchCriteria = {
    //搜索条件
    hospital: null,
    startDepartment: null,
  };
  department = []; // 院区下的科室列表(分类型)
  department1 = []; // 院区下的科室列表
  departmentSearch = []; // 院区下的科室列表(搜索框)
  allHospital: any = []; //院区下拉框
  hosId: any; //当前选中院区
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  tableHeight: number; //表格动态高
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //当前操作列id

  hospitalList: Array<object> = []; //院区列表
  btnLoading: boolean = false; //提交按钮loading状态
  printLoading: boolean = false; //批量打印按钮loading状态

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  demoValue: number = 0;
  changeInpSubject = new Subject();
  ngOnInit() {
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.searchDepartment(v[0], v[1]);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getAllHospital();
    this.initForm();
    this.getHospitalList();
  }
  // 选中表格中快捷建单
  mapOfCheckedId = {};
  checkedDepIds = []; //已选中快捷建单id
  refreshStatus(): void {
    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();
  }

  // 选择院区
  changeHospital(id, type) {
    if (type === "search") {
      this.searchCriteria.startDepartment = null;
    } else {
      if (
        this.validateForm &&
        this.validateForm.value &&
        this.validateForm.value.endDepartment
      ) {
        this.validateForm.controls.startDepartment.setValue(null);
        this.validateForm.controls.endDepartment.setValue(null);
      }
    }
    // 1,请求指定科室类型的科室列表
    let data = {
      department: {
        hospital: { id },
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("data", "department", data)
      .subscribe((data) => {
        if (data.status == 200) {
          if (type === "search") {
            this.departmentSearch = data.list;
          } else {
            this.department = data.list;
          }
        }
      });
    if (type === "search") {
      return;
    }
    // 2,请求科室类型为检验科的科室列表
    let data2 = {
      department: {
        hospital: { id },
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("data", "department", data2)
      .subscribe((data) => {
        if (data.status == 200) {
          this.department1 = data.list;
        }
      });
  }
  // 打开搜索框
  changeSearch(flag) {
    if (flag) {
      this.changeInp("no", "search");
    }
  }
  changeForm(flag) {
    if (flag) {
      this.changeInp("no", "form");
    }
  }
  changeFormEnd(flag) {
    if (flag) {
      this.changeInp("no", "formEnd");
    }
  }
  // 边输边搜节流阀
  isLoading = false;
  changeInp(dept, type) {
    if (dept === "no") {
      dept = "";
    }
    if (type === "form" || type === "formEnd") {
      if (!this.hosId) {
        this.department = [];
        return;
      }
    }
    this.isLoading = true;
    this.changeInpSubject.next([dept, type]);
  }
  // 搜索科室
  snum = 0;
  searchDepartment(dept, type) {
    let data = {
      department: {
        dept,
        hospital: {
          id: this.hosId,
        },
      },
      idx: 0,
      sum: 10,
    };
    this.snum++;
    this.mainService
      .getFetchDataList("data", "department", data)
      .subscribe((data) => {
        this.snum--;
        if (data.status == 200) {
          if (type === "search") {
            if (this.snum === 0) {
              this.isLoading = false;
            }
            this.departmentSearch = data.list;
          } else if (type === "form") {
            if (this.snum === 0) {
              this.isLoading = false;
            }
            this.department = data.list;
          } else if (type === "formEnd") {
            if (this.snum === 0) {
              this.isLoading = false;
            }
            this.department1 = data.list;
          }
        }
      });
  }

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

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

  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let postData = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      inspectDeptAbnormalSettings: {
        hospitalId: this.hosId,
      },
    };
    this.mapOfCheckedId = {};
    this.checkedDepIds = [];
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "inspectDeptAbnormalSettings", postData)
      .subscribe((result: any) => {
        this.loading1 = false;
        if (result.status == 200) {
          this.listOfData = result.list;
          this.listLength = result.totalNum;
        }
      });
  }

  // 新增/编辑弹框
  addModal() {
    this.add = true; //新增
    this.modal = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }
  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      keyword: [null, [Validators.required]],
      startDepartment: [null, [Validators.required]],
      endDepartment: [null, [Validators.required]],
    });
    this.timeSelectedValue = [];
  }

  // 新增/编辑表单提交
  submitForm(): void {
    this.btnLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      this.btnLoading = false;
      return;
    }
    let data = {};
    let startDepartmentInfo =
      this.validateForm.controls.startDepartment.value.split("&&");
    let endDepartmentInfo =
      this.validateForm.controls.endDepartment.value.split("&&");

    if (this.add) {
      //新增baba
      data = {
        hospitalId: this.hosId,
        deleteFlag: 0, //1是删除，0是不删除
        dept: startDepartmentInfo[1], //原科室名字
        deptId: startDepartmentInfo[0], //原科室id
        type: startDepartmentInfo[2], //原科室的科室类型id
        matchingDept: endDepartmentInfo[1], //匹配科室名称
        matchingDeptId: endDepartmentInfo[0], //匹配科室id
        code: this.validateForm.controls.keyword.value, //关键字
      };
    } else {
      //编辑
      data = {
        id: this.coopId,
        hospitalId: this.hosId,
        deleteFlag: 0, //1是删除，0是不删除
        dept: startDepartmentInfo[1], //原科室名字
        deptId: startDepartmentInfo[0], //原科室id
        type: startDepartmentInfo[2], //原科室的科室类型id
        matchingDept: endDepartmentInfo[1], //匹配科室名称
        matchingDeptId: endDepartmentInfo[0], //匹配科室id
        code: this.validateForm.controls.keyword.value, //关键字
      };
    }
    this.mainService
      .simplePost("addData", "inspectDeptAbnormalSettings", data)
      .subscribe((result: any) => {
        this.btnLoading = false;
        this.hideAddModal();
        this.initForm();
        if (result.status == 200) {
          this.listLength++;
          this.showPromptModal(this.add ? "新增" : "修改", true, "");
        } else {
          this.showPromptModal(this.add ? "新增" : "修改", false, "");
        }
      });
  }

  // 编辑
  maskFlag: any = false;
  edit(e, data) {
    e.stopPropagation();
    this.add = false;
    this.coopId = data.id;
    this.validateForm.controls.keyword.setValue(data.code); //关键字
    this.department = [
      {
        id: data.deptId,
        dept: data.dept,
        type: { id: data.type },
      },
    ];
    this.validateForm.controls.startDepartment.setValue(
      `${data.deptId}&&${data.dept}&&${data.type}`
    ); //检查原科室
    this.department1 = [{ id: data.matchingDeptId, dept: data.matchingDept }];
    this.validateForm.controls.endDepartment.setValue(
      `${data.matchingDeptId}&&${data.matchingDept}`
    ); //匹配的科室
    this.modal = true;
  }

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

  // 删除快捷建单
  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  confirmDelIsSwitch: boolean; //启用/停用
  showDelModal(
    e,
    id: number,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
    isSwitch?: boolean
  ) {
    e.stopPropagation();
    this.confirmDelIsSwitch = isSwitch;
    this.confirmDelType = type;
    this.delModal = true;
    this.coopId = id;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      let postData = {
        id: this.coopId,
        deleteFlag: 1,
      };
      this.mainService
        .simplePost("addData", "inspectDeptAbnormalSettings", postData)
        .subscribe((data: any) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            if (
              this.listOfData.length == 1 &&
              this.pageIndex == Math.ceil(this.listLength / this.pageSize)
            ) {
              this.listLength--;
              if (this.listLength === 0) {
                this.pageIndex = 1;
              } else {
                this.pageIndex = Math.ceil(this.listLength / this.pageSize);
              }
            }
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    } else if (this.confirmDelType === "switch") {
      //启用/停用
      this.mainService
        .switchRoundRobin(
          this.confirmDelIsSwitch ? "stop" : "active",
          this.coopId
        )
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }

  // 院区列表
  getHospitalList() {
    this.hospitalList = [this.tool.getCurrentHospital()];
  }
  //时间选择框相关
  timeSelectedValue = [];
  defaultSelectTimesOption = [];

  time: Date | null = null;
  defaultTimePickerOpenValue = new Date();
  timePickerOpen = false;
  timeSelectFocus() {
    this.timePickerOpen = true;
  }
  timePickerClick() {
    this.timePickerOpen = false;
    this.time = this.time || new Date();
    let hour = (this.time.getHours() + "").padStart(2, "0");
    let minute = (this.time.getMinutes() + "").padStart(2, "0");
    let str = `${hour}:${minute}`;
    if (!this.timeSelectedValue.includes(str)) {
      this.defaultSelectTimesOption.push(str);
      this.timeSelectedValue.push(str);
    }
  }
  timePickerChange() {
    if (this.timePickerOpen) {
      this.timePickerOpen = false;
    }
  }
}
