import { Component, OnInit, Inject, ViewChild,ElementRef,Renderer2, ViewContainerRef, ɵConsole } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatSnackBar, MatSnackBarConfig } from '@angular/material/snack-bar';
import {MatTreeFlatDataSource, MatTreeFlattener} from '@angular/material/tree';
import {FlatTreeControl} from '@angular/cdk/tree';
import {WorkingAreaComponent} from '../../working-area/working-area.component'
import {CanvasShareDataService, DisposalNodeData} from '../../canvas-share-data.service' //引入服务
import Viewer from 'viewerjs';
import Swiper from 'swiper';
import { NzFormatBeforeDropEvent, NzFormatEmitEvent,NzTreeComponent } from 'ng-zorro-antd/tree';
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
import { windows } from 'src/app/interface';
import { GameMode } from 'src/app/working-area/model/gameMode';
import { ActivatedRoute, Router } from '@angular/router';
import { examinationQuestionsRead,uploadDisposalNodesRead,uploadQuestionsRead } from './examinationQuestions'


@Component({
  selector: 'app-collection-tools',
  templateUrl: './collection-tools.component.html',
  styleUrls: ['./collection-tools.component.scss']
})
export class CollectionToolsReadComponent implements OnInit {

  @ViewChild('canvas',{static: true}) canvas:WorkingAreaComponent; //父组件中获得子组件的引用

  constructor(private http:HttpClient,public dialog: MatDialog,public snackBar: MatSnackBar,private element: ElementRef,public canvasData: CanvasShareDataService,private router:Router,private route:ActivatedRoute) { }
  @ViewChild('nzTreeComponent2', { static: false }) nzTreeComponent!: NzTreeComponent;
  // tree配置
  private _transformer = (node, level: number) => {//要给渲染节点传那些属性参数
    return {
      expandable: !!node.children && node.children.length > 0,
      name: node.name || node.Name,
      level: level,
      id: node.id || node.Id,
      children:node.children,
      isTemplate:node.isTemplate,
      isNewElement:node.isNewElement,
      isLook:node.isLook,
      isLookPattern:node.isLookPattern || null
    };
  }
  treeControl = new FlatTreeControl<any>(node => node.level, node => node.expandable);
  
  treeFlattener = new MatTreeFlattener(this._transformer, node => node.level, node => node.expandable, node => node.children);
  dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
  hasChild = (_: number, node: any) => node.expandable;

  colors = ['#076eec','#4dd0e1','#00ee76','#ffff00','#eeb422',
            '#FF6A6A','#ff0000','#ff6eb4','#00bfff','#54ff9f',
            '#009688','#836fff','#ff8c00','#ee00ee','#ffa07a',
            '#00C500','#00ffff','#6495ed','#ffdAb9','#AA00FF']
  selected = "1" //图标大小选择框
  
  allBuildings //该单位所有建筑
  beforeOneCheckedBuilding:any = {name:"总平面图"}; //当前点击选择的建筑
  beforeOneCheckedBuildingIsShow:boolean = false; //建筑是否显示
  togglebeforeOneCheckedBuilding () { this.beforeOneCheckedBuildingIsShow = !this.beforeOneCheckedBuildingIsShow }
  checkedBuildingIndex:number = -1 //当前点击选择的建筑index
  isEditPat:boolean =  true //当前是否是编辑模式

  assetName:String//素材名称
  assetWidth:number//素材宽度
  assetHeight:number//素材高度
  sliderValue:number = 0//角度滑竿的值
  sliderValueThickness:number = 0//厚度滑竿的值
  isHighLight:boolean = false//是否高亮选择框
  PropertyInfos = [] //去除图片链接真正用于循环的内容
  imagesArrNum //素材属性图片数量上限
  imagesArr = [] //属性中的图片链接集合
  clickedIndex //点击图片时的索引值

  //传入素材对象,设置右侧属性栏内容
  canvasAssetObj //传入的素材属性对象
  isImgNumCss = false //控制上传文件input显隐
  mySwiper:any //轮播图实例

