import { SelectionModel } from '@angular/cdk/collections';
import { HttpClient } from '@angular/common/http';
import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { MatSnackBar, MatSnackBarConfig } from '@angular/material/snack-bar';
import { NzDatePickerModule } from 'ng-zorro-antd/date-picker';
import { DisabledTimeFn, DisabledTimePartial } from 'ng-zorro-antd/date-picker';
import getISOWeek from 'date-fns/getISOWeek';
import setHours from 'date-fns/setHours';
import { NzFormatEmitEvent, NzTreeComponent } from 'ng-zorro-antd/tree';
import { Router } from '@angular/router';
@Component({
  selector: 'app-create-test-score',
  templateUrl: './create-test-score.component.html',
  styleUrls: ['./create-test-score.component.scss']
})
export class CreateTestScoreComponent implements OnInit {

  constructor(private router:Router,public dialog: MatDialog,private http: HttpClient,public snackBar: MatSnackBar) { }
  selectedTab:number = 1 //选中的选项卡
  selectTab(index){
    setTimeout(() => {
      this.selectedTab = index
    }, 0);
   
  }
  ngOnInit(): void {
    for (let y = 0, length = this.unitId.length; y < length; y++){
      let element = this.unitId[y]
      element.score = 0
      element.basicInfoScore = 0
      element.basicInfoItemScore = 0
      element.basicInfoNodes = []
      element.aroundScore = 0
      element.aroundItemScore = 0
      element.aroundNodes = []
      element.keySiteScore = 0
      element.keySiteItemScore = 0
      element.keySiteNodes = []
      element.funDivScore = 0
      element.funDivItemScore = 0
      element.funDivNodes = []
      element.fireFacScore = 0
      element.fireFacItemScore = 0
      element.fireFacNodes = []
    }
    this.getUnitData().then(()=>{
      this.getAround().then(()=>{
        this.getKeySite().then(()=>{
          this.getFunDiv().then(()=>{
            this.getFireFac()
          })
        })
      })
    })
  }
  //当前选中的单位
  selectedUnitIndex = 0
  clickUnitName(key){
    this.selectedUnitIndex = key
  }
  unitId:any = JSON.parse(sessionStorage.getItem('checkedWork')) 

