import { ChangeDetectorRef, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { NzFormatEmitEvent, NzTreeComponent, NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { FacilityInfoInSceneWindow } from 'src/app/babylon/view/facilityinfoinscene-window/facilityinfoinscene-window';
import { PlanComponent } from '../plan/plan.component';
import { FacilityInfoUIItem } from "../../babylon/view/facilityinfoinscene-window/facilityinfo-ui-item";
import { ConfigManager } from 'src/app/babylon/controller/config-manager';
import { FacilityType } from 'src/app/babylon/model/data/model-data/model-data-facility';
import { EventManager } from 'src/app/babylon/controller/event-manager/event-manager';
import { Event_GetAllMarkPlanData } from 'src/app/babylon/controller/event-manager/events/event-get-markplandata-success';
import { AllMarkPlanData, MarkNodeData, MarkPlanData } from 'src/app/babylon/model/data/mark/mark-plan-data';
import { MarkWindow } from 'src/app/babylon/view/mark-window/mark-window';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ModeManager, ModeType } from 'src/app/babylon/controller/mode-manager';
import { DataManager } from 'src/app/babylon/controller/data-manager';
import { ServeManager } from 'src/app/babylon/controller/serve-manager';
import { ObjectsService } from 'src/app/service/objects.service';
import Viewer from 'viewerjs';
import { HttpClient } from '@angular/common/http';
import { MarkTemplate } from 'src/app/babylon/model/data/mark/mark-template-data';

@Component({
  selector: 'app-left-domain',
  templateUrl: './left-domain.component.html',
  styleUrls: ['./left-domain.component.scss', '../plan/publicPop.scss']
})
export class LeftDomainComponent implements OnInit {

  constructor(private message: NzMessageService, private element: ElementRef, private http: HttpClient, private cd: ChangeDetectorRef) { }

  ngOnInit(): void {
    this.editMode = PlanComponent.instance.editMode
    this.initComponent()
  }

  editMode: boolean = true; //编辑/查看模式
  userMode: boolean = ModeManager.s_isMakeMode; //是否为 内部权限
  beforeFence: number; //当前选中功能栏
  FacilityList: FacilityInfoUIItem[] = []; //统计设备 list
  selectFacilityId: string = null; //选中设备 ID
  baseInfo: any; //基本信息
  isShowBaseDialog: boolean = false; //显隐 编辑信息/导出Excel 弹窗

  //初始化组件
  initComponent(type?: number) {
    if (type != undefined && type != null) {
      this.beforeFence = type
      this.handleFacility()
    } else {
      this.beforeFence = PlanComponent.instance.selectFence
      this.handleFacility()
    }
  }

  //处理 设备data
  handleFacility() {
    if (this.beforeFence === 0) { //基本信息
      if (!this.baseInfo) {
        let params = { organizationUnitId: PlanComponent.instance.companyData.id }
        this.http.get('/api/services/app/GasStation/Get', { params: params }).subscribe((data: any) => {
          data.result.govUnitDetail ? data.result.govUnitDetail = JSON.parse(data.result.govUnitDetail) : null
          this.baseInfo = data.result
        })
      }
      return
    }
    if (this.beforeFence === 8) { //应急预案
      this.selectPlanId = null
      this.selectNodeId = null
      if (MarkWindow.instance) {
        this.allMarkPlanData = MarkWindow.instance.allMarkPlanData
      }
      return
    }
    let list: FacilityInfoUIItem[] = []
    FacilityInfoInSceneWindow.instance.facilityInfoUIItemes.forEach(item => {
      if (this.beforeFence === 1) { //加油机
        item.getType() === "JY_JYJ" ? list.push(item) : null
      } else if (this.beforeFence === 2) { //油罐设备
        item.getType() === "JY_YG" ? list.push(item) : null
      } else if (this.beforeFence === 3) { //消防设施
        (item.getType()).slice(0, 3) === "XF_" ? list.push(item) : null
      } else if (this.beforeFence === 5) { //输油管线
        item.getType() === "JY_SYGX" ? list.push(item) : null
      } else if (this.beforeFence === 6) { //油气回收
        item.getType() === "JY_YQHSGX" ? list.push(item) : null
      } else if (this.beforeFence === 7) { //阀门
        item.getType() === "JY_FM" ? list.push(item) : null
      }
    })
    this.FacilityList = list
    this.selectFacilityId = null
    if (this.beforeFence === 1 || this.beforeFence === 2 || this.beforeFence === 6 || this.beforeFence === 7) { //加油机/油罐设备/油气回收/阀门
      this.FacilityList.forEach(item => {
        window.setTimeout(()=>{
          this.textInput(item)
        },0)
        if (this.beforeFence === 2) {
          item.getPropertyData().oilTankType = this.setNewData(item.getPropertyData().oilTankType)
          item.getPropertyData().oilPumpType = this.setNewData(item.getPropertyData().oilPumpType)
        } else if (this.beforeFence === 6) {
          item.getPropertyData().VRUType_2 = this.setNewData(item.getPropertyData().VRUType_2)
        }
      })
    }
    if (this.beforeFence === 3) { //消防设施
      this.handleTreeData(this.FacilityList)
    }
    if (this.beforeFence === 2) { //油罐设备
      PlanComponent.instance.tankFarm.isHave = false;
      this.FacilityList.forEach(item => {
        if (item.getPropertyData().tankFarm != undefined) {
          PlanComponent.instance.tankFarm.isHave = true
          PlanComponent.instance.tankFarm.content = item.getPropertyData().tankFarm
          return;
        }
      })
    }
    if (this.beforeFence === 5 || this.beforeFence === 6) { //初始化 Viewer
      let id: string = this.beforeFence === 5 ? "pipelineViewer" : "orvrViewer"
      this.FacilityList.forEach(item => {
        if (item.getPropertyData() && item.getPropertyData().img) {
          window.setTimeout(() => {
            new Viewer(this.element.nativeElement.querySelector(`#${id}${item.getID()}`), { url: 'data-original', navbar: false });
          }, 0)
        }
      })
    }
  
  }

  //处理 油罐罐区/油气回收 select框老数据
  setNewData(e: string):string {
    if(e === "scg") {
      e = "双层罐"
    } else if (e === "dcg") {
      e = "单层罐+防渗罐池"
    } else if (e === "zxb") {
      e = "自吸泵"
    } else if (e === "qyb") {
      e = "潜油泵"
    } else if (e === "fss") {
      e = "分散式"
    } else if (e === "jzs") {
      e = "集中式"
    }
    return e
  }

  //选中 设备
  selectFacility(event, item: FacilityInfoUIItem) {
    if (event.target.localName == 'img') {
      return
    }
    if (this.selectFacilityId != item.getID()) {
      this.selectFacilityId = item.getID()
      FacilityInfoInSceneWindow.instance.selectFacilityItem(item);
    } else {
      this.selectFacilityId = null
      item.onSelect(false)
    }
  }

  //阻止 事件冒泡
  stopBubbling(event) {
    event.stopPropagation();
    //event.preventDefault();
  }

  //上传设备 图片
  uploadLeftDomainImg(e, item: FacilityInfoUIItem) {
    if (e.target.files.length) {
      let maxSize = 30 * 1024 * 1024 //限制30MB
      let file = e.target.files[0]
      if (file.size > maxSize) { //超出限制
        this.message.info("上传资源需小于30MB");
        return
      }
      PlanComponent.instance.isShowLoading = true //打开遮罩
      let institutionKey = `${PlanComponent.instance.companyData.id}` || "ceshi"; //单位id
      let buildingKey = PlanComponent.instance.buildingUIItems.find(item => { return item.getBuildingID() == PlanComponent.instance.beforeOneBuildingID })
      let url = DataManager.getResPath_facilityProperty(institutionKey, buildingKey ? buildingKey.getBuildingID() : "building", item.getType(), item.getID(), null)
      ServeManager.instance.openFileSelect(file, url, (name: string, path: string) => { //上传
        item.getPropertyData().img = ObjectsService.getFullPath(path + name)
        if (this.beforeFence === 5) {
          window.setTimeout(() => {
            new Viewer(this.element.nativeElement.querySelector(`#pipelineViewer${item.getID()}`), { url: 'data-original', navbar: false });
          }, 0)
        } else if (this.beforeFence === 6) {
          window.setTimeout(() => {
            new Viewer(this.element.nativeElement.querySelector(`#orvrViewer${item.getID()}`), { url: 'data-original', navbar: false });
          }, 0)
        }
        PlanComponent.instance.isShowLoading = false //关闭遮罩
        this.message.info("上传成功!");
      })
    }
  }

  //删除设备 图片
  deleteImg(item: FacilityInfoUIItem) {
    let isDelete = confirm("您确定要删除吗?")
    if (isDelete) {
      this.http.delete(`${item.getPropertyData().img}`).subscribe(data => {
        item.getPropertyData().img = ""
        this.message.info("删除成功!");
      })
    }
  }

  @ViewChild('nzTreeComponent', { static: false }) nzTreeComponent!: NzTreeComponent;
  treeData: NzTreeNodeOptions[] = []; //tree data

  //处理 treeData
  handleTreeData(list: FacilityInfoUIItem[]) {
    this.treeData = []
    list.forEach(item => {
      let isFind = this.treeData.find(element => { return (item.getType()).includes(element.key) })
      if (!isFind) { //不存在
        if (item.getType().includes('XF_MHQ')) { //灭火器
          let primaryNode = { title: '灭火器', key: 'XF_MHQ', selectable: false, expanded: true, children: [], }
          let treeNode = { title: ConfigManager.getFacilityTypeName(item.getType()), key: item.getType(), selectable: false, }
          primaryNode.children.push(treeNode)
          this.treeData.push(primaryNode)
        } else {
          let primaryNode = { title: ConfigManager.getFacilityTypeName(item.getType()), key: item.getType(), selectable: false, }
          this.treeData.push(primaryNode)
        }
      } else { //存在
        if (item.getType().includes('XF_MHQ') && !isFind.children.find(elements => { return elements.key === item.getType() })) { //灭火器
          let treeNode = { title: ConfigManager.getFacilityTypeName(item.getType()), key: item.getType(), selectable: false, }
          isFind.children.push(treeNode)
        }
      }
    })
    //编辑模式
    if (this.editMode) {
      let isFind = this.treeData.find(item => { return item.key === 'XF_MHQ' })
      if (!isFind) {
        let primaryNode = { title: '灭火器', key: 'XF_MHQ', selectable: false, }
        this.treeData.push(primaryNode)
      }
      for (let facility in FacilityType) {
        if (facility.slice(0, 3) === "XF_" && !facility.includes('XF_MHQ')) {
          let isFind = this.treeData.find(item => { return item.key === facility })
          if (!isFind) {
            let primaryNode = { title: ConfigManager.getFacilityTypeName(FacilityType[facility]), key: facility, selectable: false, }
            this.treeData.push(primaryNode)
          }
        }
      }
    }
    //编辑模式
  }

  //监听textarea 输入事件
  textInput(item: FacilityInfoUIItem) {
    window.setTimeout(()=>{
      let title: HTMLCanvasElement = this.element.nativeElement.querySelector(`#title${item.modelInfo.key}`)
      let content: HTMLCanvasElement = this.element.nativeElement.querySelector(`#content${item.modelInfo.key}`)
      if (title && content) {
        title.style.height = this.getTextareaHeight(item)
        title.style.lineHeight = this.getTextareaHeight(item)
        content.style.height = this.getTextareaHeight(item)
      }
      if (this.beforeFence === 6) { //油气回收
        let orvrTitle: HTMLCanvasElement = this.element.nativeElement.querySelector(`#orvrTitle${item.modelInfo.key}`)
        let orvrContent: HTMLCanvasElement = this.element.nativeElement.querySelector(`#orvrContent${item.modelInfo.key}`)
        if (orvrTitle && orvrContent) {
          orvrTitle.style.height = `${this.element.nativeElement.querySelector(`#orvrNum${item.modelInfo.key}`).getBoundingClientRect().height}px` || `32px`
          orvrTitle.style.lineHeight = `${this.element.nativeElement.querySelector(`#orvrNum${item.modelInfo.key}`).getBoundingClientRect().height}px` || `32px`
          orvrContent.style.height = `${this.element.nativeElement.querySelector(`#orvrNum${item.modelInfo.key}`).getBoundingClientRect().height}px` || `32px`
        }
      }
    },0)
  }

  //获取textarea 高度
  getTextareaHeight(item: FacilityInfoUIItem):string {
    let html: HTMLCanvasElement = this.element.nativeElement.querySelector(`#num${item.modelInfo.key}`)
    if (html) {
      return `${html.getBoundingClientRect().height}px`
    } else {
      return `32px`
    }
  }

  //获取设备 数量
  getFacilityNum(type: string): string {
    let num = 0
    this.FacilityList.forEach(item => {
      item.getType().includes(type) ? num = num + 1 : null
    })
    let unit = type === 'XF_MHQ'? '具' : ConfigManager.getFacilityNumUnit(FacilityType[type])
    let facilityNum = `${num}${unit}`
    if (type === FacilityType.XF_XFS) {
      facilityNum = `${num*2}${unit}`
    }
    return facilityNum
  }

  //点击tree节点
  nzClick(event: NzFormatEmitEvent) {
    if (event.node.key != 'XF_MHQ') {
      event.node.isSelected = !event.node.isSelected
      if (event.node.isSelected) { //显示当前, 隐藏所有
        FacilityInfoInSceneWindow.instance.showFacilityByType(null, false)
        FacilityInfoInSceneWindow.instance.showFacilityByType(FacilityType[event.node.key], event.node.isSelected)
      } else { //显示所有
        this.treeData.forEach(item => {
          if (item.key != 'XF_MHQ') {
            FacilityInfoInSceneWindow.instance.showFacilityByType(FacilityType[item.key], true)
          } else {
            item.children.forEach(element => { FacilityInfoInSceneWindow.instance.showFacilityByType(FacilityType[element.key], true) })
          }
        })
      }
    }
  }

  allMarkPlanData: AllMarkPlanData; //处置预案节点数据
  allSandBoxTemplate: MarkTemplate[] = []; //所有模板
  selectPlanId: number;
  selectNodeId: number;
  addDisposalPop: boolean = false; //显示/隐藏 创建预案 弹窗
  addNodePop: number = null; //显示/隐藏 创建节点 父节点ID

  //创建预案/节点
  addDisposal(e) {
    if (this.addDisposalPop) { //创建预案
      if (e.selectMould) {
        MarkWindow.instance.addMarkPlanByTemplate(e.selectMould)
        this.addDisposalPop = false
      } else {
        if (!e.name) {
          this.message.info('请填写名称!');
          return
        }
        MarkWindow.instance.createMarkPlaneData(e.name)
        this.addDisposalPop = false
      }
    } else { //创建节点
      if (!e.name) {
        this.message.info('请填写名称!');
        return
      }
      MarkWindow.instance.createMarkNodeData(this.addNodePop, e.name)
      this.addNodePop = null
    }
  }

  editSelectDisposal: MarkPlanData = null; //编辑预案名称 选中预案
  editDisposalName: string = null; //显示/隐藏 编辑预案名称 弹窗

  //打开 创建预案弹窗
  openAddDisposal(event, id: number) {
    event.stopPropagation()
    this.addNodePop = id
  }

  selectMould: number = 0; //当前选择模板

  //删除模板
  deleteMould(e) {
    if (e.selectMould) {
      let isTrue = confirm('您确定要删除当前选中模板吗')
      if (isTrue) {
        MarkWindow.instance.deleteSandBoxTemplate(e.selectMould)
        this.allSandBoxTemplate.splice(this.allSandBoxTemplate.findIndex(item => item.id === e.selectMould), 1)
        this.selectMould = 0
      }
    }
  }

  //保存为模板
  saveMould() {
    MarkWindow.instance.saveToSandBoxTemplate(this.editSelectDisposal)
    this.message.info('保存成功!')
  }

  //打开 编辑预案名称弹窗
  openEditDisposal(event, item: MarkPlanData) {
    event.stopPropagation()
    this.editSelectDisposal = item;
    this.editDisposalName = JSON.parse(JSON.stringify(item.name))
  }

  //编辑预案名称
  editDisposal(e) {
    this.editSelectDisposal.name = e.name
    this.editSelectDisposal = null
  }

  //删除预案/节点
  deleteDisposal(event, item: MarkPlanData, e?: MarkNodeData) {
    event.stopPropagation()
    let isTrue = confirm('您确定要删除吗')
    if (isTrue) {
      if (!e) {
        MarkWindow.instance.deleteMarkPlaneData(item.id)
      } else {
        MarkWindow.instance.deleteMarkNodeData(item.id, e.id)
      }
    }
  }

  //选中 数据节点
  selectNode(item: MarkPlanData, e: MarkNodeData, index: number) {
    if (this.selectPlanId != item.id || this.selectNodeId != e.id) { //选中
      this.selectPlanId = item.id
      this.selectNodeId = e.id
      PlanComponent.instance.beforeEmergencyPlan = item
      PlanComponent.instance.beforePlanNode = e
      if (PlanComponent.instance.progressList.length != item.nodes.length) {
        PlanComponent.instance.updateProgressList()
      }
      this.updateFatherData(index) //更新/初始化父组件 数据
      PlanComponent.instance.initViewer()
      MarkWindow.instance.selectMarkNode(item.id, e.id)
    } else if (this.selectPlanId === item.id && this.selectNodeId === e.id) { //取消选中
      this.selectPlanId = null
      this.selectNodeId = null
      PlanComponent.instance.beforeEmergencyPlan = new MarkPlanData(-99, "请选择应急预案")
      PlanComponent.instance.beforePlanNode = new MarkNodeData(-99, "请选择应急预案")
      this.updateFatherData(index) //更新/初始化父组件 数据
      MarkWindow.instance.selectMarkNode(null, null)
    }
  }

  //更新/初始化父组件 数据
  updateFatherData(index) {
    PlanComponent.instance.updateTimer ? window.clearTimeout(PlanComponent.instance.updateTimer) : null //清除定时器
    PlanComponent.instance.progressList.forEach((item, key) => { key >= index ? PlanComponent.instance.progressList[key] = 0 : PlanComponent.instance.progressList[key] = 100 })
    PlanComponent.instance.nzCurrent = index
    PlanComponent.instance.isSuspend = true //暂停
  }

  saveDisposalDialog: boolean = false; //整体保存预案 弹窗
  saveType: number = null; //新建保存/保存到已有 弹窗
  allNodeList: any[] = []; //所有根节点/节点

  //保存-1
  saveDisposal(markPlanId: number = null, nodeId: number = null) {
    if (!MarkWindow.instance.currentMarkNodeInfo) { //未选中节点
      this.message.info('还没有进行标绘,无法保存');
      return
    }
    if (markPlanId === null && nodeId === null) { // 整体弹窗保存
      this.saveDisposalDialog = true
    } else {
      if (this.selectPlanId === markPlanId && this.selectNodeId === nodeId) {
        MarkWindow.instance.saveToOldNode(markPlanId, nodeId)
      } else {
        let isTrue = confirm('是否覆盖要保存的节点?')
        isTrue ? MarkWindow.instance.saveToOldNode(markPlanId, nodeId) : null
      }
    }
  }

  //保存-2
  saveNode(isNew: boolean) {
    this.saveDisposalDialog = false
    if (isNew) { //新建节点并保存
      this.saveType = 1
      this.allNodeList = MarkWindow.instance.allMarkPlanData.datas
    } else { //保存到已有节点
      this.saveType = 2
      this.allNodeList = []
      MarkWindow.instance.allMarkPlanData.datas.forEach(item => {
        item.nodes.forEach(element => {
          let node = {
            id: element.id,
            parrentId: item.id,
            name: element.name,
          }
          this.allNodeList.push(node)
        })
      });
    }
  }

  //保存-3
  saveDisposalNode(e) {
    if (this.saveType === 1) { //新建节点并保存
      if (!e.name || !e.root) {
        this.message.info('请完善表单')
        return
      }
      MarkWindow.instance.createNewNodeAndSave(e.root.id, e.name)
      this.saveType = null
    } else { //保存到已有节点
      if (!e.node) {
        this.message.info('请完善表单')
        return
      }
      MarkWindow.instance.saveToOldNode(e.node.parrentId, e.node.id)
      this.saveType = null
    }
  }

  originalData: any; //sessionStorage 原始数据

  //编辑信息
  editInfo() {
    this.originalData = sessionStorage.getItem('userdata')
    let userdata = { organization: PlanComponent.instance.companyData, hideCloseBtn: true }
    sessionStorage.setItem('userdata', JSON.stringify(userdata))
    this.isShowBaseDialog = true
  }

  //导出Excel
  deriveExcel() {
    this.originalData = sessionStorage.getItem('userdata')
    let userdata = { organization: PlanComponent.instance.companyData, hideCloseBtn: true }
    sessionStorage.setItem('userdata', JSON.stringify(userdata))
    this.isShowBaseDialog = true
  }

  //关闭 编辑信息/导出Excel 弹窗
  closeBaseInfoDialog() {
    PlanComponent.instance.isShowLoading = true
    let params = { organizationUnitId: PlanComponent.instance.companyData.id }
    this.http.get('/api/services/app/GasStation/Get', { params: params }).subscribe((data: any) => {
      data.result.govUnitDetail ? data.result.govUnitDetail = JSON.parse(data.result.govUnitDetail) : null
      this.baseInfo = data.result
      sessionStorage.setItem('userdata', this.originalData)
      this.isShowBaseDialog = false
      PlanComponent.instance.isShowLoading = false
    })
  }

}

export class treeData {
  static nodes: NzTreeNodeOptions[] = []
}