  gallery//viewerJs实例
  selectedcolor:any//选择素材的颜色代码
  //设置属性框
  setAssetsProperty(obj){
    //初始化viewerJs实例
    setTimeout(() => {
      obj.PropertyInfos.forEach(item => {
        if(item.PropertyType == 4){
          this.gallery = new Viewer(document.getElementById('viewerjs'),{
            url: 'data-original'
          });
        }
      })
    }, 0);
    
    //从颜色中取出透明度
    let color = obj.Color
    let strh = color.substring(color.length -2,color.length)
    let opacity = Math.round(parseInt(strh,16)/255 * 100) 

    this.isShowProperty = true
    this.isShowAttribute = false
    let _this = this
    this.imagesArr = []
    this.imagesArrNum = ""

    this.canvasAssetObj = obj //将选中素材对象存到本地变量

    this.assetName = obj.Name
    this.assetWidth = obj.Width
    this.assetHeight = obj.Height
    this.sliderValue = obj.Angle
    this.selectedcolor = obj.Color
    this.PropertyInfos = obj.PropertyInfos
    this.sliderValueThickness = obj.Thickness
    this.PropertyInfos.forEach(item => {
      if(item.PropertyType == 3){ //如果是图片链接类型
        this.imagesArr.push(item)
      }
      if(item.PropertyType == 4){//图片数值上线
        this.imagesArrNum = item.PropertyValue
      }
    })

    //如果存在图片则加载轮播图
    if(this.imagesArr.length){
      setTimeout(() => {
        this.mySwiper = new Swiper('.swiper-container',{
          loop: false,
          // grabCursor: true,
          // 如果需要前进后退按钮
          navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
          },
          on:{
            click: function(){
              _this.clickedIndex = this.clickedIndex
            },
          }
        });
      }, 0);
    }
    //判断此时图片数量是否达到上限
    if(this.imagesArr.length < this.imagesArrNum){//如果不超出
      this.isImgNumCss = true
    }else{
      this.isImgNumCss = false
    }
  }
  pattern:boolean = false//默认为基本信息编辑



  //左侧div边框宽度调节
  leftDivMouseDown(e){
    document.onmousemove = (ev) => {
      let bodyWidth = document.body.clientWidth //网页宽度
      let maxWidth = bodyWidth - 260 - this.element.nativeElement.querySelector('#rightDiv').clientWidth  //最大宽度
      if(ev.clientX - 240 >= maxWidth){
        this.element.nativeElement.querySelector('#leftDiv').style.width = maxWidth + 'px'
      }else{
        this.element.nativeElement.querySelector('#leftDiv').style.width = ev.clientX - 260 + 'px';
      }
    }
    document.onmouseup = () => {
      document.onmousemove = null;
      document.onmouseup = null;
    }
  }


  //右侧div边框宽度调节
  rightDivMouseDown(e){
    document.onmousemove = (ev) => {
      let bodyWidth = document.body.clientWidth //网页宽度
      let maxWidth = bodyWidth - 240 - this.element.nativeElement.querySelector('#leftDiv').clientWidth  //最大宽度
      if(bodyWidth - ev.clientX >= maxWidth){
        this.element.nativeElement.querySelector('#rightDiv').style.width = maxWidth + 'px'
      }else{
        this.element.nativeElement.querySelector('#rightDiv').style.width = bodyWidth - ev.clientX + 'px';
      }
    }
    document.onmouseup = () => {
      document.onmousemove = null;
      document.onmouseup = null;
    }
  }

  examMsg = { //单位,考试信息
    conpanyName: sessionStorage.getItem('companyName') || '暂无数据', //单位名称
    keynote: '', //考试要点
  }

  async ngOnInit(): Promise<void> {

    this.getAllBuildings() //获取所有建筑
    this.getAllFirePlan() //获取当前单位灾情

    await this.getPaperPlanData()//获得当前考题题目
    
    let that = this
    window.setTimeout(()=>{
      document.getElementById("functionalDomainContent").oncontextmenu = function (event) {
        event.preventDefault();
      };
    })

    this.canvasData.getMessage().subscribe((message: any)=>{
      if(message == "send a message"){
        this.refurbishTreeData()
      }
    })
  }

  paperType:any = this.route.snapshot.queryParams.paperType // 阅卷 / 查看试卷
  paperId:any = this.route.snapshot.queryParams.paperId
  planData:any //当前考题题目
  Facilities:any //当前预案考题所有楼层要考的基本信息素材
  //获得单位预案设定
  async getPaperPlanData(){
    let params = {
      paperId : this.paperId
    }
    await new Promise((resolve,reject)=>{
      this.http.get(`/api/PaperPlans`,{params:params}).subscribe((data:any) => {
        data.forEach(item => {
          item.id == this.route.snapshot.queryParams.paperplanId ? 
          this.planData = item : null
        })
       
        let questions = JSON.parse(this.planData.examDisposalNodesData) 
        this.handleHybridTree(questions,'题目')
        this.Facilities = JSON.parse(this.planData.examFacilityAssetsData)
        console.log('当前预案设定需要隐藏的基本信息图标',this.Facilities)
        resolve(1)
      })
    })
  }

  ngAfterViewInit(): void {
    
    this.getSitePlan() //获取总平面图/楼层

    // 监听canvas组件选中素材事件
    this.canvas.on("select",obj=>{
      //选中素材属性注入函数
      this.setAssetsProperty(obj.assetData)
    
    })
    // 监听canvas组件取消选中素材事件
    this.canvas.on("deselect",obj=>{
      this.isShowProperty = false
    })
    // 监听canvas组件新增素材事件
    this.canvas.on("createIcon",obj=>{
      console.log(obj.assetData)
    })
    // 监听canvas组件删除素材事件
    this.canvas.on("deleteIcon",obj=>{
    })

    
  }


  score(){
    let data = {score:this.planData.score}
    let dialogRef = this.dialog.open(Score,{data});
  }

  submitScore(){
    if(!sessionStorage.getItem('scoreNum')){
      const config = new MatSnackBarConfig();
      config.verticalPosition = 'top';
      config.duration = 3000
      this.snackBar.open('请先进行评分!','确定',config);
    }else{
      if(window.confirm('你确定要提交此阅卷结果吗?')){
        let params = {
          paperPlanId : this.route.snapshot.queryParams.paperplanId,
          examinationId : this.route.snapshot.queryParams.examId,
          score : sessionStorage.getItem('scoreNum')
        }
        this.http.put('/api/ExaminationPlans/ModifyScore','',{params:params}).subscribe(data => {
          const config = new MatSnackBarConfig();
          config.verticalPosition = 'top';
          config.duration = 1000
          this.snackBar.open('提交成功,页面将于一秒后关闭!','确定',config);
          setTimeout(() => {
            window.close()
          }, 1000);
        })
        return true;
      }else{
        return false;
      }
    }
   
  }


  //获得所有的建筑物
  getAllBuildings(){
    this.http.get("/api/Buildings",{
      params:{
        companyId : this.params.companyId
      }
    }).subscribe(data=>{
      this.allBuildings = data
    })
  }


  //选择建筑
  checkedBuilding(item,index){
    if (this.checkedBuildingIndex!=index) {
      this.beforeOneCheckedBuilding = item
      this.checkedBuildingIndex = index
      if (index==-1) { //总平面图数据
        this.getSitePlan()
      } else { //建筑楼层/区域数据
        this.getBuildingSitePlan(item)
      }
    } //if
  }



  storeyData //将建筑素材和当前楼层素材合二为一

  //处理 tree 数据结构
  handleTreeData (storeyData) {
    //storeyData为当前楼层拥有的消防设施
    this.storeyData = storeyData
    let data = JSON.parse(JSON.stringify(this.allFireElements))  //所有消防要素模板
    let treeData = [] //tree型 处理完成后的数据
    this.allFireElements.forEach(element => {
      element.key = element.id
      element.isTemplate = true //添加模板标识
      element.isLook = true //添加是否可见标识
      element.name != '其他' ? element.children = [] : null
      if(storeyData){
        for(let key in storeyData.data){
          storeyData.data[key].isLookPattern = true
          if(element.id == storeyData.data[key].FireElementId){
            storeyData.data[key].isTemplate = false
            storeyData.data[key].isLook = true
            
            element.isNewElement = true //该节点children是否存在新添加的真实素材 标识

            //定义查看模式下能看到的元素
            element.isLookPattern = true
            if(element.parentId){
              data.forEach(i => {
                if(i.id == element.parentId){
                  i.isLookPattern = true
                }
              })
            }
            element.children.push(storeyData.data[key])
          }
        }
      }
      this.allFireElements.forEach(item => { if (item.parentId == element.id) {element.children.push(item)} });
    });
    this.allFireElements.forEach(element => {
      if (!element.parentId) { treeData.push(element) }
    });

    function recursionFilterEmpty(originalList, result) {
        for(let i = 0, length = originalList.length; i < length; i++) {
            const item = originalList[i];
            if (item.PropertyInfos) {
                // 最内层
                result.push(item);
            } else if (item.children && item.children.length) {
                const newChildren = [];
                // 递归调用,底层的真实数据会全部 push 进 newChildren 中
                recursionFilterEmpty(item.children, newChildren);
                if (newChildren.length) {
                    // 替换原始数据
                    item.children = newChildren;
                    // 子项有真实的数据,就保留这一项
                    result.push(item);
                } // 如果没有这一项就会被删除
            }
        }
    }
        
    function filterEmpty(listData) {
        const result = [];
        recursionFilterEmpty(listData, result);
        return result;
    }

    this.dataSource.data = filterEmpty(treeData)

    this.treeControl.expandAll()
    
  }

  //点击树节点
  clickTreeNode(node){

    if(this.canvasData.originalcompanyBuildingData.data[node.id]){
      this.setAssetsProperty(this.canvasData.originalcompanyBuildingData.data[node.id])
    }else if(this.canvasData.originaleveryStoreyData.data[node.id]){
      this.setAssetsProperty(this.canvasData.originaleveryStoreyData.data[node.id])
    }

    // canvas上的素材高亮
    let iconHighLightArr:any = []
    if(node.isTemplate){//如果是模板,则开始向下找
      node.children.forEach(item => {
        if(item.isTemplate){//如果子节点依旧是模板,则继续开始向下找
          item.children.forEach(i => {
            iconHighLightArr.push(i.Id)
          })
        }else{
          iconHighLightArr.push(item.Id)
        }
      })
    }else{
      iconHighLightArr.push(node.id)
    }
    this.canvas.setHighlight(iconHighLightArr)
  }

  //点击树节点的显示隐藏icon
  clickLookItem(node){
    //子节点跟随父节点的islook变化
    let iconVisibleArr:any = []
    if(node.origin.children && node.origin.children.length != 0){
      node.origin.isLook = !node.origin.isLook
      node.origin.children.forEach(item=>{
        item.isLook = node.origin.isLook 
        if(item.children && item.children.length != 0){
          item.children.forEach(i=>{
            i.isLook = node.origin.isLook 
            if(i.children && i.children.length != 0){

            }else{
              iconVisibleArr.push(i.Id)
            }
          })
        }else{
          iconVisibleArr.push(item.Id)
        }
      })
     }else{
      node.origin.isLook = !node.origin.isLook
      iconVisibleArr.push(node.origin.Id)
    }
    console.log(iconVisibleArr)
    console.log(node.origin.isLook)
    this.canvas.setIconVisible(iconVisibleArr, node.origin.isLook)
  }

  //打开消防设施考题设定
  openFireExamination () {
    let buildFloorData = {
      buildingData:this.beforeOneCheckedBuilding,
      floorData:this.selectingSitePlan
    }
    let data = { oldRealData:this.storeyData ,buildFloorData:buildFloorData,Facilities:this.Facilities,allFireElements:this.allFireElements,paperType:this.paperType}
    let dialogRef = this.dialog.open(examinationQuestionsRead,{data}); //examinationQuestionsExaminee
  }

  answerDivDrag:boolean = false//查看答案窗口的显隐
  answertreeData:any = []
  lookAnswerDiv(){
    this.answerDivDrag = !this.answerDivDrag
    
    let question = JSON.parse(this.planData.examDisposalNodesData)
    let questionDataArr = []
    question.forEach(item => {
      item.sitePlanId ? questionDataArr.push(item) : null
    });
    
    function array_diff(a, b) {
      for(var i=0;i<b.length;i++)
      {
        for(var j=0;j<a.length;j++)
        {
          if(a[j].id==b[i].id){
            a.splice(j,1);
            j=j-1;
          }
        }
      } 
      return a;
    }
    console.log(111,this.allExaminationQuestions)
    console.log(222,questionDataArr)
    let arr = array_diff(this.allExaminationQuestions,questionDataArr)
    
    let treeData = []
    arr.forEach(element => {

      element.title = element.name //name
      element.key = element.id //id
      element.children = [] //children
      if (element.sitePlanId || element.buildingAreaId) { //是数据节点
        element.isLeaf = true
        element.isDataNode = true
      } else { //不是数据节点
        element.isLeaf = false
        element.isDataNode = false
      }
      arr.forEach(item=>{
        item.parentId === element.id? element.children.push(item) : null
      })
    });
    arr.forEach(element=>{
      !element.parentId? treeData.push(element) : null
    })
    console.log(789,treeData)
    this.answertreeData = treeData

  }

  //考官获得设置考题的所有处置节点
  allExaminationQuestions:any
  getExaminationQuestions(){
    let api
    this.examType == 1? api='/api/DisposalNodes' : api='/api/ExamDisposalNodes'
    this.defaultExpandedKeys = []
    let params
    this.examType == 1?  params = {disasterId: this.allFirePlan[0].id || ''} :  params = {examDisasterId: this.allFirePlan[0].id || ''}
    this.http.get(api,{params:params}).subscribe(nodeData=>{

      this.allExaminationQuestions = nodeData
    })
  }
   /**
   * 获得所有素材库
   */
  basicAssetLibraries:any = []//基本信息素材库
  getAllAssetLibraries(Facilitiesitem){
  
    console.log('具体到当前楼层需要隐藏的基本信息图标',Facilitiesitem.children)
    let arr = []
    Facilitiesitem.children.forEach(item => {
      arr.push(item.Id)
    })
    this.canvasData.hiddenBasicInfoFacilities = arr
    // this.canvas.loadExamineeData()

   
  }
  //上传考题
  openUploadQuestions () {

    let data = {allFireElements:this.allFireElements,Facilities:this.Facilities}
    let dialogRef = this.dialog.open(uploadQuestionsRead,{data});
    
  }


  renderData:any = []//当前层默认隐藏的基本信息考试题目
  hiddenBasicInfoFacilities:any
  //封装 刷新 tree 数据
  async renovateTreeData (isRefresh:boolean = true) {
    this.allFireElements[this.allFireElements.length-1].children = []
    this.beforeOneCheckedBuildingIsShow = false
    isRefresh? this.canvasData.isChange = false : null //服务中 数据是否改动 改为false
    isRefresh? this.isShowProperty = true : null
    isRefresh? this.isShowAttribute = true : null

    let beforeOneId = this.selectingSitePlan.id || '' //当前 选中 平面图 楼层/区域 id
    let companyBuildingData = JSON.parse(JSON.stringify( this.canvasData.originalcompanyBuildingData || {} )) // 当前 单位/建筑 数据 
    let storeyData = JSON.parse(JSON.stringify( this.canvasData.originaleveryStoreyData || {} )) //当前 楼层 数据
    console.log('this.Facilities',this.Facilities)

    for(let key in storeyData.data){ //筛选数据 
      storeyData.data[key].key = storeyData.data[key].Id
      let noMatch = this.allFireElements.find( every=> every.id===storeyData.data[key].FireElementId )
      //没有匹配全部放入到   其他   数组
      if (!noMatch) {
        this.allFireElements[this.allFireElements.length-1].children.push(storeyData.data[key])
      }
    }
    this.handleTreeData(storeyData) //处理tree数据结构
  }
  //处理数据 将消防要素模板与真实素材结合
  processingData(allFireElements,realData){
    allFireElements[allFireElements.length-1].children = []
  
    realData.forEach(item => {
      item.isLook = false
      item.isLeaf = true
      let noMatch = allFireElements.find( every=> every.id === item.FireElementId)
      if (!noMatch) {
        allFireElements[allFireElements.length-1].children.push(item)
      }
    })
    let treeData = [] //tree型 处理完成后的数据
    allFireElements.forEach(element => {
      element.key = element.id
      element.name != '其他' ? element.children = [] : null
      if(realData && realData.length != 0){
        realData.forEach(item => {
          if(element.id == item.FireElementId){
            element.children.push(item)
          }
        })
      }
      allFireElements.forEach(item => { if (item.parentId == element.id) {element.children.push(item)} });
    });
    allFireElements.forEach(element => {
      element.isLook = false
      if (!element.parentId) {
        element.isLook = false
        treeData.push(element) 
      }
    });
    function recursionFilterEmpty(originalList, result) {
        for(let i = 0, length = originalList.length; i < length; i++) {
            const item = originalList[i];
            if (item.PropertyInfos) {
                // 最内层
                result.push(item);
            } else if (item.children && item.children.length) {
                const newChildren = [];
                // 递归调用,底层的真实数据会全部 push 进 newChildren 中
                recursionFilterEmpty(item.children, newChildren);
                if (newChildren.length) {
                    // 替换原始数据
                    item.children = newChildren;
                    // 子项有真实的数据,就保留这一项
                    result.push(item);
                } // 如果没有这一项就会被删除
            }
        }
    }
    function filterEmpty(listData) {
        const result = [];
        recursionFilterEmpty(listData, result);
        return result;
    }
    return filterEmpty(treeData)

  }

  
  //陈鹏飞↓↓↓
  //陈鹏飞↓↓↓
  //陈鹏飞↓↓↓
  params = {companyId: sessionStorage.getItem('companyId')}
  allFireElements:any = []; //当前 单位/建筑 下的消防要素

  isShowAttribute:boolean = true; //属性栏 是否显示 默认数据
  isShowProperty:boolean = false //属性栏 是否有东西

  toggleExpandPanel:boolean = false; //左侧可展开面板展开或关闭
  toggleExpandPanelRight:boolean = false; //右侧可展开面板展开或关闭
  togglePlane:boolean = true; //可展开面板平面图 显隐
  toggleMaterialBank:boolean = true; //可展开面板素材库 显隐
  toggleHandlePlans:boolean = true; //可展开面板处置预案 显隐
  //可展开面板展开或关闭
  toggle () {
    this.toggleExpandPanel = !this.toggleExpandPanel
  }
  //可展开面板展开或关闭
  toggle2 () {
    this.toggleExpandPanelRight = !this.toggleExpandPanelRight
  }
  //可展开面板 平面图 展开或关闭
  togglePlanarGraph () {
    this.togglePlane = !this.togglePlane
  }
  //可展开面板 素材库 展开或关闭
  toggleMaterial () {
    this.toggleMaterialBank = !this.toggleMaterialBank
  }
  //可展开面板 处置预案 展开或关闭
  toggleHandlePlan () {
    this.toggleHandlePlans = !this.toggleHandlePlans
  }

  sitePlanData:any = []; //总平面图 楼层/区域 数据
  selectingSitePlan:any; //选中的 平面图 楼层/区域
  selectSitePlanIndex:number; //选中的 平面图 楼层/区域 index

  //获取总平面图
  getSitePlan () {
    let fireData = this.getFireElements(sessionStorage.getItem('buildingTypeId')) //获取单位下 消防要素
    let planData = this.getSitePlanCompanyData() //获取 单位 数据
    this.http.get('/api/SitePlans',{params:this.params}).subscribe(data=>{
      this.sitePlanData = data
      console.log('建筑楼层数据',this.sitePlanData)
      this.Facilities ? this.sitePlanData.forEach(item => {
        this.Facilities.forEach(i =>{
          if(item.id == i.key){
            item.isLabel = true 
          }
        })
      }) : null
      this.selectingSitePlan = this.sitePlanData[0] || {}
      this.canvasData.selectStorey = this.sitePlanData[0] || {} //服务中 存一份数据
      this.selectSitePlanIndex = 0
     
      Promise.all([fireData,planData]).then((res)=>{
        this.getSitePlanStorey(this.selectingSitePlan) //获取 平面图 楼层数据
      })

    })
  }

  //获取建筑 楼层/区域
  getBuildingSitePlan (item) {
    let params = { buildingId: item.id }
    let fireData = this.getFireElements(item.buildingTypes[0].id || '') //获取建筑下 消防要素
    let planData = this.getBuildingData(params) //获取 建筑 数据
    this.http.get('/api/BuildingAreas',{params}).subscribe(data=>{
      this.sitePlanData = data
      console.log('预案平台当前有哪些楼层',this.sitePlanData)
      this.Facilities ? this.sitePlanData.forEach(item => {
        this.Facilities.forEach(i =>{
          if(item.id == i.key){
            item.isLabel = true 
          }
        })
      }) : null
      this.selectingSitePlan = this.sitePlanData[0] || {}
      this.canvasData.selectStorey = this.sitePlanData[0] || {} //服务中 存一份数据
      this.selectSitePlanIndex = 0

      Promise.all([fireData,planData]).then((res)=>{
        this.getBuildingStorey(this.selectingSitePlan) //获取 建筑 楼层数据
      })

    })
  }

  //根据单位类型获得所有的消防要素
  getFireElements (e) {
    let params = {ids:e}
    return new Promise ((resolve,reject)=>{
      this.http.get('/api/Companies/FireElements',{params}).subscribe((data:any)=>{
        this.allFireElements = data //所有消防要素
        let other = {
          children: [],
          computed: true,
          id: '',
          name: '其他',
          order: 999,
          parentId: null,
          tag: "INPUT",
          isLookPattern : true
        }
        this.allFireElements.push(other)
        resolve('success')
      })
    })
  }

  //获取 单位 数据
  getSitePlanCompanyData () {
    return new Promise ((resolve,reject)=>{
      this.http.get('/api/CompanyData',{params:this.params}).subscribe((data:any)=>{
        this.canvasData.originalcompanyBuildingData = data || {} // 单位原数据
        this.canvasData.originalcompanyBuildingData.data? this.canvasData.originalcompanyBuildingData.data = JSON.parse(this.canvasData.originalcompanyBuildingData.data) : this.canvasData.originalcompanyBuildingData.data = {}
        this.canvasData.originalcompanyBuildingData.version? null : this.canvasData.originalcompanyBuildingData.version = "2.0"
        this.canvasData.originalcompanyBuildingData.companyId? null : this.canvasData.originalcompanyBuildingData.companyId = sessionStorage.getItem('companyId')
        resolve('success')
      })
    })
  }

  //获取 平面图 楼层数据
  originaleveryStoreyData:any
  getSitePlanStorey (e) {
    let params = {sitePlanId: e.id}
    this.http.get(`/api/SitePlanData`,{params}).subscribe((data:any)=>{
      console.log('预案平台楼层原始素材',data)
      this.originaleveryStoreyData = data
      this.canvasData.originaleveryStoreyData = JSON.parse(JSON.stringify(data))  || {} // 楼层原数据
      this.canvasData.originaleveryStoreyData.data? this.canvasData.originaleveryStoreyData.data = JSON.parse(this.canvasData.originaleveryStoreyData.data) : this.canvasData.originaleveryStoreyData.data = {}
      this.canvasData.originaleveryStoreyData.version? null : this.canvasData.originaleveryStoreyData.version = "2.0"
      this.canvasData.originaleveryStoreyData.sitePlanId? null : this.canvasData.originaleveryStoreyData.sitePlanId = e.id || null

      let examParams = {
        sitePlanId  : e.id,
        examinationId  : this.route.snapshot.queryParams.examId,
        planComponentId : this.route.snapshot.queryParams.planComponentId
      }
      this.http.get('/api/ExamSitePlanData',{params:examParams}).subscribe((data2:any)=>{
        console.log('考生新添加的基本信息素材数据',data2)
        this.canvasData.examOriginaleveryStoreyData = data2 || {} // 楼层原数据
        this.canvasData.examOriginaleveryStoreyData.data? this.canvasData.examOriginaleveryStoreyData.data = JSON.parse(this.canvasData.examOriginaleveryStoreyData.data) : this.canvasData.examOriginaleveryStoreyData.data = {}
        this.canvasData.examOriginaleveryStoreyData.version? null : this.canvasData.examOriginaleveryStoreyData.version = "2.0"
        this.canvasData.examOriginaleveryStoreyData.buildingAreaId? null : this.canvasData.examOriginaleveryStoreyData.buildingAreaId = e.id || null
        this.renovateTreeData()
            //如果有需要标注的平面图
        if(this.Facilities){
          this.Facilities.some((item,key)=>{
            if(item.key == this.selectingSitePlan.id){
              let arr = []
              item.children.forEach(i => {
                arr.push(i.Id)
              })
              this.hiddenBasicInfoFacilities = arr
              this.canvasData.hiddenBasicInfoFacilities = JSON.parse(JSON.stringify(arr)) 
              console.log('这层有需要标注的基本信息素材',item)
              let allFireElements = JSON.parse(JSON.stringify(this.allFireElements))
              this.renderData = []
              setTimeout(() => {
                this.renderData = [...this.processingData(allFireElements,item.children)]
              }, 0);
              this.canvas.onExamineeClickFloor()
              this.clickedNodeType = null
              return true 
            } else{
              if(key == this.Facilities.length - 1){
                this.renderData = []
                this.canvas.onExamineeClickFloor()
                return false 
              }
            }
          })
        }else{
          this.canvas.onExamineeClickFloor()
        }
      })
          //如果有需要标注的平面图
      


    })
  }
  //获取 建筑 楼层数据
  getBuildingStorey (e) {
    let params = {buildingAreaId: e.id}
    this.http.get(`/api/BuildingAreaData`,{params}).subscribe((data:any)=>{
      this.originaleveryStoreyData = data
      this.canvasData.originaleveryStoreyData = JSON.parse(JSON.stringify(data)) || {} // 楼层原数据
      this.canvasData.originaleveryStoreyData.data? this.canvasData.originaleveryStoreyData.data = JSON.parse(this.canvasData.originaleveryStoreyData.data) : this.canvasData.originaleveryStoreyData.data = {}
      this.canvasData.originaleveryStoreyData.version? null : this.canvasData.originaleveryStoreyData.version = "2.0"
      this.canvasData.originaleveryStoreyData.buildingAreaId? null : this.canvasData.originaleveryStoreyData.buildingAreaId = e.id || null
      let examParams = {
        buildingAreaId : e.id,
        examinationId : this.route.snapshot.queryParams.examId,
        planComponentId : this.route.snapshot.queryParams.planComponentId
      }
      this.http.get('/api/ExamBuildingAreaData',{params:examParams}).subscribe((data:any)=>{
        this.canvasData.examOriginaleveryStoreyData = data || {} // 楼层原数据
        this.canvasData.examOriginaleveryStoreyData.data? this.canvasData.examOriginaleveryStoreyData.data = JSON.parse(this.canvasData.examOriginaleveryStoreyData.data) : this.canvasData.examOriginaleveryStoreyData.data = {}
        this.canvasData.examOriginaleveryStoreyData.version? null : this.canvasData.examOriginaleveryStoreyData.version = "2.0"
        this.canvasData.examOriginaleveryStoreyData.buildingAreaId? null : this.canvasData.examOriginaleveryStoreyData.buildingAreaId = e.id || null
        this.renovateTreeData()
            //如果有需要标注的平面图
        if(this.Facilities){
          this.Facilities.some((item,key)=>{
            if(item.key == this.selectingSitePlan.id){
              let arr = []
              item.children.forEach(i => {
                arr.push(i.Id)
              })
              this.hiddenBasicInfoFacilities = arr
              this.canvasData.hiddenBasicInfoFacilities = JSON.parse(JSON.stringify(arr)) 
              console.log('这层有需要标注的基本信息素材',item)
              let allFireElements = JSON.parse(JSON.stringify(this.allFireElements))
              this.renderData = []
              setTimeout(() => {
                this.renderData = [...this.processingData(allFireElements,item.children)]
              }, 0);


              this.canvas.onExamineeClickFloor()
              this.clickedNodeType = null
            
              return true 
            } else{
              if(key == this.Facilities.length - 1){
                this.renderData = []
                this.canvas.onExamineeClickFloor()
                return false 
              }
            }
          })

        }else{
          this.canvas.onExamineeClickFloor()
        }
      })
    })
  }
  //获取 建筑 数据
  getBuildingData (e) {
    return new Promise ((resolve,reject)=>{
      this.http.get(`/api/BuildingData`,{params:e}).subscribe((data:any)=>{
        this.canvasData.originalcompanyBuildingData = data || {} // 建筑原数据
        this.canvasData.originalcompanyBuildingData.data? this.canvasData.originalcompanyBuildingData.data = JSON.parse(this.canvasData.originalcompanyBuildingData.data) : this.canvasData.originalcompanyBuildingData.data = {}
        this.canvasData.originalcompanyBuildingData.version? null : this.canvasData.originalcompanyBuildingData.version = "2.0"
        this.canvasData.originalcompanyBuildingData.buildingId? null : this.canvasData.originalcompanyBuildingData.buildingId = e.buildingId
        resolve('success')
      })
    })
  }

 

  //点击选中 平面图 楼层/区域 时
  selectSitePlan (item,index) {
    
    if (this.selectSitePlanIndex != index) {
      this.clickedNodeType = 1
      this.canvasData.selectPanelPoint = new DisposalNodeData();
      this.selectingSitePlan = item
      this.selectSitePlanIndex = index
      this.canvasData.selectStorey = item //服务中 存一份数据
      if (this.checkedBuildingIndex==-1) {  //总平面图时
        this.getSitePlanStorey(item) //获取 平面图 楼层数据
      } else {  //楼层/区域时
        this.getBuildingStorey(item) //获取 建筑 楼层数据
      }
    }
  }



  //删除当前 单位/建筑的 共享数据中 已删除data
  deleteShareData (e,isCompany) {
    this.sitePlanData.forEach((element,index) => {
      if (element.id===e.id) {
        this.sitePlanData.splice(index,1)
        return
      }
    });
    let data = this.canvasData.originalcompanyBuildingData;
    for(let key in data.data){
      if (data.data[key].FloorId === e.id) { //处理 单位/建筑 数据是否归于当前楼层下
        delete data.data[key]
      }
    }
    let newData = JSON.parse(JSON.stringify(this.canvasData.originalcompanyBuildingData));
    newData.data = JSON.stringify(newData.data) // 转换JSON 数据格式
    this.selectingSitePlan = this.sitePlanData[0] || {}
    this.canvasData.selectStorey = this.sitePlanData[0] || {} //服务中 存一份数据
    this.selectSitePlanIndex = 0
    this.canvasData.isChange = false
    if (isCompany===-1) {
      this.http.post("/api/CompanyData",newData).subscribe(data => {})
      this.getSitePlanStorey(this.selectingSitePlan) //获取 平面图 楼层数据
    } else {
      this.http.post("/api/BuildingData",newData,{params:this.params}).subscribe(data => {})
      this.getBuildingStorey(this.selectingSitePlan) //获取 建筑 楼层数据
    }
  }



  //处置预案
  examType = Number(this.route.snapshot.queryParams.openType)  // 预案类型  1=已存在/2=自定义
  allFirePlan:any = []; //所有灾情
  selectDisposalNode:string = ''; //当前点击tree节点 css选中样式

  //获取所有灾情
  getAllFirePlan () {
    let api
    this.examType == 1? api='/api/Disasters' : api='/api/ExamDisasters'
    let params = {componentId: this.route.snapshot.queryParams.planComponentId}
    this.http.get(api,{params:params}).subscribe((data:any)=>{
      if (!data.length) { //该 单位没有灾情时
        let msg = {
          name: '灾情',
          modifiedTime: new Date(),
          examPlanComponentId: sessionStorage.getItem('planId')
        }
        this.http.post('/api/ExamDisasters',msg).subscribe(data=>{ 
          this.allFirePlan.push(data)
          this.getDisposalNode()
        })
      } else { //单位 有灾情时
        this.allFirePlan = data
        this.getDisposalNode()
      }
    })
  }

  //获取所有处置节点
  getDisposalNode () {
    let api
    api='/api/ExamDisposalNodes'
    this.selectDisposalNode = ''
    let params
    params = {examDisasterId: this.allFirePlan[0].id || '',disposalNodeType:1,examinationId:this.route.snapshot.queryParams.examId}
    this.http.get(api,{params:params}).subscribe(data=>{ //处置节点
      this.canvasData.allDisposalNode = data
      this.getExaminationQuestions()
      this.handleHybridTree(this.canvasData.allDisposalNode,'答案')
    })
  }

  treeData:any = []; //渲染tree处理完成数据
  questionstreeData:any = [];//渲染tree处理完成数据(题目)
  defaultExpandedKeys:any = []; //首次渲染 tree展开状态
  //处理 节点 Tree数据
  handleHybridTree (disposalNodedata,type) {
    // this.defaultExpandedKeys = []
    let treeData = []
    let data =  JSON.parse(JSON.stringify( disposalNodedata || [] )) 
    data.forEach(element => {

      element.title = element.name //name
      element.key = element.id //id
      element.children = [] //children
      if (element.sitePlanId || element.buildingAreaId) { //是数据节点
        element.isLeaf = true
        element.isDataNode = true
      } else { //不是数据节点
        element.isLeaf = false
        element.isDataNode = false
      }
      data.forEach(item=>{
        item.parentId === element.id? element.children.push(item) : null
      })
    });
    data.forEach(element=>{
      !element.parentId? treeData.push(element) : null
    })
    type == '题目' ? this.questionstreeData = [...treeData] : this.treeData = [...treeData]
    
  }

  //刷新 treeData 保存已展开节点
  refurbishTreeData () {
    let api
    api='/api/ExamDisposalNodes'
    this.defaultExpandedKeys = []
    let params
    params = {examDisasterId: this.allFirePlan[0].id,disposalNodeType:1,examinationId:this.route.snapshot.queryParams.examId}
    this.http.get(api,{params:params}).subscribe(nodeData=>{ //处置节点
      this.canvasData.allDisposalNode = nodeData
      let oldTreeData = this.nzTreeComponent.getExpandedNodeList()
      oldTreeData.forEach(item=>{
        this.defaultExpandedKeys.push(item.key)
      })
      let treeData = []
      let data =  JSON.parse(JSON.stringify( this.canvasData.allDisposalNode || [] )) 
      data.forEach(element => {
        element.title = element.name //name
        element.key = element.id //id
        element.children = [] //children
        if (element.sitePlanId || element.buildingAreaId) { //是数据节点
          element.isLeaf = true
          element.isDataNode = true
        } else { //不是数据节点
          element.isLeaf = false
          element.isDataNode = false
        }
        data.forEach(item=>{
          item.parentId === element.id? element.children.push(item) : null
        })
      });
      data.forEach(element=>{
        !element.parentId? treeData.push(element) : null
      })
      this.treeData = [...treeData]
      this.defaultExpandedKeys = [...this.defaultExpandedKeys]
    })
  }


  // 切换 基本信息时  刷新  删除 建筑楼层 自定义属性
  mateDeleteCustomize () {
    this.defaultExpandedKeys = []
    this.sitePlanData.forEach(element => { //楼层
      delete element.fire
      delete element.force
    });
    this.allBuildings.forEach(element => { //建筑
      delete element.fire
      delete element.force
    });
  }

  //选择 考试节点
  countValue (e) {
    e.stopPropagation()
    if (this.canvasData.allDisposalNode.length) {
      let data = {treeData: JSON.parse( JSON.stringify(this.treeData) ), oldTreeData: JSON.parse( JSON.stringify(this.canvasData.allDisposalNode) )}
      let dialogRef = this.dialog.open(uploadDisposalNodesRead,{data});
      dialogRef.afterClosed().subscribe(data=>{
        if (data) {
          sessionStorage.setItem('examNodeList',JSON.stringify(data))
          const config = new MatSnackBarConfig();
          config.verticalPosition = 'top';
          config.duration = 3000
          this.snackBar.open('节点保存成功','确定',config);
        }
      })
    } else {
      const config = new MatSnackBarConfig();
      config.verticalPosition = 'top';
      config.duration = 3000
      this.snackBar.open('暂无处置节点','确定',config);
    }
  }



  clickedNodeType:any = 1//点击节点的类型 如果是考官节点 则为0  考生为1
  //点击 处置Tree节点
  selectanelPoint (e,type) {
    this.clickedNodeType = type
    if (!e.buildingAreaId && !e.sitePlanId) { //当前节点 不是 数据节点 时
      let msg = this.canvasData.findDisposalNode(e.id)
      this.canvasData.selectPanelPointBaseData = msg
      this.selectDisposalNode == msg.id? this.selectDisposalNode = '' : this.selectDisposalNode = msg.id //选中 节点

    } else if (e.buildingAreaId || e.sitePlanId) { //当前节点 是 数据节点 时
    
      let msg = this.canvasData.findDisposalNode(e.parentId)
      

      this.canvasData.selectPanelPointBaseData = msg
      this.selectDisposalNode = e.parentId //选中 节点

      this.Facilities ? this.sitePlanData.forEach(item => {
        this.Facilities.forEach(i =>{
          if(item.id == i.key){
            item.isLabel = true //标记当层需要标注基本信息素材
          }
        })
      }) : null

      if (this.canvasData.selectPanelPoint.DisposalNodeId != e.id) { //选择节点  不是当前节点时
        let api
        //如果是已存在预案
        if( this.examType == 1){
          type == 0 ? api='/api/DisposalNodeData' : api='/api/ExamDisposalNodeData'
        }else{ //如果是自定义预案
          api='/api/ExamDisposalNodeData'
        }
       
        let params = {nodeId: e.id}
        let parameter = { //查询 节点 对应 建筑/楼层 index,id
          buildingIndex: e.sitePlanId? -1 : this.allBuildings.findIndex(item=>{ return item.id===e.buildingId }), //总平面图/建筑 index
          storeyId: e.sitePlanId? e.sitePlanId : e.buildingAreaId, //楼层id
        }
        this.http.get(api,{params:params}).subscribe(data=>{
          // console.log('xixixi',data)
          this.canvasData.selectPanelPoint = this.canvasData.deserialize(JSON.stringify(data || new DisposalNodeData())) //选择 当前 节点
          
          this.canvasData.selectPanelPoint.Data = this.canvasData.deserialize(this.canvasData.selectPanelPoint.Data)
          // console.log(456,this.canvasData.selectPanelPoint.Data)
          this.seekPanelPoint(parameter)
        })
      } //if

    } //else if
  }

  //查找 数据节点 对应 建筑/楼层
  seekPanelPoint (paramsData) {
    this.checkedBuildingIndex = paramsData.buildingIndex
    if (paramsData.buildingIndex ==-1) { //总平面图时
      this.beforeOneCheckedBuilding={name:"总平面图"}
      let fireData = this.getFireElements(sessionStorage.getItem('buildingTypeId')) //获取单位下 消防要素
      let planData = this.getSitePlanCompanyData() //获取 单位 数据
      this.http.get('/api/SitePlans',{params:this.params}).subscribe(data=>{
        this.sitePlanData = data
        let index = this.sitePlanData.findIndex(item=>{ return item.id===paramsData.storeyId })
        this.selectingSitePlan = this.sitePlanData[index] || {}
        this.canvasData.selectStorey = this.sitePlanData[index] || {} //服务中 存一份数据
        this.selectSitePlanIndex = index
  
        this.Facilities ? this.sitePlanData.forEach(item => {
          this.Facilities.forEach(i =>{
            if(item.id == i.key){
              item.isLabel = true 
            }
          })
        }) : null
        Promise.all([fireData,planData]).then((res)=>{
          this.getSitePlanStorey(this.selectingSitePlan) //获取 平面图 楼层数据
        })
      }) //get
      
    } else { //建筑时
      this.beforeOneCheckedBuilding=this.allBuildings[paramsData.buildingIndex]
      let params = { buildingId: this.beforeOneCheckedBuilding.id }
      let fireData = this.getFireElements(this.beforeOneCheckedBuilding.buildingTypes[0].id || '') //获取建筑下 消防要素
      let planData = this.getBuildingData(params) //获取 建筑 数据
      this.http.get('/api/BuildingAreas',{params}).subscribe(data=>{
        this.sitePlanData = data
        let index = this.sitePlanData.findIndex(item=>{ return item.id===paramsData.storeyId })
        this.selectingSitePlan = this.sitePlanData[index] || {}
        this.canvasData.selectStorey = this.sitePlanData[index] || {} //服务中 存一份数据
        this.selectSitePlanIndex = index
        this.Facilities ? this.sitePlanData.forEach(item => {
          this.Facilities.forEach(i =>{
            if(item.id == i.key){
              item.isLabel = true 
            }
          })
        }) : null 
        Promise.all([fireData,planData]).then((res)=>{
          this.getBuildingStorey(this.selectingSitePlan) //获取 建筑 楼层数据
        })
      }) //get
    }
  }



}