  //获取单位基本信息
  async getUnitData(){
    let that = this
    for (let y = 0, length = this.unitId.length; y < length; y++){
      let element = this.unitId[y]
      
      let result1 = await new Promise((resolve, reject) => {
        this.http.get(`/api/Companies/${element.id}`).subscribe((data:any)=>{
          let unitData = {
            name: '单位信息',
            type:'基本信息',
            expanded: true,
            key:(Math.random()*10000000).toString(16).substr(0,4)+(new Date()).getTime()+Math.random().toString().substr(2,5),
            children:[]
          }
          data.usci ? unitData.children.push({
            name: '统一社会信用代码',key: element.id+'统一社会信用代码',isLeaf:true,value:data.usci
          }) : null
          data.buildingTypes[0].name ? unitData.children.push({
            name: '单位类型',key: element.id+'单位类型',isLeaf:true,value:data.buildingTypes[0].name
          }) : null
          data.contacts ? unitData.children.push({
            name: '联系人',key: element.id+'联系人',isLeaf:true,value:data.contacts
          }) : null
          data.phone ? unitData.children.push({
            name: '联系电话',key: element.id+'联系电话',isLeaf:true,value:data.phone
          }) : null
          data.organizationName ? unitData.children.push({
            name: '辖区中队',key: element.id+'辖区中队',isLeaf:true,value:data.organizationName
          }) : null
          data.address ? unitData.children.push({
            name: '单位地址',key: element.id+'单位地址',isLeaf:true,value:data.address
          }) : null
    
          
          element.basicInfoNodes.push(unitData)

          resolve(1)
        }) 
      }).then(async ()=>{
        let result2 = await new Promise((resolve, reject) => {
          var buildingsData:any
          this.http.get("/api/Buildings",{
            params:{
              companyId:element.id
            }
          }).subscribe(async (data:any)=>{
            await getAllBuildingData(data)
            resolve(2)
          })
        })
      })
      async function getAllBuildingData(data){
        for (let i = 0, length = data.length; i < length; i++){
          const result = await new Promise((resolve) =>{
            that.http.get("/api/BuildingBasicInfos",{ // 循环请求当前单位建筑每一个建筑的信息保存到数组中
              params:{
                companyId :element.id,
                buildingId:data[i].id,
                buildingType:data[i].buildingTypes[0].id
              }
            }).subscribe((buildingsData:any)=>{
              buildingsData.name = data[i].name
              buildingsData.buildingType = data[i].buildingTypes[0].name
              buildingsData[0].buildingBasicGroups.forEach((y,m) => {
                let propertyInfosArr = []
                let tabledata
                if(y.type == 1){//如果是表格类
                  var map = {},
                  dest:any = [];
                  for(var i = 0; i < y.propertyInfos.length; i++){
                      var ai = y.propertyInfos[i];
                      if(!map[ai.propertyName]){
                          dest.push({
                              propertyName: ai.propertyName,
                              data: [ai]
                          });
                          map[ai.propertyName] = ai;
                      }else{
                          for(var j = 0; j < dest.length; j++){
                              var dj = dest[j];
                              if(dj.propertyName == ai.propertyName){
                                  dj.data.push(ai);
                                  break;
                              }
                          }
                      }
                  }
                  //根据行数确定在循环数组中的index
                  dest.forEach(item => {
                    item.data.sort(function(a,b){
                      return Number(a.tag) - Number(b.tag) 
                    })
                  })
                  y.tabledata = dest
                  tabledata = dest
                  y.tabledata[0].data.forEach((x,key) => {
                    if(x.propertyValue){
                      x.key = (Math.random()*10000000).toString(16).substr(0,4)+(new Date()).getTime()+Math.random().toString().substr(2,5)
                      x.isLeaf = true
                      x.name = x.propertyValue
                      propertyInfosArr.push(x)
                    }
                  })
                }else{
                  y.propertyInfos.forEach((x,key) => {
                    if(x.propertyValue){
                      x.key = (Math.random()*10000000).toString(16).substr(0,4)+(new Date()).getTime()+Math.random().toString().substr(2,5)
                      x.isLeaf = true
                      x.name = x.propertyName
                      propertyInfosArr.push(x)
                    }
                  })
                }
                if(propertyInfosArr.length != 0){
                  element.basicInfoNodes.push({
                    name:y.name != '基本信息' ? buildingsData.name + '-' + y.name : buildingsData.name ,
                    type:'基本信息',
                    expanded: true,
                    key:(Math.random()*10000000).toString(16).substr(0,4)+(new Date()).getTime()+Math.random().toString().substr(2,5),
                    children:propertyInfosArr,
                    tabledata:tabledata ? tabledata : null
                  })
                  element.basicInfoNodes = [...element.basicInfoNodes]
                }
                
              })
              resolve(i)
            })
          })
        }
      }

    }
  }
  //获取四周毗邻数据
  async getAround(){
    let that = this
    for (let y = 0, length = this.unitId.length; y < length; y++){
      let element = this.unitId[y]
      
      //获得当前单位的单位毗邻
      let id = {companyId:element.id}
      let result1 = await new Promise((resolve, reject) => {
        this.http.get('/api/CompanyAdjoins',{params:id}).subscribe((data:any)=>{
          data.forEach(item => {
            item.direction == 0 ? item.title = '东方向' : null
            item.direction == 1 ? item.title = '西方向' : null
            item.direction == 2 ? item.title = '南方向' : null
            item.direction == 3 ? item.title = '北方向' : null
            item.direction == 4 ? item.title = '东南方向' : null
            item.direction == 5 ? item.title = '西南方向' : null
            item.direction == 6 ? item.title = '东北方向' : null
            item.direction == 7 ? item.title = '西北方向' : null
            item.isLeaf = true,
            item.key = item.id
          })
          //如果存在单位毗邻
          if(data.length != 0){
            this.unitId[y].aroundNodes.push({
              name: '单位毗邻',
              key: (Math.random()*10000000).toString(16).substr(0,4)+(new Date()).getTime()+Math.random().toString().substr(2,5),
              expanded: true,
              type:'四周毗邻',
              children: data
            })
            element.aroundNodes = [...element.aroundNodes]
          }
          resolve(1)
        })
      }).then(async ()=>{
        //获得当前单位的建筑毗邻
        let result2 = await new Promise((resolve, reject) => {
          this.http.get('/api/Buildings',{params:id}).subscribe(async (data:any)=>{
            if (data.length) {   
            await getAllArchitecture(data)
            resolve(2)
            }
          })
        })
      })
      async function getAllArchitecture(buildingsdata){
        for (let i = 0, length = buildingsdata.length; i < length; i++){
          let id = {buildingId:buildingsdata[i].id}
          let result = await new Promise((resolve, reject) => {
            that.http.get('/api/BuildingAdjoins',{params:id}).subscribe((data:any)=>{
              data.forEach(item => {
                item.direction == 0 ? item.title = '东方向' : null
                item.direction == 1 ? item.title = '西方向' : null
                item.direction == 2 ? item.title = '南方向' : null
                item.direction == 3 ? item.title = '北方向' : null
                item.direction == 4 ? item.title = '东南方向' : null
                item.direction == 5 ? item.title = '西南方向' : null
                item.direction == 6 ? item.title = '东北方向' : null
                item.direction == 7 ? item.title = '西北方向' : null
                item.isLeaf = true
                item.key = item.id
              })
              if(data.length != 0){
                that.unitId[y].aroundNodes.push({
                  name: buildingsdata[i].name,
                  key: (Math.random()*10000000).toString(16).substr(0,4)+(new Date()).getTime()+Math.random().toString().substr(2,5),
                  expanded: true,
                  type:'四周毗邻',
                  children: data
                })
                element.aroundNodes = [...element.aroundNodes]
              }
              resolve(1)
            })
          })  
        }

      }
    }
  }
  //获取重点部位
  async getKeySite(){
    let that = this
    for (let y = 0, length = this.unitId.length; y < length; y++){
      let element = this.unitId[y]
     
      //获得单位重点部位
      let id = {companyId:element.id}

      let result1 = await new Promise((resolve, reject) => {
        this.http.get('/api/CompanyImportantLocations',{params:id}).subscribe((data:any)=>{
          //如果存在单位毗邻
          let newData = []
          data.forEach(item => {
            item.isLeaf = true
            item.key = item.id
            item.name ? newData.push(item) : null
          })
          if(data.length != 0){
            this.unitId[y].keySiteNodes.push({
              name: '单位重点部位',
              key: (Math.random()*10000000).toString(16).substr(0,4)+(new Date()).getTime()+Math.random().toString().substr(2,5),
              expanded: true,
              type:'重点部位',
              children: newData
            })
            element.keySiteNodes = [...element.keySiteNodes]
          }
          resolve(1)
        })
      }).then(async ()=>{
        //获得建筑重点部位
        let result2 = await new Promise((resolve, reject) => {
          this.http.get('/api/Buildings',{params:id}).subscribe(async (data:any)=>{
            if (data.length) {   
              await getAllBuildingPositon(data)
              resolve(2)
            }
          })
        })
        
      })
      



      
      //获取当前单位所有建筑重点部位
      async function getAllBuildingPositon (buildingsdata) {
        for (let i = 0, length = buildingsdata.length; i < length; i++){
          let id = {buildingId:buildingsdata[i].id}
          let result = await new Promise((resolve, reject) =>{
            that.http.get('/api/BuildingImportantLocations',{params:id}).subscribe((data:any)=>{
              let newData = []
              data.forEach(item => {
                item.isLeaf = true
                item.key = item.id
                item.name ? newData.push(item) : null
              })
              if(newData.length != 0){
                that.unitId[y].keySiteNodes.push({
                  name: buildingsdata[i].name,
                  key: (Math.random()*10000000).toString(16).substr(0,4)+(new Date()).getTime()+Math.random().toString().substr(2,5),
                  expanded: true,
                  type:'重点部位',
                  children: newData
                })
                element.keySiteNodes = [...element.keySiteNodes]
              }
              resolve('2')
            })
          })
          
        }
      }
    } 
  }
  //获取功能分区
  async getFunDiv(){
    let that = this
    for (let y = 0, length = this.unitId.length; y < length; y++){
      let element = this.unitId[y]
     
      let id = {companyId:element.id}
      //单位功能分区
      let result1 = await new Promise((resolve, reject) => {
        this.http.get('/api/CompanyFunctionalDivisions',{params:id}).subscribe((data:any)=>{
          //如果存在单位的单位功能分区
          let newData = []
          data.forEach(item => {
            item.isLeaf = true
            item.key = item.id
            item.region ? newData.push(item) : null
          })
          if(data.length != 0){
            this.unitId[y].funDivNodes.push({
              name: '单位功能分区',
              key: (Math.random()*10000000).toString(16).substr(0,4)+(new Date()).getTime()+Math.random().toString().substr(2,5),
              expanded: true,
              type:'功能分区',
              children: newData
            })
            element.funDivNodes = [...element.funDivNodes]
          } 
          resolve(1)
        })
      }).then(async ()=>{
        //建筑功能分区
        let result2 = await new Promise((resolve, reject) => {
          this.http.get('/api/Buildings',{params:id}).subscribe(async (data:any)=>{
            if (data.length) {   
              await getAllBuildingFunDiv(data)
              resolve(2)
            }
          })
        })
      })
      
      
      
      
      //获取当前单位所有建筑功能分区
      async function getAllBuildingFunDiv (buildingsdata) {
        for (let i = 0, length = buildingsdata.length; i < length; i++){
          let id = {buildingId:buildingsdata[i].id}
          let result = await new Promise((resolve, reject) =>{
            that.http.get('/api/BuildingFunctionalDivisions',{params:id}).subscribe((data:any)=>{
              let newData = []
              data.forEach(item => {

                item.isLeaf = true
                item.key = item.id
                item.region ? newData.push(item) : null

              })
              if(newData.length != 0){
                that.unitId[y].funDivNodes.push({
                  name: buildingsdata[i].name,
                  key: (Math.random()*10000000).toString(16).substr(0,4)+(new Date()).getTime()+Math.random().toString().substr(2,5),
                  expanded: true,
                  type:'功能分区',
                  children: newData
                })
                element.funDivNodes = [...element.funDivNodes]
              }
              resolve('2')
            })
          })
          
        }
      }

    }
  }
  //获取消防设施
  getFireFac(){
    let that = this
    this.unitId.forEach((element,index) =>{
     
      let companyId  = element.id
      //获取单位级别消防设施
      this.http.get(`/api/Companies/${companyId}`).subscribe((data:any)=>{
        if (data.buildingTypes.length) {
          let newData = {buildingType: data.buildingTypes[0].id,companyId : companyId}
          this.http.get('/api/CompanyFacilities',{params:newData}).subscribe((data:any)=>{ //获得单位的消防设施
            
            data[0].summary.companyFacilityGroups.forEach(element => { //循环单位内置分组项
              element.facilityItems.forEach((elements,index) => {
                elements.total = element.facilityCount[index]
              });
            });
            let newData = []
            data[0].summary.companyFacilityGroups.forEach(item => {
              item.facilityItems.forEach(i => {
                i.isLeaf = true
                i.key = (Math.random()*10000000).toString(16).substr(0,4)+(new Date()).getTime()+Math.random().toString().substr(2,5),
                (i.total && (i.total!= '总数:0' && i.total!= '总数:0')) ? newData.push(i) : null
              })
            })
            if(newData.length != 0){
              this.unitId[index].fireFacNodes.push({
                name: '单位消防设施',
                key: (Math.random()*10000000).toString(16).substr(0,4)+(new Date()).getTime()+Math.random().toString().substr(2,5),
                expanded: true,
                type:'消防设施',
                children: newData
              })
              element.fireFacNodes = [...element.fireFacNodes]
            }
          }) 
        } 
      })

      //获取各建筑消防设施
      this.http.get('/api/Buildings',{params:{
        companyId:companyId
      }}).subscribe((data:any)=>{
        if (data.length != 0) { getAllBuildingFireFac(data) }
      })

      async function getAllBuildingFireFac (buildingsdata) {
        // console.log('建筑'+index,buildingsdata)
        for (let i = 0, length = buildingsdata.length; i < length; i++){
          let header = {buildingId: buildingsdata[i].id, buildingType: buildingsdata[i].buildingTypes[0].id,companyId:buildingsdata[i].companyId}
          let result = await new Promise((resolve, reject) =>{
            that.http.get('/api/BuildingFacilities',{params:header}).subscribe((data:any)=>{
              // console.log(index+'消防设施'+ i,data)

              data[0].summary.buildingFacilityGroups.forEach(element => { //循环单位内置分组项
                element.facilityItems.forEach((elements,index) => {
                  elements.total = element.facilityCount[index]
                });
              });
              let newData = []
              data[0].summary.buildingFacilityGroups.forEach(item => {
                item.facilityItems.forEach(i => {
                  i.isLeaf = true
                  i.key = (Math.random()*10000000).toString(16).substr(0,4)+(new Date()).getTime()+Math.random().toString().substr(2,5),
                  (i.total && (i.total!= '总数:0' && i.total!= '总数:0')) ? newData.push(i) : null
                })
              })
              if(newData.length != 0){
                that.unitId[index].fireFacNodes.push({
                  name: buildingsdata[i].name,
                  key: buildingsdata[i].id,
                  expanded: true,
                  type:'消防设施',
                  children: newData
                })
                element.fireFacNodes = [...element.fireFacNodes]
              }
              resolve('消防设施')
            })
          })
          
        }
      }
    })
  }

