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

import { MainService } from "../../services/main.service";
import { ToolService } from "src/app/services/tool.service";
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: "app-hospital-management",
  templateUrl: "./hospital-management.component.html",
  styleUrls: ["./hospital-management.component.less"],
})
export class HospitalManagementComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private tool: ToolService
  ) {}

  ngOnInit() {
    this.searchParentHospitalSubject.pipe(debounceTime(500)).subscribe(({e, type}) => {
      if(type === 'parentDept'){
        this.getAllParentHospital(e, type === 'parentDept').subscribe((result) => {
          this.isLoading = false;
          if (result.status == 200) {
            this.parentDepts = result.list;
          }
        });
      }else if(type === 'parent'){
        this.getAllParentHospital(e, type === 'parentDept').subscribe((result) => {
          this.isLoading = false;
          if (result.status == 200) {
            this.parentHospitals = result.list;
          }
        });
      }

    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getList();
    this.initForm();
    this.initFormCopy();
    this.getHospitalType();
  }

  currentUserAccount: any = JSON.parse(localStorage.getItem("user")).user.account; //当前登录人账号
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  modal: boolean = false; //新增/编辑模态框
  modalCopy: boolean = false; //复制模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  validateFormCopy: FormGroup; //复制表单
  coopId: number; //当前操作列id

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

  btnLoading: boolean = false; //确认按钮loading状态

  // 初始化增删改按钮
  coopBtns: any = {};
  //所有院区
  parentHospitals: any = [];
  parentDepts: any = [];
  searchParentHospitalSubject = new Subject();
  //搜索父级院区
  changeInp(e, type) {
    this.isLoading = true;
    this.searchParentHospitalSubject.next({e, type});
  }
  // 打开父级科室下拉框
  isLoading = false;
  openHospitalSelect(flag) {
    if (flag) {
      this.isLoading = true;
      this.getAllParentHospital().subscribe((result) => {
        this.isLoading = false;
        if (result.status == 200) {
          this.parentHospitals = result.list;
        }
      });
    }
  }
  // 打开父级部门下拉框
  openParentDeptSelect(flag) {
    if (flag) {
      this.isLoading = true;
      this.getAllParentHospital('', true).subscribe((result) => {
        this.isLoading = false;
        if (result.status == 200) {
          this.parentDepts = result.list;
        }
      });
    }
  }
  // 选择父级科室下拉框
  changeHospitalSelect(e) {
    if(!e){
      this.validateForm.controls.hospitalType.setValue(null);
    }
    this.requiredChange(Boolean(e), 'hospitalType');
  }
  // 打开部门类型下拉框
  isHospitalTypeLoading = false;
  hospitalTypes: any = [];
  openHospitalTypeSelect(flag) {
    if (flag) {
      this.isHospitalTypeLoading = true;
      this.mainService.getDictionary("list", "hospital_type").subscribe((result) => {
        this.isHospitalTypeLoading = false;
        this.hospitalTypes = result;
      });
    }
  }
  // 获取院区类型
  getHospitalType() {
    this.mainService.getDictionary("list", "hospital_type").subscribe((result) => {
      this.hospitalTypes = result || [];
    });
  }
  //获取所有的父级院区列表
  getAllParentHospital(keyWord = "", isParentDept = false) {
    if(isParentDept){
      let postData: any = {
        idx: 0,
        sum: 10,
        hospital: {
          keyWord: keyWord,
          type: isParentDept ? this.hospitalTypes.find(v => v.value == 6) : undefined
        },
      };
      if (this.coopId) {
        // 过滤这个院区及其子院区
        postData.hospital.filterByHosId = this.coopId;
      }
      return this.mainService.getFetchDataList("data", "hospital", postData);
    }else{
      let postData: any = {
        idx: 0,
        sum: 10,
        hospital: {
          keyWord: keyWord,
        },
      };
      if (this.coopId) {
        // 过滤这个院区及其子院区
        postData.hospital.filterByHosId = this.coopId;
      }
      return this.mainService.getFetchDataList("data", "hospital", postData);
    }
  }

  // 表格数据
  loading1 = false;
  getList() {
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("data", "hospital", data)
      .subscribe((data) => {
        this.loading1 = false;
        this.listOfData = data.list;
        this.listLength = data.totalNum;
      });
  }

  // 修改验证规则-是否必选
  requiredChange(required: boolean, field: string): void {
    if (!required) {
      this.validateForm.get(field)!.clearValidators();
      this.validateForm.get(field)!.markAsPristine();
    } else {
      this.validateForm.get(field)!.setValidators(Validators.required);
      this.validateForm.get(field)!.markAsDirty();
    }
    this.validateForm.get(field)!.updateValueAndValidity();
  }


  addModal() {
    this.add = true;
    this.modal = true;
    this.validateForm.controls.parentHospital.setValue(null);
    this.validateForm.controls.hospitalName.setValue("");
    this.validateForm.controls.hospitalNum.setValue("");
  }
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }
  copy(data) {
    this.coopId = data.id;
    this.addModalCopy();
  }
  addModalCopy() {
    this.modalCopy = true;
  }
  hideAddModalCopy() {
    this.modalCopy = false;
    this.initFormCopy();
  }
  // 初始化复制form表单
  initFormCopy() {
    this.validateFormCopy = this.fb.group({
      copyHosId: [null, [Validators.required]],
    });
  }
  // 复制表单提交
  submitFormCopy(): void {
    var that = this;
    for (const i in that.validateFormCopy.controls) {
      that.validateFormCopy.controls[i].markAsDirty();
      that.validateFormCopy.controls[i].updateValueAndValidity();
    }
    if (that.validateFormCopy.invalid) return;
    that.btnLoading = true;
    let data = {
      sourceHosId: this.coopId,
      destHosId: that.validateFormCopy.value.copyHosId,
    };
    that.mainService.copyHosTaskType(data).subscribe((data) => {
      that.btnLoading = false;
      that.hideAddModalCopy();
      if (data["status"] == 200) {
        that.showPromptModal("复制", true, "");
        that.initFormCopy();
      } else {
        that.showPromptModal("复制", false, data["msg"]);
      }
    });
  }
  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      hospitalType: [null],
      parentHospital: [null],
      parentDeptId: [null],
      hospitalName: [null, [Validators.required]],
      hospitalNum: [null, [Validators.required]],
    });
  }

  // 新增表单提交
  submitForm(): void {
    var that = this;
    for (const i in that.validateForm.controls) {
      that.validateForm.controls[i].markAsDirty();
      that.validateForm.controls[i].updateValueAndValidity();
    }
    if (that.validateForm.invalid) return;
    that.btnLoading = true;
    let data: any = {
      hospital: {
        hosName: that.validateForm.value.hospitalName,
        hosNo: that.validateForm.value.hospitalNum,
      },
    };
    if (this.validateForm.value.parentHospital) {
      data.hospital.parent = { id: this.validateForm.value.parentHospital };
    }
    if (this.validateForm.value.parentDeptId) {
      data.hospital.parentDeptId =  this.validateForm.value.parentDeptId;
    }
    if (this.validateForm.value.hospitalType) {
      data.hospital.type = { id: this.validateForm.value.hospitalType };
    }
    if (!that.add) {
      data.hospital["id"] = that.coopId;
    }
    that.mainService
      .coopData(that.add ? "addData" : "updData", "hospital", data)
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideAddModal();
        if (data.status == 200) {
          that.showPromptModal(that.add ? "新增" : "编辑", true, "");
          that.initForm();
        } else {
          that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
        }
      });
  }

  // 编辑
  edit(data) {
    this.add = false;
    this.modal = true;
    this.coopId = data.id;
    if (data.parent) {
      this.parentHospitals = [data.parent];
      this.validateForm.controls.parentHospital.setValue(data.parent.id);
    }
    if (data.parentDeptId && data.parentDeptDTO) {
      this.parentDepts = [data.parentDeptDTO];
      this.validateForm.controls.parentDeptId.setValue(data.parentDeptId);
    }
    if(data.type){
      this.mainService.getDictionary("list", "hospital_type").subscribe((result) => {
        this.hospitalTypes = result;
        this.validateForm.controls.hospitalType.setValue(data.type.id);
      });
    }
    this.validateForm.controls.hospitalName.setValue(data.hosName);
    this.validateForm.controls.hospitalNum.setValue(data.hosNo);
  }

  delModal: boolean = false; //删除模态框
  showDelModal(id) {
    this.delModal = true;
    this.coopId = id;
  }
  hideDelModal() {
    this.delModal = false;
  }
  confirmDel() {
    this.delModal = false;
    var that = this;
    that.btnLoading = true;
    that.mainService
      .coopData("rmvData", "hospital", [that.coopId])
      .subscribe((data) => {
        that.btnLoading = false;
        if (data.status == 200) {
          if (
            that.listOfData.length == 1 &&
            that.pageIndex == Math.ceil(that.listLength / that.pageSize)
          ) {
            that.listLength--;
            that.pageIndex = Math.ceil(that.listLength / that.pageSize) || 1;
          }
          this.showPromptModal("删除", true, "");
        } else {
          this.showPromptModal("删除", false, data.msg);
        }
      });
  }

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