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";

import host from "../../../assets/js/http";
import { HttpRequest, HttpResponse, HttpClient } from '@angular/common/http';
import { filter } from 'rxjs/operators';

@Component({
  selector: "app-building-floor",
  templateUrl: "./building-floor.component.html",
  styleUrls: ["./building-floor.component.less"],
})
export class BuildingFloorComponent implements OnInit {
  tableHeight;
  validateForm: FormGroup;
  validateFloorForm: FormGroup;
  allFloorList: any[] = []; //当前选中的楼栋包含的所有楼层
  mapOfCheckedId: { [key: string]: boolean } = {};
  checkedBuilding: any = {}; //选中楼栋
  buildingList: 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; //是否单个删除楼层
  generateModal: boolean = false; //生成楼层的模态框
  isAllDisplayDataChecked = false; //当前页是否全选
  maskFlag: any = false;

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

  @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 - 312;
  }

  // 模板导出
  excelExport(){
    this.maskFlag = this.message.loading("下载模板中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService.exportExcel("building", {}).subscribe(
      (data) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.message.success('下载模板成功');
        var file = new Blob([data], {
          type: "application/vnd.ms-excel",
        });
        //trick to download store a file having its URL
        var fileURL = URL.createObjectURL(file);
        var a = document.createElement("a");
        a.href = fileURL;
        a.target = "_blank";
        a.download = "楼栋楼层导入模板.xls";
        document.body.appendChild(a);
        a.click();
      },
      (err) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.message.error('下载模板失败');
      }
    );
  }

  // 导入---start
  // model-取消
  isShow = false;
  hideExcelImport() {
    this.isShow = false;
  }
  // 触发
  excelImport() {
    this.isShow = true;
  }
  submitExcelImport({fileList}){
    this.isShow = false;
    const formData = new FormData();
    fileList.forEach((file: any) => {
      formData.append('file', file);
    });
    this.maskFlag = this.message.loading("正在导入中..", {
      nzDuration: 0,
    }).messageId;
    const req = new HttpRequest('Post', this.mainService.returnImportExcelUrl('building'), formData, {
      reportProgress: true
    });
    this.http
      .request(req)
      .pipe(filter(e => e instanceof HttpResponse))
      .subscribe(
        (res:any) => {
          if(res.body.status == 200){
            this.message.remove(this.maskFlag);
            this.maskFlag = false;
            this.message.success('导入成功');
            this.getBuildingList();
          }else{
            this.message.remove(this.maskFlag);
            this.maskFlag = false;
            this.showPromptModal("导入", false, res.body.msg);
          }
        },
        () => {
          this.message.remove(this.maskFlag);
          this.maskFlag = false;
          this.message.error('导入失败');
        },
      );
  }
  // 导入---end

  // 楼栋列表
  getBuildingList() {
    let postData = {
      idx: 0,
      sum: 9999,
      building: { hosId: this.hosId },
    };
    this.buildingsLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "building", postData)
      .subscribe((result) => {
        this.buildingsLoading = false;
        if (result.status == 200) {
          this.buildingList = result.list;
          if (Object.keys(this.checkedBuilding).length) {
            result.list.forEach((item) => {
              if (item.id == this.checkedBuilding.id) {
                this.checkBuilding(item);
              }
            });
          } else {
            this.checkBuilding(result.list[0]);
          }
        }
      });
  }

  // 获取选中楼栋下楼层列表
  getAllFloor() {
    // 初始化的时候搜索一次，然后前端过滤
    let postData = {
      idx: 0,
      sum: 9999,
      floor: { hosId: this.hosId, buildId: this.checkedBuilding.id },
    };
    this.floorsLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "floor", postData)
      .subscribe((result) => {
        this.floorsLoading = false;
        if (result.status == 200) {
          this.allFloorList = result.list;
          this.refreshStatus();
        }
      });
  }

  // 选中楼栋
  checkBuilding(data) {
    this.positionY = this.osComponentRef1.osInstance().scroll().position.y; //内容滚动的距离
    this.checkedBuilding = data ? data : {};
    this.mapOfCheckedId = {};
    this.getAllFloor();
  }

  selectedUser(data) {
    this.mapOfCheckedId[data.id] = !this.mapOfCheckedId[data.id];
    this.refreshStatus();
  }
  // 选中列表中楼层
  refreshStatus(): void {
    let arr = [];
    if (this.allFloorList.length) {
      this.isAllDisplayDataChecked = this.allFloorList.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.checkedBuilding.id) {
      this.message.create("warning", "请选择需要编辑的楼栋！");
      return;
    }
    this.coopModal = true;
    this.add = type == "add";
    if (type == "edit") {
      this.initForm();
      this.validateForm.controls.buildingName.setValue(
        this.checkedBuilding["buildingName"]
      );
    } else {
      this.initForm();
    }
  }

  // 新增/编辑楼层模态框
  showFloorModal(e, type, data?) {
    this.floorModal = true;
    this.addFloor = type == "add";
    if (type == "edit") {
      this.initFormFloor();
      this.floorDataEdit = data;
      this.validateFloorForm.controls.buildId.setValue(data.buildId);
      this.validateFloorForm.controls.floorName.setValue(data.floorName);
    } else {
      this.initFormFloor();
    }
    e.stopPropagation();
  }

  // 隐藏楼栋模态框
  hideCoopModal() {
    this.coopModal = false;
  }

  // 隐藏楼层模态框
  hideFloorModal() {
    this.floorModal = false;
  }

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

  // 初始化新增form表单floor
  initFormFloor() {
    this.validateFloorForm = this.fb.group({
      buildId: [this.checkedBuilding.id, [Validators.required]],
      floorName: [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.buildingList.filter(
      (item) => item.buildingName == this.validateForm.value.buildingName
    );
    //有重复名称
    if (arr.length > 0) {
      this.btnLoading = false;
      this.showPromptModal(
        "新增",
        false,
        `存在重复的楼栋名称【${this.validateForm.value.buildingName}】请修改后再保存！`
      );
      return;
    }
    if (this.add) {
      postData = {
        buildingName: this.validateForm.value.buildingName,
        deleted: false,
        hosId: this.hosId,
      };
    } else {
      postData = {
        buildingName: this.validateForm.value.buildingName,
        deleted: false,
        hosId: this.hosId,
        id: this.checkedBuilding.id,
      };
    }
    this.mainService
      .simplePost("addData", "building", 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 postData;
    let arr = this.allFloorList.filter(
      (item) => item.floorName == this.validateFloorForm.value.floorName
    );
    //有重复名称
    if (arr.length > 0) {
      this.btnLoading = false;
      this.showPromptModal(
        "新增",
        false,
        `同一个楼栋存在重复的楼层名称【${this.validateFloorForm.value.floorName}】请修改后再保存！`
      );
      return;
    }
    if (this.addFloor) {
      postData = {
        buildId: this.validateFloorForm.value.buildId,
        floorName: this.validateFloorForm.value.floorName,
        deleted: false,
        hosId: this.hosId,
      };
    } else {
      postData = {
        buildId: this.validateFloorForm.value.buildId,
        floorName: this.validateFloorForm.value.floorName,
        deleted: false,
        hosId: this.hosId,
        id: this.floorDataEdit.id,
      };
    }
    this.addFloorHandler(postData, false);
  }

  //新增楼层
  addFloorHandler(postData, flag) {
    this.mainService
      .simplePost(flag ? "addListData" : "addData", "floor", postData)
      .subscribe((result) => {
        this.hideFloorModal();
        this.generate1 && (this.generate1.delModal = false);
        this.hideGenerateModal();
        this.btnLoading = false;
        if (result["status"] == 200) {
          this.showPromptModal(this.addFloor ? "新增" : "编辑", true, "");
        } else {
          this.showPromptModal(
            this.addFloor ? "新增" : "编辑",
            false,
            result["msg"]
          );
        }
      });
  }

  //删除楼栋
  showDelModal() {
    if (!this.checkedBuilding.id) {
      this.message.create("warning", "请选择需要删除的楼栋！");
      return;
    }
    this.delModal = true;
  }
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    let postData = [this.checkedBuilding["id"]];
    this.mainService.delBuildingList(postData).subscribe((result) => {
      this.hideDelModal();
      this.btnLoading = false;
      if (result["status"] == 200 && !result["data"][0].msg) {
        this.showPromptModal("删除", true, "");
        this.checkedBuilding = {};
      } else {
        this.showPromptModal("删除", false, result["data"][0].msg);
      }
    });
  }
  /**
   * 删除楼层
   * @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;
  }
  // 确认删除
  confirmFloorDel() {
    this.btnLoading = true;
    let selectedFloor = this.selectedFloor.map((item) => item.id);
    let postData = this.isDelSingle ? [this.floorDataEdit.id] : selectedFloor;
    this.mainService.delFloorList(postData).subscribe((result) => {
      this.hideDelFloorModal();
      this.btnLoading = false;
      if (result["status"] == 200 && !result["data"][0].msg) {
        this.showPromptModal("删除", true, "");
      } else {
        this.showPromptModal("删除", false, result["data"][0].msg);
      }
    });
  }
  // 全选
  checkAll(value: boolean): void {
    console.log(this.allFloorList);
    this.allFloorList.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);
    }
  }
  // 生成楼层
  generate() {
    this.generateModal = true;
  }
  // 隐藏楼层模态框
  hideGenerateModal() {
    this.generateModal = false;
  }
  // 确认生成
  confirmGenerate(e) {
    console.log(e);
    let arr = []; //生成的楼层
    for (let i = e[1]; i <= e[2]; i++) {
      arr.push({
        buildId: e[0].id,
        floorName: i + "",
        deleted: false,
        hosId: this.hosId,
      });
    }
    // 去重
    this.allFloorList.forEach((item1) => {
      arr = arr.filter(
        (item2) =>
          !(
            item1.buildId == item2.buildId && item1.floorName == item2.floorName
          )
      );
    });
    this.btnLoading = true;
    this.addFloorHandler(arr, true);
  }
}