  //查看树节点
  lookTreeNode(node){
    const dialogRef = this.dialog.open(LookTreeNodeDialog, {
      id:'lookTreeNode',
      data: node.origin
    });
    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
    });
  }

  //阻止input事件冒泡
  stopPropagation($event){
    $event.stopPropagation()
  }
  defaultCheckedKeys = []; //指定选中复选框的树节点 key值
  defaultExpandedKeys = []; //展开指定的树节点 key值
  defaultSelectedKeys = []; //指定选中的树节点 key值

  examScore:any = 0//整个试卷的总分
  
  

  //计算分数
  calculateScore(key){
    //key代表第几个建筑
    //计算整个单位的总分
    this.unitId[key].score = this.unitId[key].basicInfoScore + this.unitId[key].aroundScore + this.unitId[key].keySiteScore + this.unitId[key].funDivScore + this.unitId[key].fireFacScore  

   //计算整个试卷的总分
    let examScore = 0
    this.unitId.forEach(element => {
      examScore += element.score
    })
    let examScore2 = 0
    this.unitId.forEach(element => {
      let x = 0
      if(element.planList){
        element.planList.forEach(i => {
          x += i.score
        })
      }
      examScore2 += Number(x) 
    })
    this.examScore = examScore + examScore2
  }

  //tree的选择事件
  nzEvent(event: NzFormatEmitEvent,key): void {

      if(event.node.origin.type == '基本信息' || (event.node.parentNode && event.node.parentNode.origin.type == '基本信息')){

        let selectedNum = []
        this.unitId[key].basicInfoNodes.forEach(item => {
          item.children.forEach(i => {
            i.checked ? selectedNum.push(i) : ''
          })
        })
        if(selectedNum.length != 0 ){
          this.unitId[key].basicInfoScore ? this.unitId[key].basicInfoItemScore = this.unitId[key].basicInfoScore / selectedNum.length : null
        }else{
          this.unitId[key].basicInfoItemScore = 0
        }
      }
      if(event.node.origin.type == '四周毗邻' || (event.node.parentNode && event.node.parentNode.origin.type == '四周毗邻')){
        let selectedNum = []
        this.unitId[key].aroundNodes.forEach(item => {
          item.children.forEach(i => {
            i.checked ? selectedNum.push(i) : ''
          })
        })
        if(selectedNum.length != 0 ){
          this.unitId[key].aroundScore ? this.unitId[key].aroundItemScore = this.unitId[key].aroundScore / selectedNum.length : null
        }else{
          this.unitId[key].aroundItemScore = 0
        }
      }
      if(event.node.origin.type == '重点部位' || (event.node.parentNode && event.node.parentNode.origin.type == '重点部位')){
        let selectedNum = []
        this.unitId[key].keySiteNodes.forEach(item => {
          item.children.forEach(i => {
            i.checked ? selectedNum.push(i) : ''
          })
        })
        if(selectedNum.length != 0 ){
          this.unitId[key].keySiteScore ? this.unitId[key].keySiteItemScore = this.unitId[key].keySiteScore / selectedNum.length : null
        }else{
          this.unitId[key].keySiteItemScore = 0
        }
      }
      if(event.node.origin.type == '功能分区' || (event.node.parentNode && event.node.parentNode.origin.type == '功能分区')){
        let selectedNum = []
        this.unitId[key].funDivNodes .forEach(item => {
          item.children.forEach(i => {
            i.checked ? selectedNum.push(i) : ''
          })
        })
        if(selectedNum.length != 0 ){
          this.unitId[key].funDivScore  ? this.unitId[key].funDivItemScore  = this.unitId[key].funDivScore  / selectedNum.length : null
        }else{
          this.unitId[key].funDivItemScore  = 0
        }
      }
      if(event.node.origin.type == '消防设施' || (event.node.parentNode && event.node.parentNode.origin.type == '消防设施')){
        let selectedNum = []
        this.unitId[key].fireFacNodes.forEach(item => {
          item.children.forEach(i => {
            i.checked ? selectedNum.push(i) : ''
          })
        })
        if(selectedNum.length != 0 ){
          this.unitId[key].fireFacScore   ? this.unitId[key].fireFacItemScore   = this.unitId[key].fireFacScore   / selectedNum.length : null
        }else{
          this.unitId[key].fireFacItemScore   = 0
        }
      }
  }

  //单位各项总分数动态计算
  sumScore(type,key){
    //key代表第几个建筑 type代表哪个部分
    if(type == '基本信息'){
      let selectedNum = 0
      this.unitId[key].basicInfoNodes.forEach(item => {
        item.children.forEach(i => {
          i.checked ? selectedNum++ : ''
        })
      })
      if(selectedNum != 0){
        this.unitId[key].basicInfoItemScore = this.unitId[key].basicInfoScore / selectedNum
      }else{
        this.unitId[key].basicInfoItemScore = 0
      }
    }
    if(type == '四周毗邻'){
      let selectedNum = 0
      this.unitId[key].aroundNodes.forEach(item => {
        item.children.forEach(i => {
          i.checked ? selectedNum++ : ''
        })
      })
      if(selectedNum != 0){
        this.unitId[key].aroundItemScore = this.unitId[key].aroundScore / selectedNum
      }else{
        this.unitId[key].aroundItemScore = 0
      }
    }
    if(type == '重点部位'){
      let selectedNum = 0
      this.unitId[key].keySiteNodes.forEach(item => {
        item.children.forEach(i => {
          i.checked ? selectedNum++ : ''
        })
      })
      if(selectedNum != 0){
        this.unitId[key].keySiteItemScore = this.unitId[key].keySiteScore / selectedNum
      }else{
        this.unitId[key].keySiteItemScore = 0
      }
    }
    if(type == '功能分区'){
      let selectedNum = 0
      this.unitId[key].funDivNodes.forEach(item => {
        item.children.forEach(i => {
          i.checked ? selectedNum++ : ''
        })
      })
      if(selectedNum != 0){
        this.unitId[key].funDivItemScore = this.unitId[key].funDivScore / selectedNum
      }else{
        this.unitId[key].funDivItemScore = 0
      }
    }
    if(type == '消防设施'){
      let selectedNum = 0
      this.unitId[key].fireFacNodes.forEach(item => {
        item.children.forEach(i => {
          i.checked ? selectedNum++ : ''
        })
      })
      if(selectedNum != 0){
        this.unitId[key].fireFacItemScore = this.unitId[key].fireFacScore  / selectedNum
      }else{
        this.unitId[key].fireFacItemScore = 0
      }
    }
    this.calculateScore(key)//更新标题栏分数
    
  }

  //添加预案
  addPlan(){
    let companyData = {
      companyData : this.unitId[this.selectedUnitIndex]
    }
    const dialogRef = this.dialog.open(AddPlanDialog, {
      width: '380px',
      height: '136px',
      data: companyData
    });

    dialogRef.afterClosed().subscribe(result => {
      if(result){
        if(this.unitId[this.selectedUnitIndex].planList){
          this.unitId[this.selectedUnitIndex].planList.push(result)
        }else{
          this.unitId[this.selectedUnitIndex].planList = [] 
          this.unitId[this.selectedUnitIndex].planList.push(result)
        }
      }
    });
  }
  //每条预案分数增加在试卷分数
  planItemScore(item){
    //计算整个试卷的总分
    console.log(item)
    let examScore = 0
    this.unitId.forEach(element => {
      examScore += element.score
    })
    let examScore2 = 0
    this.unitId.forEach(element => {
      let x = 0
      if(element.planList){
        element.planList.forEach(i => {
          x += i.score
        })
      }
      examScore2 += Number(x) 
    })
    this.examScore = examScore + examScore2
  }
  //编辑每条预案试卷
  edit(item){
    const config = new MatSnackBarConfig();
    config.verticalPosition = 'top';
    config.duration = 3000
    this.snackBar.open('暂不能编辑','确定',config);
  }
  //删除每条预案试卷
  deletePlan(item){
    this.unitId[this.selectedUnitIndex].planList.forEach((element,key)=>{
      if(item == element){
        this.unitId[this.selectedUnitIndex].planList.splice(key,1)
      }
    })
    const config = new MatSnackBarConfig();
    config.verticalPosition = 'top';
    config.duration = 3000
    this.snackBar.open('删除成功','确定',config);
  }
  //保存
  save(){
     let copyDatas = JSON.parse(JSON.stringify(this.unitId))
     
     //循环每个建筑处理数据筛选出选中数据
     copyDatas.forEach(item => {
        //建筑的基本信息模块处理
        item.basicInfoNodes.forEach((i,key) => {
          //如果顶级节点未选中则需要筛除没有选中的数据
          if(!i.checked){
            // console.log(i)
            let newArr = []
            i.children.forEach(element => {
              element.checked ? newArr.push(element) : null
            })
            let discard = []//即将废弃的数组
            // newArr.length == 0 ? item.basicInfoNodes.splice(key,1) : i.children = newArr
            newArr.length == 0 ? discard.push(i) : i.children = newArr
            item.basicInfoNodes = item.basicInfoNodes.filter(items => {
              if (!discard.includes(items)) return items;
            })
          } 
          //将children处理成指定形式
          if(i.name =='单位信息'){
            let newChildren = []
            i.children.forEach((element,index) => {
              let newChildrenItem:any= {}
              newChildrenItem.name = element.name//题目名称
              newChildrenItem.result = element.value//题目答案
              newChildrenItem.physicalUnit = element.physicalUnit || ''//计量单位
              newChildrenItem.propertyType = 0//输入框类型
              newChildren.push(newChildrenItem)
            })
            i.children = newChildren
          }else if(!i.tabledata){
            let newChildren = []
            i.children.forEach((element,index) => {
              let newChildrenItem:any= {}
              newChildrenItem.name = element.propertyName//题目名称
              newChildrenItem.result = element.propertyValue//题目答案
              newChildrenItem.physicalUnit = element.physicalUnit || ''//计量单位
              newChildrenItem.propertyType = element.propertyType//输入框类型
              newChildren.push(newChildrenItem)
            })
            i.children = newChildren
          }else if(i.tabledata){//如果是表格类
            let newChildren = []
            i.children.forEach((element,index) => {
              let newChildrenItem:any= {}
              newChildrenItem.name = element.propertyValue//题目名称
              newChildrenItem.result = element.tag//代表第几行
              newChildrenItem.physicalUnit = ''//计量单位
              newChildrenItem.propertyType = ''//输入框类型
              newChildren.push(newChildrenItem)
            })
            i.children = newChildren
            i.tabledata.forEach(element => {
              let newData = []
              element.data.forEach(ele => {
                let newObj:any = {}
                newObj.name = ele.propertyName//题目名称
                newObj.result = ele.propertyValue//代表第几行
                newObj.physicalUnit = ele.physicalUnit//计量单位
                newObj.propertyType = ele.propertyType//输入框类型
                newObj.tag = ele.tag//第几行
                newData.push(newObj)
              })
              element.data = newData
            })
          }
          delete i.selected

        })
        //建筑的四周毗邻模块处理
        item.aroundNodes.forEach((i,key) => {
          //如果顶级节点未选中则需要筛除没有选中的数据
          if(!i.checked){
            let newArr = []
            i.children.forEach(element => {
              element.checked ? newArr.push(element) : null
            })
            let discard = []//即将废弃的数组
            newArr.length == 0 ? discard.push(i) : i.children = newArr
            item.aroundNodes = item.aroundNodes.filter(items => {
              if (!discard.includes(items)) return items;
            })
          }
          let newChildren = []
          i.children.forEach((element,index) => {
            let newChildrenItem:any= {}
            newChildrenItem.name = element.title//题目名称
            newChildrenItem.result = element.name//题目答案
            newChildrenItem.physicalUnit = ''//计量单位
            newChildrenItem.propertyType = 0//输入框类型
            newChildren.push(newChildrenItem)
          })
          i.children = newChildren
          delete i.selected
        })
        console.log(111,item)
        //建筑的重点部位模块处理
        item.keySiteNodes ? item.keySiteNodes.forEach((i,key) => {
          i.selected ?  i.selected = null : null
          //如果顶级节点未选中则需要筛除没有选中的数据
          if(!i.checked){
            let newArr = []
            i.children.forEach(element => {
              element.checked ? newArr.push(element) : null
            })
            let discard = []//即将废弃的数组
            newArr.length == 0 ? discard.push(i) : i.children = newArr
            item.keySiteNodes = item.keySiteNodes.filter(items => {
              if (!discard.includes(items)) return items;
            })
          }
          i.tabledata = [{propertyName: "重点部位名称",data:[]},
          {propertyName: "重点部位所在位置",data:[]},
          {propertyName: "建筑结构",data:[]},
          {propertyName: "使用性质",data:[]},
          {propertyName: "主要危险性",data:[]}]
          i.children.forEach(element => {
            i.tabledata[0].data.push({
              name: "重点部位名称",
              physicalUnit: '',
              propertyType: 0,
              result: element.name,
              tag: ""
            })
            i.tabledata[1].data.push({
              name: "重点部位所在位置",
              physicalUnit: '',
              propertyType: 0,
              result: element.position,
              tag: ""
            })
            i.tabledata[2].data.push({
              name: "建筑结构",
              physicalUnit: '',
              propertyType: 0,
              result: element.structure,
              tag: ""
            })
            i.tabledata[3].data.push({
              name: "使用性质",
              physicalUnit: '',
              propertyType: 0,
              result: element.nature,
              tag: ""
            })
            i.tabledata[4].data.push({
              name: "主要危险性",
              physicalUnit: '',
              propertyType: 0,
              result: element.hazards,
              tag: ""
            })
          })
          let newChildren = []
          i.children.forEach((element,index) => {
            let newChildrenItem:any= {}
            // newChildrenItem.name = element.name//重点部位题目名称
            // newChildrenItem.position = element.position//重点部位所在位置
            // newChildrenItem.structure = element.structure//重点部位建筑结构
            // newChildrenItem.nature = element.nature//重点部位使用性质
            // newChildrenItem.hazards = element.hazards//重点部位主要危险性
            newChildrenItem.name = element.name//题目名称
            newChildrenItem.result = element.position + element.structure + element.nature + element.hazards//题目答案
            newChildrenItem.physicalUnit = element.physicalUnit || ''//计量单位
            newChildrenItem.propertyType = 0//输入框类型
            newChildren.push(newChildrenItem)
          })
          i.children = newChildren
          delete i.selected
          

        }) : null
        //建筑的功能分区模块处理
        item.funDivNodes ? item.funDivNodes.forEach((i,key) => {
         
          //如果顶级节点未选中则需要筛除没有选中的数据
          if(!i.checked){
            let newArr = []
            i.children.forEach(element => {
              element.checked ? newArr.push(element) : null
            })
            let discard = []//即将废弃的数组
            newArr.length == 0 ? discard.push(i) : i.children = newArr
            item.funDivNodes = item.funDivNodes.filter(items => {
              if (!discard.includes(items)) return items;
            })
          }

          i.tabledata = [{propertyName: "区域",data:[]},
          {propertyName: "面积",data:[]},
          {propertyName: "基本情况",data:[]}]
          i.children.forEach(element => {
            i.tabledata[0].data.push({
              name: "区域",
              physicalUnit: '',
              propertyType: 0,
              result: element.region,
              tag: ""
            })
            i.tabledata[1].data.push({
              name: "面积",
              physicalUnit: '',
              propertyType: 0,
              result: element.area,
              tag: ""
            })
            i.tabledata[2].data.push({
              name: "基本情况",
              physicalUnit: '',
              propertyType: 0,
              result: element.details,
              tag: ""
            })
          })
          let newChildren = []
          i.children.forEach((element,index) => {
            let newChildrenItem:any= {}
            // newChildrenItem.name = element.region//功能分区题目名称
            // newChildrenItem.area = element.area//功能分区面积
            // newChildrenItem.details = element.details//功能分区基本情况
            newChildrenItem.name = element.region//题目名称
            newChildrenItem.result = element.area + element.details//题目答案
            newChildrenItem.physicalUnit = element.physicalUnit || ''//计量单位
            newChildrenItem.propertyType = 0//输入框类型
            newChildren.push(newChildrenItem)
          })
          i.children = newChildren
          delete i.selected
        }) : null
        //建筑的数据核验模块处理
        item.fireFacNodes ? item.fireFacNodes.forEach((i,key) => {
         i.selected ?  i.selected = null : null
          //如果顶级节点未选中则需要筛除没有选中的数据
          if(!i.checked){
            let newArr = []
            i.children.forEach(element => {
              element.checked ? newArr.push(element) : null
            })
            let discard = []//即将废弃的数组
            newArr.length == 0 ? discard.push(i) : i.children = newArr
            item.fireFacNodes = item.fireFacNodes.filter(items => {
              if (!discard.includes(items)) return items;
            })
          }
          let newChildren = []
          i.children.forEach((element,index) => {
            let newChildrenItem:any= {}
            newChildrenItem.name = element.name//题目名称
            newChildrenItem.result = element.total//题目答案
            newChildrenItem.physicalUnit = ''//计量单位
            newChildrenItem.propertyType = 0//输入框类型
            newChildren.push(newChildrenItem)
          })
          i.children = newChildren
          delete i.selected
        }) : null
     })

     //循环每个建筑处理数据
     console.log(copyDatas) 
     
     let paperDataInfo = []
     copyDatas.forEach((item,key) =>{
      paperDataInfo[key] = {}
      paperDataInfo[key].id = null
      paperDataInfo[key].paperId = null
      paperDataInfo[key].companyId = item.id
      paperDataInfo[key].basicInfoData = item.basicInfoNodes ? JSON.stringify(item.basicInfoNodes) : '[]'
      paperDataInfo[key].basicInfoScore = item.basicInfoScore
      paperDataInfo[key].adjoinData = item.aroundNodes ? JSON.stringify(item.aroundNodes) : '[]'
      paperDataInfo[key].adjoinScore = item.aroundScore
      paperDataInfo[key].importLocationData = item.keySiteNodes ? JSON.stringify(item.keySiteNodes) : '[]'
      paperDataInfo[key].importLocationScore = item.keySiteScore
      paperDataInfo[key].functionalDivisionData = item.funDivNodes ? JSON.stringify(item.funDivNodes) : '[]'
      paperDataInfo[key].functionalDivisionScore = item.funDivScore
      paperDataInfo[key].facilityData = item.fireFacNodes ? JSON.stringify(item.fireFacNodes) : '[]'
      paperDataInfo[key].facilityScore = item.fireFacScore
     })

     console.log(paperDataInfo) 

    const dialogRef = this.dialog.open(FinishDialog, {
      width: '650px',
      data: paperDataInfo
    });

    dialogRef.afterClosed().subscribe(result => {
      
      
    });
  }
  //上一步
  goBack(){
    window.history.back(); 
  }
}