//查看需要标记的消防设施按钮
@Component({
  selector: 'score',
  templateUrl: './score.html',
  styleUrls: ['./score.scss',]
})
export class Score {

    constructor(private http:HttpClient, public dialog: MatDialog, public snackBar: MatSnackBar, public dialogRef: MatDialogRef<any>,
    @Inject(MAT_DIALOG_DATA) public data) {}

    score:any
    scoreNum:any = sessionStorage.getItem('scoreNum') || ''
    ngOnInit(): void {
      console.log(this.data)
      this.score = '请输入分数 ( 此试题满分为' +  this.data.score + '分 ) '
    }

    isSave:boolean = false
    inputNum(){
      if(this.scoreNum > this.data.score){
        // this.scoreNum = this.data.score
        const config = new MatSnackBarConfig();
        config.verticalPosition = 'top';
        config.duration = 3000
        this.snackBar.open('超出最大分值!','确定',config);
      }
      if(this.scoreNum < 0){
        // this.scoreNum = 0
        const config = new MatSnackBarConfig();
        config.verticalPosition = 'top';
        config.duration = 3000
        this.snackBar.open('分数不能为负数!','确定',config);
      }
    }
    ok(){
      if(this.scoreNum > this.data.score){
        const config = new MatSnackBarConfig();
        config.verticalPosition = 'top';
        config.duration = 3000
        this.snackBar.open('超出最大分值!','确定',config);
      }
      if(this.scoreNum < 0){
        // this.scoreNum = 0
        const config = new MatSnackBarConfig();
        config.verticalPosition = 'top';
        config.duration = 3000
        this.snackBar.open('分数不能为负数!','确定',config);
      }
      if(this.scoreNum >= 0 && this.scoreNum < this.data.score){
        sessionStorage.setItem('scoreNum',this.scoreNum)
        this.dialogRef.close()
      }
    }
}