import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute, ParamMap } from "@angular/router";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { GenerateFloorComponent } from "../../share/generate-floor/generate-floor.component";
import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";

@Component({
  selector: "app-data-floor",
  templateUrl: "./data-floor.component.html",
  styleUrls: ["./data-floor.component.less"],
})
export class DataFloorComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  @ViewChild(GenerateFloorComponent, { static: false })
  generate1: GenerateFloorComponent;
  osComponentRef1: OverlayScrollbarsComponent;
  loading1 = false; //获取楼栋,楼层信息列表加载状态
  loading3 = false; //保存
  hosId: any; //院区id
  id: number = 0; //自定义id，负整数
  buildingList: Array<any> = []; //楼栋信息列表
  floorList: Array<any> = []; //楼层信息列表
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  coop: any; //当前操作列
  loading2 = false; //删除接口
  mainWidth = "100%";
  coopBtns = {};
  constructor(
    private mainService: MainService,
    private route: ActivatedRoute,
    private tool: ToolService
  ) {}
  ngOnInit() {
    this.route.queryParamMap.subscribe((params: ParamMap) => {
      this.hosId = params.get("id");
      if (!this.hosId) {
        this.hosId = this.tool.getCurrentHospital().id;
      }
      this.getBuildingList();
    });
    this.coopBtns = this.tool.initCoopBtns("dataDictionary");
    this.changeSize();
    window.addEventListener("resize", () => {
      this.changeSize();
    });
  }
  // 选择楼栋(获取楼栋名称)
  selectBuild(data) {
    this.buildingList.forEach((item) => {
      if (item.id == data.buildId) {
        data.building.buildingName = item.buildingName;
      }
    });
  }
  // 改变窗口大小
  changeSize() {
    let w = window.innerWidth - 582; //屏幕宽-其他元素宽度
    this.mainWidth = Math.floor(w / 370) * 370 + "px";
  }
  // 新增
  add() {
    this.floorList.push({
      id: --this.id,
      buildId: null,
      building: { buildingName: "" },
      floorName: "",
    });
  }
  // 删除
  delete(data) {
    this.showDelModal(data, "您确认要删除此楼层吗？");
  }
  // 删除快捷建单
  showDelModal(data: any, tipsMsg1: string) {
    this.delModal = true;
    this.coop = data;
    this.tipsMsg1 = tipsMsg1;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.loading2 = true;
    if (this.coop.id > 0) {
      //接口删除
      let postData = [this.coop.id];
      this.mainService.delFloorList(postData).subscribe(
        (result) => {
          this.loading2 = false;
          this.delModal = false;
          if (result["status"] == 200 && !result["data"][0].msg) {
            this.showPromptModal("删除", true, "", false);
            // 过滤掉当前这一条
            this.floorList = this.floorList.filter(
              (item) => item.id !== this.coop.id
            );
          } else {
            this.showPromptModal("删除", false, result["data"][0].msg, false);
          }
        },
        (err) => {
          this.loading2 = false;
          this.delModal = false;
          this.showPromptModal("删除", false, "", false);
        }
      );
    } else {
      this.loading2 = false;
      this.delModal = false;
      this.showPromptModal("删除", true, "", false);
      // 过滤掉当前这一条
      this.floorList = this.floorList.filter(
        (item) => item.id !== this.coop.id
      );
    }
  }
  // 生成楼层baba
  generateModal: boolean = false;
  generate() {
    this.generateModal = true;
  }
  // 隐藏楼层模态框
  hideGenerateModal() {
    this.generateModal = false;
  }
  // 确认生成baba
  loading4: boolean = false;
  confirmGenerate(e) {
    let arr = []; //生成的楼层
    for (let i = e[1]; i <= e[2]; i++) {
      arr.push({
        id: --this.id,
        buildId: e[0].id,
        building: { buildingName: e[0].buildingName },
        floorName: i + "",
      });
    }
    // 去重
    this.floorList.forEach((item1) => {
      arr = arr.filter(
        (item2) =>
          !(
            item1.buildId == item2.buildId && item1.floorName == item2.floorName
          )
      );
    });
    this.floorList = [...this.floorList, ...arr];
    console.log(this.floorList, "seimin");
    this.save("生成楼层", "loading4");
  }
  // 保存
  /**
   *
   * @param type string 保存还是生成楼层,取值'保存','生成楼层'
   * @param loadingName string 保存还是生成楼层,取值'loading3','loading4'
   */
  save(type, loadingName) {
    let arr = []; //排查是否有重复的名称的容器
    let arrStr = ""; //重复名称
    console.log(this.floorList, "seimin");
    // 过滤空值
    this.floorList = this.floorList.filter((item) => {
      return (
        item.buildId !== null &&
        item.floorName !== "" &&
        item.building &&
        item.building.buildingName !== ""
      );
    });
    // 数据处理
    let postData = JSON.parse(JSON.stringify(this.floorList));
    postData.forEach((item) => {
      arr.push([item.building.buildingName, item.floorName]);
      item.hosId = this.hosId;
      item.deleted = false;
      delete item.building;
      if (item.id < 0) {
        delete item.id;
      }
    });
    if (arr.length > 1) {
      arr.sort((a, b) => a[1] - b[1]);
      for (let i = 0; i < arr.length - 1; i++) {
        if (arr[i][1] === arr[i + 1][1] && arr[i][0] === arr[i + 1][0]) {
          arrStr += `【${arr[i][0]}-${arr[i][1]}】,`;
        }
      }
    }
    if (arrStr) {
      //有重复名称
      arrStr = [...new Set(arrStr.split(","))].join(); //去重
      this.showPromptModal(
        type,
        false,
        `同一个楼栋存在重复的楼层名称${arrStr}请修改后再保存！`,
        false
      );
    } else {
      this[loadingName] = true;
      this.mainService.saveFloorList(postData).subscribe(
        (result) => {
          this[loadingName] = false;
          if (result["status"] == 200) {
            this.showPromptModal(type, true, "");
            this.hideGenerateModal(); //隐藏
            this.generate1.delModal = false;
          } else {
            this.showPromptModal(type, false, result["msg"]);
          }
        },
        (err) => {
          this[loadingName] = false;
          this.showPromptModal(type, false, "");
        }
      );
    }
  }
  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo, isRefresh = true) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
    if (isRefresh) {
      this.getFloorList();
    }
  }
  // 获取楼层信息列表
  getFloorList() {
    this.mainService
      .getFetchDataList("simple/data", "floor", {
        idx: 0,
        sum: 9999,
        floor: { hosId: this.hosId },
      })
      .subscribe((result) => {
        this.loading1 = false;
        if (result["status"] == 200) {
          if (
            result["list"] &&
            Array.isArray(result["list"]) &&
            result["list"].length < 6
          ) {
            let arr = result["list"];
            let len = 6 - arr.length;
            for (let i = 0; i < len; i++) {
              arr.push({
                id: --this.id,
                buildId: null,
                building: { buildingName: "" },
                floorName: "",
              });
            }
            this.floorList = arr;
          } else if (
            result["list"] &&
            Array.isArray(result["list"]) &&
            result["list"].length >= 6
          ) {
            this.floorList = result["list"];
          } else {
            let arr = [];
            for (let i = 0; i < 6; i++) {
              arr.push({
                id: --this.id,
                buildId: null,
                building: { buildingName: "" },
                floorName: "",
              });
            }
            this.floorList = arr;
          }
        }
      });
  }
  // 获取楼栋信息列表
  getBuildingList() {
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "building", {
        idx: 0,
        sum: 9999,
        building: { hosId: this.hosId },
      })
      .subscribe((result) => {
        if (result["status"] == 200) {
          this.buildingList = result["list"];
          this.getFloorList();
        }
      });
  }
}