//添加预案1
@Component({
  selector: 'addplan-dialog',
  templateUrl: 'addPlan.html',
  styleUrls: ['addPlan.scss']
})
export class AddPlanDialog {

  constructor(public dialog: MatDialog,public dialogRef: MatDialogRef<AddPlanDialog>,@Inject(MAT_DIALOG_DATA) public data: any) {}

  onNoClick(): void {
    this.dialogRef.close();
  }

  close(){
    this.dialogRef.close();
  }

  //选择想要添加的预案类型 (已存在或者自定义)
  selectType(type){
    let obj = {
      type:type,
      companyData:this.data
    }
    const dialogRef = this.dialog.open(AddPlanTwoDialog, {
      id:'addPlanTwo',
      data: obj
    });

    dialogRef.afterClosed().subscribe(result => {
      if(result){
        console.log(1111111,result)
        this.dialogRef.close(result);
      }else{
        this.dialogRef.close();
      }
     
    });
  }
}


//添加预案2
@Component({
  selector: 'addplantwo-dialog',
  templateUrl: 'addPlanTwo.html',
  styleUrls: ['addPlanTwo.scss']
})
export class AddPlanTwoDialog {

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

  planType:any = this.data.type == 1 ? true : false//显示的预案类型
  displayedColumns: string[] = ['select', 'name', 'people', 'time', 'level'];
  dataSource : any //列表数据
  selectedRadioData:any//当前选择的二维预案
  customPlanName:any//自定义预案名称
  radioChange(e){
    this.selectedRadioData = e
  }
  ngOnInit(): void {
    this.get2DPlan()
    console.log(this.data)
  }

