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

  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopData: any; //当前操作列
  currentHospital; //当前院区

  btnLoading: boolean = false; //提交按钮loading状态

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  nextSchemeName = ""; //下一个开启的方案名称
  modelName = ""; //模态框名称

  changeInpSubject = new Subject(); //防抖
  showDropdown:boolean = false;

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[1] === 'department'){
        this.getDeparts(v[0], v[2]);
      } else if(v[1] === 'building'){
        this.getBuildings(v[0], v[2]);
      } else if(v[1] === 'floor'){
        this.getFloors(v[0], v[2], this.validateForm.value.buildId);
      }
    });
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getList(1);
    this.getDeparts('search', '');
    this.getDeparts('add', '');
    this.getTags('add', '');
    this.getBuildings('add', '');
    this.getBuildings('search', '');
    this.getDispatchMethods();
  }

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

  // 批量关联科室
  inspectionAddressDepartmentPromptModalShow = false; //标本历史记录弹窗开关
  showInspectionAddressDepartment() {
    this.inspectionAddressDepartmentPromptModalShow = true;
  }
  // 关闭弹窗
  closeModelInspectionAddressDepartment(e) {
    this.inspectionAddressDepartmentPromptModalShow = JSON.parse(e).show;
  }
  // 确认弹窗
  checkedDepIdsModel = [];
  confirmModelInspectionAddressDepartment(checkedDepIds) {
    this.inspectionAddressDepartmentPromptModalShow = true;
    this.checkedDepIdsModel = checkedDepIds;
    console.log(checkedDepIds)
    this.showInspectionAddressTag();
  }

  // 批量关联科室-标签
  inspectionAddressTagPromptModalShow = false; //标本历史记录弹窗开关
  showInspectionAddressTag() {
    this.inspectionAddressTagPromptModalShow = true;
  }
  // 关闭弹窗
  closeModelInspectionAddressTag(e) {
    this.inspectionAddressTagPromptModalShow = JSON.parse(e).show;
  }
  // 确认弹窗
  maskFlag: any = false;
  confirmModelInspectionAddressTag(tags) {
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.inspectionAddressTagPromptModalShow = true;
    console.log(this.checkedDepIdsModel, tags);
    let postData:any = {
      deptIds: this.checkedDepIdsModel.toString(),
      hosId: this.currentHospital.id,
      tagIds: tags.toString(),
    };
    console.log(postData);
    this.btnLoading = true;
    this.mainService
      .inspectionPost("batchBindFormNode", postData)
      .subscribe((result) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.btnLoading = false;
        if (result.status == 200) {
          this.inspectionAddressDepartmentPromptModalShow = false;
          this.inspectionAddressTagPromptModalShow = false;
          this.showPromptModal('操作', true, '');
        } else if (result.status == 501) {
          this.inspectionAddressDepartmentPromptModalShow = false;
          this.inspectionAddressTagPromptModalShow = false;
          this.showPromptModal('操作', true, result.msg);
        } else {
          this.showPromptModal('操作', false, result.msg);
        }
      });
  }

  // 打印
  codes = []; //二维码
  printLoading: boolean = false; //批量打印按钮loading状态
  print(e, batch, id?) {
    e.stopPropagation();
    this.printLoading = true;
    this.mainService
      .inspectionPost("getNodeQrCode", batch ? { nodeIds: this.checkedDepIds.toString() } : [id])
      .subscribe((data) => {
				if(data.status==200){
					this.codes = data.data;
					this.printLoading = false;
					setTimeout(() => {
					  const printContent = document.getElementById("report");
					  const WindowPrt = window.open("", "", "width=700,height=900");
					  WindowPrt.document.write(printContent.innerHTML);
					  WindowPrt.document.close();
					  WindowPrt.focus();
					  WindowPrt.print();
					  WindowPrt.close();
					}, 100);
				}else{
					this.showPromptModal('打印', false, data.msg)
				}
      });
  }

  // 选中表格单列
  mapOfCheckedId: { [key: string]: boolean } = {};
  checkedDepIds = []; //已选中单列id
  refreshStatus(): void {
    let listOfData = this.listOfData;
    this.isAllDisplayDataChecked = listOfData.every(
      (item) => this.mapOfCheckedId[item.id]
    );
    let arr = [];
    for (var k in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[k]) {
        arr.push(Number(k));
      }
    }
    this.checkedDepIds = arr;
  }
  // 整行操作
  selectedListData(data) {
    this.mapOfCheckedId[data.id] = !this.mapOfCheckedId[data.id];
    this.refreshStatus();
  }
  // 全选
  isAllDisplayDataChecked = false; //当前页是否全选
  checkAll(value: boolean): void {
    this.listOfData.forEach((item) => {
      this.mapOfCheckedId[item.id] = value;
    });
    this.refreshStatus();
  }

  // 搜索
  search() {
    this.getList(1);
  }
  // 重置
  reset() {
    this.searchDto = {};
    this.getList(1);
  }

  // 表格数据
  searchDto: any = {};
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      inspectionNode: {
        hosId: this.currentHospital.id,
        ...this.searchDto,
      },
    };
    this.mapOfCheckedId = {};
    this.checkedDepIds = [];
    this.isAllDisplayDataChecked = false;
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "inspectionNode", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 新增弹框
  addModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modal = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }

  // 初始化新增form表单
  initForm() {
    this.floorList = [];
    this.validateForm = this.fb.group({
      name: ['', [Validators.required, Validators.pattern(/\S/)]],
      // deptId: [null, [Validators.required]],
      deptId: [null],
      buildId: [null, [Validators.required]],
      floorId: [null, [Validators.required]],
      address: ['', [Validators.required]],
      tagIds: [[], [Validators.required]],
      signType: [null, [Validators.required]],
    });
  }

  // 边输边搜节流阀
  isLoading = false;
  changeInp(type, model, e) {
    this.isLoading = true;
    this.changeInpSubject.next([type, model, e]);
  }

  // 获取所有科室
  departmentAddList: any = []; //所有所属科室
  departmentSearchList: any = []; //所有所属科室(搜索)
  getDeparts(type, keyword, init = false) {
    let postData:any = {
      department: {
        // searchType: 1,// 简单查询
        dept: keyword,
        cascadeHosId: this.currentHospital.id,
      },
      idx: 0,
      sum: 20,
    };
    if(type === 'add'){
      postData.department.bussType = 'inspection';
    }
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((data) => {
        if (type == "search") {
          this.departmentSearchList = data.list;
        } else if (type == "add") {
          this.departmentAddList = data.list;
        }

        this.isLoading = false;

        if(init && this.coopData && this.coopData.departmentDTO){
          let deptId = this.coopData.departmentDTO.id;
          let flag = this.departmentAddList.some(v => v.id == deptId);
          if(!flag){
            this.departmentAddList.unshift(this.coopData.departmentDTO)
          }
          this.validateForm.controls.deptId.setValue(this.coopData.departmentDTO.id);
        }
      });
  }

  // 获取标签
  tagList: any = [];
  tagListCopy: any = [];
  getTags(type, keyword) {
    let postData = {
      tag: {
        hosId: this.currentHospital.id,
        modelType: { value: 'inspection' },
      },
      idx: 0,
      sum: 50,
    };
    this.mainService
      .getFetchDataList("simple/data", "tag", postData)
      .subscribe((data) => {
        this.tagList = data.list;
        this.tagListCopy = JSON.parse(JSON.stringify(this.tagList));
        this.isLoading = false;
      });
  }

  // 获取楼栋
  buildingAddList: any = [];
  buildingSearchList: any = [];
  getBuildings(type, keyword, init = false) {
    let postData = {
      building: {
        simpleQuery: true,
        buildingName: keyword,
        cascadeHosId: this.currentHospital.id,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("simple/data", "building", postData)
      .subscribe((data) => {
        if (type == "search") {
          this.buildingSearchList = data.list;
        } else if (type == "add") {
          this.buildingAddList = data.list;
        }
        this.isLoading = false;

        if(init && this.coopData && this.coopData.buildingDTO){
          let buildId = this.coopData.buildingDTO.id;
          let flag = this.buildingAddList.some(v => v.id == buildId);
          if(!flag){
            this.buildingAddList.unshift(this.coopData.buildingDTO)
          }
          this.validateForm.controls.buildId.setValue(this.coopData.buildingDTO.id);
        } else if (this.deptDto && this.deptDto.building){
          let buildId = this.deptDto.building.id;
          let flag = this.buildingAddList.some(v => v.id == buildId);
          if(!flag){
            this.buildingAddList.unshift(this.deptDto.building)
          }
          this.validateForm.controls.buildId.setValue(this.deptDto.building.id);
        }
      });
  }

  // 修改关联科室
  deptDto:any = null;
  changeDepartment(deptId){
    if(this.add){
      console.log(deptId)
      this.deptDto = this.departmentAddList.find(v => v.id == deptId);
      console.log(this.deptDto);
      if(this.deptDto && this.deptDto.dept && !this.validateForm.value.name){
        this.validateForm.controls.name.setValue(this.deptDto.dept);
      }

      if(this.deptDto && this.deptDto.building){
        this.getBuildings('add', '');
      }

      if(this.deptDto && this.deptDto.floor){
        this.noChangeBuilding = true;
        this.getFloors('add', '', this.deptDto.building.id, false, true);
      }
    }
  }

  // 修改楼栋
  noChangeBuilding:boolean = false;
  changeBuilding(buildId?){
    console.log(buildId)
    if(!this.noChangeBuilding){
      this.validateForm.controls.floorId.setValue(null);
      this.getFloors('add', '', this.validateForm.value.buildId);
    }
    this.noChangeBuilding = false;
  }

  // 获取楼层
  floorList: any = [];
  getFloors(type, keyword, buildId, init = false, isNoChangeBuilding = false) {
    console.log(isNoChangeBuilding)
    if(!buildId){
      this.floorList = [];
      return;
    }
    let postData = {
      floor: {
        floorName: keyword,
        buildId,
        // hosId: this.currentHospital.id,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("simple/data", "floor", postData)
      .subscribe((data) => {
        this.floorList = data.list;
        this.isLoading = false;

        if(init && this.coopData && this.coopData.floorDTO){
          let floorId = this.coopData.floorDTO.id;
          let flag = this.floorList.some(v => v.id == floorId);
          if(!flag){
            this.floorList.unshift(this.coopData.floorDTO)
          }
          this.validateForm.controls.floorId.setValue(this.coopData.floorDTO.id);
        } else if (isNoChangeBuilding && this.deptDto && this.deptDto.floor){
          let floorId = this.deptDto.floor.id;
          let flag = this.floorList.some(v => v.id == floorId);
          if(!flag){
            this.floorList.unshift(this.deptDto.floor)
          }
          this.validateForm.controls.floorId.setValue(this.deptDto.floor.id);
        }
      });
  }

  // 选择标签
  changeTags(tags){
    if(tags.length){
      let flag = tags.every(v => {
        return this.tagListCopy.map(vv => vv.name).includes(v);
      })

      if(flag){
        return;
      }

      let tagName = tags[tags.length - 1];
      let postData = {
        tag: {
          name: tagName,
          hosId: this.currentHospital.id,
          modelType: { value: 'inspection' },
        }
      }
      this.isLoading = true;
      this.mainService
      .coopData("addData", "tag", postData)
      .subscribe((result) => {
        this.isLoading = false;
        console.log(result);
        if(result.status == 200){
          this.tagListCopy.unshift(result.data)
          console.log(this.tagListCopy);
        } else if (result.status == 10001){
          // 名称重复
          this.tagListCopy.unshift(result.data)
          console.log(this.tagListCopy);
        } else {
          tags.pop();
          this.message.warning(result.msg || '请求数据失败')
        }
      });
    }
  }

  //获取填写方式
  dispatchMethods:any[] = [];
  getDispatchMethods() {
    this.isLoading = true;
    this.mainService.getDictionary("list", "inspection_node_sign_type").subscribe((data) => {
      this.isLoading = false;
      this.dispatchMethods = data || [];
    });
  }

  // 新增/编辑表单提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }

    console.log(this.validateForm.value)
    console.log(this.tagListCopy);

    this.btnLoading = true;
    let postData:any = {};

    let tagNames = this.validateForm.value.tagIds;
    let tags = this.tagListCopy;
    let tagIds = tagNames.map(name =>{
      return tags.find(v => v.name === name).id;
    })

    if (this.add) {
      //增加
      postData = {
        inspectionNode: {
          name: this.validateForm.value.name,
          deptId: this.validateForm.value.deptId || undefined,
          buildId: this.validateForm.value.buildId,
          floorId: this.validateForm.value.floorId,
          address: this.validateForm.value.address,
          tagIds: tagIds.toString(),
          signType: this.dispatchMethods.find(v => v.value === this.validateForm.value.signType),
          hosId: this.currentHospital.id,
        }
      };
    } else {
      //编辑
      postData = {
        inspectionNode:{
          ...this.coopData,
          ...{
            name: this.validateForm.value.name,
            deptId: this.validateForm.value.deptId || undefined,
            buildId: this.validateForm.value.buildId,
            floorId: this.validateForm.value.floorId,
            address: this.validateForm.value.address,
            tagIds: tagIds.toString(),
            signType: this.dispatchMethods.find(v => v.value === this.validateForm.value.signType),
          }
        }
      };
    }
    this.mainService
      .coopData("addData", "inspectionNode", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideAddModal();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          this.showPromptModal(msg, true, "");
        } else if (result.status == 10001) {
          this.showPromptModal(msg, false, "关联科室重复");
        } else {
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 编辑
  edit(e, data) {
    e.stopPropagation();
    console.log(data);
    this.initForm();
    this.modelName = "编辑";
    this.add = false;
    this.modal = true;
    this.coopData = data;
    this.validateForm.controls.name.setValue(data.name); //名称
    this.validateForm.controls.deptId.setValue(data.deptId);
    this.validateForm.controls.tagIds.setValue(data.tagIdsList.map(v => v.name));
    this.validateForm.controls.signType.setValue(data.signType.value);
    this.validateForm.controls.address.setValue(data.address);

    if(data.deptId){
      this.getDeparts('add', '', true);
    }

    if(data.buildId){
      this.getBuildings('add', '', true);
    }

    if(data.floorId){
      this.noChangeBuilding = true;
      this.getFloors('add', '', data.buildId, true, 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);
    this.getTags('add', '');
  }

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  showDelModal(
    e,
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    e.stopPropagation();
    this.confirmDelType = type;
    this.delModal = true;
    this.coopData = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      this.mainService
        .simplePost("rmvData", "inspectionNode", [this.coopData.id])
        .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);
          }
        });
    } else if (this.confirmDelType === "delList") {
      //批量删除
      this.mainService
        .simplePost("rmvData", "inspectionNode", this.checkedDepIds)
        .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);
          }
        });
    } else if (this.confirmDelType === "resetList") {
      //批量重置
      let postData = {
        nodeIds: this.checkedDepIds.toString(),
      }
      this.mainService
        .inspectionPost("batchResetNodeCode", postData)
        .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);
          }
        });
    }
  }
}
