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

import { MainService } from "../../services/main.service";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { GenerateFloorComponent } from "src/app/share/generate-floor/generate-floor.component";
import { NzMessageService } from "ng-zorro-antd";

@Component({
  selector: "app-inspect-type-config",
  templateUrl: "./inspect-type-config.component.html",
  styleUrls: ["./inspect-type-config.component.less"],
})
export class InspectTypeConfigComponent implements OnInit {
  tableHeight;
  validateForm: FormGroup;
  validateFloorForm: FormGroup;
  allKeyword: any[] = []; //当前选中的检查类型包含的所有关键字
  mapOfCheckedId: { [key: string]: boolean } = {};
  checkedInspectType: any = {}; //选中检查类型
  inspectTypeList: Array<any> = []; //检查类型信息
  hosId: any; //当前选择的院区id
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //是否展示提示框
  btnLoading: boolean = false; //确认按钮loading状态
  coopBtns: any = {}; // 初始化增删改按钮
  buildingsLoading = false; //获取检查类型列表的loading
  floorsLoading = false; //获取关键字列表的loading
  positionY = 0; //记录Y轴滚动距离
  selectedFloor = []; //选中的关键字
  coopModal: boolean = false; //检查类型模态框是否展示
  add: boolean = true; //检查类型新增的标识，true：新增；false：编辑
  floorModal: boolean = false; //关键字模态框是否展示
  addFloor: boolean = true; //关键字，true：新增；false：编辑
  floorDataEdit; //正在编辑的关键字
  delModal: boolean = false; //删除检查类型，模态框是否显示
  delFloorModal: boolean = false; //删除关键字，模态框是否显示
  isDelSingle: boolean = false; //是否单个删除关键字
  isAllDisplayDataChecked = false; //当前页是否全选

  constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private mainService: MainService,
    private msg: NzMessageService,
    private tool: ToolService
  ) {}

  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild(GenerateFloorComponent, { static: false })
  generate1: GenerateFloorComponent;

  ngOnInit() {
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.hosId = this.tool.getCurrentHospital().id;
    this.getBuildingList();
    this.tableHeight = document.body.clientHeight - 267;
  }
  // 检查类型列表
  getBuildingList() {
    this.buildingsLoading = true;
    let postData = {
      idx: 0,
      sum: 9999,
      dictionary: {
        key: "inspect_check_type",
      },
    };
    this.mainService
      .getFetchDataList("simple/data", "dictionary", postData)
      .subscribe((result) => {
        this.buildingsLoading = false;
        if (result.status == 200) {
          this.inspectTypeList = result.list;
          this.inspectTypeList.forEach((item) => {
            if (!item.extra2) {
              item.extra2 = "";
            }
          });
          if (Object.keys(this.checkedInspectType).length) {
            result.list.forEach((item) => {
              if (item.id == this.checkedInspectType.id) {
                this.checkBuilding(item);
              }
            });
          } else {
            this.checkBuilding(result.list[0]);
          }
        }
      });
  }

  // 获取选中检查类型下关键字列表
  id: number = 0;
  getAllFloor() {
    console.log(this.checkedInspectType, "baba");
    if (this.checkedInspectType.extra2) {
      this.allKeyword = this.checkedInspectType.extra2
        .split(",")
        .map((item) => ({ id: ++this.id, keyword: item }));
    } else {
      this.allKeyword = [];
    }
    this.refreshStatus();
  }

  // 选中检查类型
  checkBuilding(data) {
    this.positionY = this.osComponentRef1.osInstance().scroll().position.y; //内容滚动的距离
    this.checkedInspectType = data ? data : {};
    this.mapOfCheckedId = {};
    this.getAllFloor();
  }

  selectedUser(data) {
    this.mapOfCheckedId[data.id] = !this.mapOfCheckedId[data.id];
    this.refreshStatus();
  }
  // 选中列表中关键字
  refreshStatus(): void {
    let arr = [];
    if (this.allKeyword.length) {
      this.isAllDisplayDataChecked = this.allKeyword.every(
        (item) => this.mapOfCheckedId[item.id]
      );
    } else {
      this.isAllDisplayDataChecked = false;
    }

    for (var m in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[m]) {
        arr.push({ id: m });
      }
    }
    this.selectedFloor = arr;
  }

  // 新增/编辑检查类型模态框
  showCoopModal(type) {
    if (type == "edit" && !this.checkedInspectType.id) {
      this.msg.create("warning", "请选择需要编辑的检查类型！");
      return;
    }
    this.coopModal = true;
    this.add = type == "add";
    if (type == "edit") {
      this.initForm();
      this.validateForm.controls.inspectTypeName.setValue(
        this.checkedInspectType.name
      );
    } else {
      this.initForm();
    }
  }

  // 新增/编辑关键字模态框
  showFloorModal(e, type, data?) {
    this.floorModal = true;
    this.addFloor = type == "add";
    this.floorDataEdit = data;
    if (type == "edit") {
      this.initFormFloor();
      this.validateFloorForm.controls.inspectTypeName.setValue(
        this.checkedInspectType.name
      );
      this.validateFloorForm.controls.keyword.setValue(data.keyword);
    } else {
      this.initFormFloor();
    }
    e.stopPropagation();
  }

  // 隐藏检查类型模态框
  hideCoopModal() {
    this.coopModal = false;
  }

  // 隐藏关键字模态框
  hideFloorModal() {
    this.floorModal = false;
  }

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      inspectTypeName: [null, [Validators.required]],
    });
  }

  // 初始化新增form表单floor
  initFormFloor() {
    this.validateFloorForm = this.fb.group({
      inspectTypeName: [this.checkedInspectType.name, [Validators.required]],
      keyword: [null, [Validators.required]],
    });
  }

  // 新增/编辑检查类型提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.btnLoading = true;
    let postData;
    let arr = this.inspectTypeList.filter(
      (item) => item.name == this.validateForm.value.inspectTypeName
    );
    //有重复名称
    if (arr.length > 0) {
      this.btnLoading = false;
      this.showPromptModal(
        "新增",
        false,
        `存在重复的检查类型名称【${this.validateForm.value.inspectTypeName}】请修改后再保存！`
      );
      return;
    }
    if (this.add) {
      let n = 0;
      if (this.inspectTypeList.length > 0) {
        let sortArr = this.inspectTypeList.map((item) => Number(item.value));
        n = Math.max.apply(null, sortArr);
      } else {
        n = 0;
      }
      postData = {
        key: "inspect_check_type",
        name: this.validateForm.value.inspectTypeName,
        value: n + 1,
        orders: n + 1,
        desc: "检查类型",
      };
    } else {
      postData = {
        extra2: this.checkedInspectType.extra2,
        name: this.validateForm.value.inspectTypeName,
        id: this.checkedInspectType.id,
      };
    }
    this.mainService.upDictionary(postData).subscribe((result) => {
      this.hideCoopModal();
      this.btnLoading = false;
      if (result["status"] == 200) {
        this.showPromptModal(this.add ? "新增" : "编辑", true, "");
      } else {
        this.showPromptModal(this.add ? "新增" : "编辑", false, result["msg"]);
      }
    });
  }

  // 新增/编辑关键字提交
  submitFormFloor(): void {
    for (const i in this.validateFloorForm.controls) {
      this.validateFloorForm.controls[i].markAsDirty();
      this.validateFloorForm.controls[i].updateValueAndValidity();
    }
    if (this.validateFloorForm.invalid) return;
    this.btnLoading = true;
    let arr = this.allKeyword.filter(
      (item) => item.keyword == this.validateFloorForm.value.keyword
    );
    //有重复名称
    if (arr.length > 0) {
      this.btnLoading = false;
      this.showPromptModal(
        "新增",
        false,
        `同一个检查类型存在重复的关键字名称【${this.validateFloorForm.value.keyword}】请修改后再保存！`
      );
      return;
    }
    if (this.addFloor) {
      this.allKeyword.push({
        keyword: this.validateFloorForm.value.keyword,
        id: ++this.id,
      });
    } else {
      this.allKeyword.forEach((item) => {
        if (item.id === this.floorDataEdit.id) {
          item.keyword = this.validateFloorForm.value.keyword;
        }
      });
    }
    this.addFloorHandler();
  }

  //新增关键字baba
  addFloorHandler() {
    let postData = {
      id: this.checkedInspectType.id,
      extra2: this.allKeyword.map((item) => item.keyword).toString(),
    };
    this.mainService.upDictionary(postData).subscribe((result) => {
      this.hideFloorModal();
      this.generate1 && (this.generate1.delModal = false);
      this.btnLoading = false;
      if (result["status"] == 200) {
        this.showPromptModal(this.addFloor ? "新增" : "编辑", true, "");
      } else {
        this.showPromptModal(
          this.addFloor ? "新增" : "编辑",
          false,
          result["msg"]
        );
      }
    });
  }

  //删除检查类型
  showDelModal() {
    if (!this.checkedInspectType.id) {
      this.msg.create("warning", "请选择需要删除的检查类型！");
      return;
    }
    this.delModal = true;
  }
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除baba
  confirmDel() {
    this.btnLoading = true;
    let postData = {
      deleted: true,
      id: this.checkedInspectType.id,
    };
    this.mainService.upDictionary(postData).subscribe((result) => {
      this.hideDelModal();
      this.btnLoading = false;
      if (result["status"] == 200) {
        this.showPromptModal("删除", true, "");
        this.checkedInspectType = {};
      } else {
        this.showPromptModal("删除", false, "");
      }
    });
  }
  /**
   * 删除关键字
   * @param e 事件对象
   * @param data 有值就是单个删除，无值就是批量删除
   */
  showDelFloorModal(e, data?) {
    if (data) {
      this.isDelSingle = true;
      this.floorDataEdit = data;
    } else {
      this.isDelSingle = false;
    }
    this.delFloorModal = true;
    e.stopPropagation();
  }
  hideDelFloorModal() {
    this.delFloorModal = false;
  }
  // 确认删除baba
  confirmFloorDel() {
    let allKeyword = JSON.parse(JSON.stringify(this.allKeyword));
    this.btnLoading = true;
    let selectedFloor = this.selectedFloor.map((item) => item.id);
    if (this.isDelSingle) {
      allKeyword = allKeyword.filter(
        (item) => item.id != this.floorDataEdit.id
      );
    } else {
      allKeyword = allKeyword.filter(
        (item) => !selectedFloor.includes(item.id + "")
      );
    }
    let postData = {
      id: this.checkedInspectType.id,
      extra2: allKeyword.map((v) => v.keyword).toString(),
    };
    this.mainService.upDictionary(postData).subscribe((result) => {
      this.hideDelFloorModal();
      this.btnLoading = false;
      if (result["status"] == 200) {
        this.allKeyword = allKeyword;
        this.showPromptModal("删除", true, "");
      } else {
        this.showPromptModal("删除", false, "");
      }
    });
  }
  // 全选
  checkAll(value: boolean): void {
    console.log(this.allKeyword);
    this.allKeyword.forEach((item) => {
      this.mapOfCheckedId[item.id] = value;
    });
    this.refreshStatus();
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    this.osComponentRef1.osInstance().scroll({ x: 0, y: this.positionY });
    if (success) {
      setTimeout(() => {
        this.promptModalShow = true;
        this.getBuildingList();
      }, 100);
    } else {
      setTimeout(() => {
        this.promptModalShow = true;
      }, 100);
    }
  }
}