  //获取当前公司的二维预案
  get2DPlan(){
    let planArr = []
    this.http.get('/api/PlanComponents',{params:{
      companyId:this.data.companyData.companyData.id
    }}).subscribe((data:any) => {
      data.items.forEach(item => {
        item.planType == 1 ? planArr.push(item) : null
      })
      this.dataSource = planArr
    })
  }

  onNoClick(): void {
    this.dialogRef.close();
  }
  //确定
  confirm(){
    if(this.planType){//如果选择的是已存在预案
      if(this.selectedRadioData){
        this.dialogRef.close(this.selectedRadioData);
        sessionStorage.setItem('companyName',this.data.companyData.companyData.name)
        sessionStorage.setItem('planId',this.selectedRadioData.id)
        sessionStorage.setItem('buildingTypeId',this.data.companyData.companyData.buildingTypes[0].id)
        sessionStorage.setItem('companyId',this.data.companyData.companyData.id)
        window.open('/canvasTool')
      }else{
        const config = new MatSnackBarConfig();
        config.verticalPosition = 'top';
        config.duration = 3000
        this.snackBar.open('请选择要添加的预案','确定',config);
      }
    }else{//如果选择的是自定义预案


      let level = sessionStorage.getItem('level')
      let body  = {
        id: "",
        name: this.customPlanName,
        planType:1,
        planMode: 2,
        planLevel:Number(level),
        url: "",
        attachmentUrls: null
      }
      this.http.post("/api/PlanComponents2D",body,{params:{
        companyId : this.data.companyData.companyData.id
      }}).subscribe((data:any)=>{
        // console.log("创建成功")
        this.dialogRef.close(data);
        sessionStorage.setItem("planId",data.id);
        sessionStorage.setItem("companyId",this.data.companyData.companyData.id)
        sessionStorage.setItem("buildingTypeId",this.data.companyData.companyData.buildingTypes[0].id)
        sessionStorage.setItem("editable","1")
        window.open('/canvasTool')
      })
    }
  }
  //取消
  close(){
    this.dialogRef.close();
  }

}

//完成弹窗
@Component({
  selector: 'finish-dialog',
  templateUrl: 'finishDialog.html',
  styleUrls: ['finishDialog.scss']
})
export class FinishDialog{

  constructor(private router:Router,private http: HttpClient,public dialog: MatDialog,public snackBar: MatSnackBar,public dialogRef: MatDialogRef<AddPlanTwoDialog>,@Inject(MAT_DIALOG_DATA) public data: any) {}
  ngOnInit(): void {
    this.getProfiles()
  }
  //获取登录账号的个人资料
  Profiles:any 
  getProfiles(){
    this.http.get('/api/ExamAccounts/Profiles').subscribe(data => {
      console.log(data)
      this.Profiles = data
    })
  }


  startTime:string//考试开始时间
  endTime:string//考试结束时间
  examName:string//考试名称
  
  //弹窗确定点击事件
  onNoClick(): void {
    const config = new MatSnackBarConfig();
    config.verticalPosition = 'top';
    config.duration = 3000
    if(this.startTime!=undefined&&this.endTime!=undefined&&this.examName!=undefined){
      if(this.startTime>this.endTime){
        this.snackBar.open('开始时间不能大于结束时间','确定',config);
      }
      else{
        //截取字符串,得到日期部分"2009-12-02",用split把字符串分隔成数组
        var begin1=this.startTime.substr(0,10).split("-");
        var end1=this.endTime.substr(0,10).split("-");
        //将拆分的数组重新组合,并实例成化新的日期对象
        var date1=new Date(begin1[1] + - + begin1[2] + - + begin1[0]);
        var date2=new Date(end1[1] + - + end1[2] + - + end1[0]);
        //得到两个日期之间的差值m,以分钟为单位
        var m=Number(Math.abs(Number(date2)-Number(date1))/1000/60);
        //小时数和分钟数相加得到总的分钟数
        var min1=parseInt(this.startTime.substr(11,2))*60+parseInt(this.startTime.substr(14,2));
        var min2=parseInt(this.endTime.substr(11,2))*60+parseInt(this.endTime.substr(14,2));
        //两个分钟数相减得到时间部分的差值,以分钟为单位
        var n=min2-min1;
        //将日期和时间两个部分计算出来的差值相加,即得到两个时间相减后的分钟数
        var minutes=m+n;
        
        console.log(this.startTime,this.endTime)
        let params = {
          id: null,
          title: this.examName,
          duration: minutes,
          modifiedTime: new Date(),
          deleted: false,
          startTime: this.startTime,
          endTime: this.endTime,
          organizationId: this.Profiles.organizationId,
          creatorId: this.Profiles.id,
          paperDataInfo: this.data
        }
        this.http.post('/api/Papers',params).subscribe(data => {
          this.snackBar.open('创建成功','确定',config);
          this.dialogRef.close();
          sessionStorage.removeItem("checkedWork")
          this.router.navigate(['/home/createexam-index']) //跳转试卷列表页面
        },err => {
          this.snackBar.open(err,'确定',config);
        })
      }
    }
    else{
      if(this.startTime==undefined)
      this.snackBar.open('请输入开始时间','确定',config);
      else if(this.endTime==undefined)
      this.snackBar.open('请输入结束时间','确定',config);
      else if(this.examName==undefined)
      this.snackBar.open('请输入试卷名称','确定',config);
    }
    
  }

  //ngzerro组件
  timeDefaultValue = setHours(new Date(), 0);
  disabledDateTime: DisabledTimeFn = () => {
    var second=[]
    for(var i=1;i<60;i++){
      second.push(i)
    }
    return {
      nzDisabledHours: () => [],
      nzDisabledMinutes: () => [],
      nzDisabledSeconds: () => second
    };
  };
  
  onChange(result: Date[]): void {
    console.log('onChange: ', result);
  }

  getWeek(result: Date[]): void {
    console.log('week: ', result.map(getISOWeek));
  }
  close(){
    this.dialogRef.close();
  }
}

//查看答案
@Component({
  selector: 'lookTreeNode-dialog',
  templateUrl: 'lookTreeNode.html',
  styleUrls: ['lookTreeNode.scss']
})
export class LookTreeNodeDialog {

  constructor(public dialog: MatDialog,public dialogRef: MatDialogRef<LookTreeNodeDialog>,@Inject(MAT_DIALOG_DATA) public data: any) {}

  
  ngOnInit(): void {
    console.log(this.data)
  }

  onNoClick(): void {
    this.dialogRef.close();
  }

  //取消
  close(){
    this.dialogRef.close();
  }

}