<template>
  <div class="box">
    <el-container style="height:100%">
      <el-header>
        <div class="spaceName">
          <b>空间名称：</b>{{ spaceDetails.RoomLocalName ? spaceDetails.RoomLocalName : "-" }}
        </div>
      </el-header>
      <el-container>
        <el-aside width="450px">
          <div class="aside-top">
            <div class="aside-top-left">
              <p><b>空间功能区类型:</b>{{ spaceDetails.RoomFuncType ? spaceDetails.RoomFuncType : "-" }}</p>
              <p style="padding-right: 10px"><b>备注文字:</b>{{ spaceDetails.Intro ? spaceDetails.Intro : "-" }}</p>
            </div>
            <div class="aside-top-right">
              <p><b>空间二维码:</b><span v-if="!spaceDetails.RoomQRCode">-</span></p>
              <img :src="'/image-service/common/file_get/'+ spaceDetails.RoomQRCode +'?systemId=dataPlatform'"
                   alt="二维码图片"
                   v-if="spaceDetails.RoomQRCode">
            </div>
          </div>
          <div>
            <p><b>位置图片:</b></p>
            <div v-show="spaceDetails.Outline && spaceDetails.Outline[0] && spaceDetails.Outline[0].length" id="graphy"
                 ref="graphy"
                 style="width:400px;height:280px;" v-loading="canvasLoading">
              <div style="color:#333;font-weight: 700">{{ buildingFloor }}</div>
              <canvas id="floorCanvas" :width="canvasWidth" :height="canvasHeight" ref="canvas" tabindex="0"></canvas>
            </div>
          </div>
          <div v-show="spaceDetails.Outline && !spaceDetails.Outline[0] || !spaceDetails.Outline"
               style="height: 280px;transform: translateY(30%);text-align:center;">
            <i class="icon-wushuju iconfont"></i>
            暂无数据
          </div>
          <div class="space-img" style="height:400px;margin-top:40px;">
            <el-scrollbar>
              <p><b>空间照片:</b></p>
              <div v-if="spaceDetails.Pic">
                <div class="img-box" v-for="(item) in spaceDetails.Pic" :key='`${item.Id}+${item.Key}`'>
                  <img :src="`/image-service/common/image_get?systemId=dataPlatform&key=${item.Key}`" alt="空间图片">
                </div>
              </div>
              <div v-show="!spaceDetails.Pic" style="height:100%;transform: translateY(50%);textAlign:center;">
                <i class="icon-wushuju iconfont"></i>
                暂无数据
              </div>
            </el-scrollbar>
          </div>
        </el-aside>
        <el-main>
          <el-tabs v-model="activeTab" type='card'>
            <template v-for="(item,index) in tabsList">
              <el-tab-pane :name="item.Code" :key="index" :label="item.Name">
                <section v-show="activeTab === 'staticData'">
                  <el-radio-group
                    v-model="radio"
                    style=" margin: 0 10px;"
                    @change="changRadio"
                    v-for="(item,index) in radioList"
                    :key="index"
                  >
                    <el-radio :label="item.label">{{ item.value }}</el-radio>
                  </el-radio-group>

                  <exhibitionBaseInformation :exhibitionBaseInformation="exhibitionBaseInformation"/>
                </section>
                <section v-show="activeTab === 'dynamicData'">
                  <div style="text-align: left;margin-bottom: 10px">
                    <el-checkbox v-model="onlyMessage" @change="handleCheckbox">只看需采集的信息点</el-checkbox>
                  </div>
                  <el-table height="700" ref="multipleTable" :data="tableData" stripe :header-cell-style="headerStyle">
                    <el-table-column prop="name" label="信息点名称">
                      <template slot-scope="scope">
                        <div>
                          <span>{{ scope.row.name }}</span>
                          <span class="unit">{{ scope.row.unit ? `${"(" + scope.row.unit + ")"}` : "" }}</span>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="functionNo" label="表号功能号"></el-table-column>
                    <el-table-column prop="functionNoDynamicData" label="动态数据"></el-table-column>
                    <el-table-column prop="functionNoTime" label="数据采集时间"></el-table-column>
                    <!-- 后台未提供，暂不显示 -->
                    <!-- <el-table-column prop="LastUpdate" label="数据采集时间"></el-table-column> -->
                    <template slot="empty">
                      <div style="height: 60%;transform: translateY(50%);">
                        <i class="icon-wushuju iconfont"></i>
                        暂无数据
                      </div>
                    </template>
                  </el-table>

                </section>
                <div v-if="activeTab === 'objectRelationship'" class="objectRelationship">
                  <div class="objectRelationship-left">
                    <h5>空间内设备：</h5>
                    <eqToSpaceTable :params="params" type="Equipment"></eqToSpaceTable>
                  </div>
                  <div class="objectRelationship-center">
                    <h5>服务于空间的设备：</h5>
                    <eqToSpaceTable :params="params" type="EquipmentFor"></eqToSpaceTable>
                  </div>
                  <div class="objectRelationship-right">
                    <h5>空间内系统：</h5>
                    <syInSpaceTable :params="params" type="generalSystem"></syInSpaceTable>
                  </div>
                </div>
              </el-tab-pane>
            </template>
          </el-tabs>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import { BeatchQueryParam, floorQuery, zoneQuery, zoneQueryOutline } from '@/api/scan/request'
import { getDataDictionary } from "@/api/dict";

import eqToSpaceTable from '@/components/business_space/newTables/eqToSpaceTable'
import syInSpaceTable from '@/components/business_space/newTables/syInSpaceTable'
import { DivideFloorScene, FloorView } from "@saga-web/cad-engine/lib";
import tools from "@/utils/scan/tools";
import exhibitionBaseInformation from "@/components/ledger/details/detail/exhibitionBaseInformation";


export default {
  data() {
    return {
      tabsList: [
        { Code: 'staticData', Name: '静态数据' },
        { Code: 'dynamicData', Name: '动态数据' },
        { Code: 'objectRelationship', Name: '对象关系' }
      ],
      activeTab: 'staticData',
      checked: true,
      spaceDetails: {},
      iframeSrc: '',
      proId: '',
      params: {},
      view: null,
      scene: null,
      canvasWidth: 410,
      canvasHeight: 300,
      page: {
        pageSize: 50,
        pageSizes: [10, 20, 50, 100],
        pageNumber: 1,
        total: 0
      },
      tableData: [],
      headerStyle: {// 列表样式
        backgroundColor: '#e1e4e5',
        color: '#2b2b2b',
        lineHeight: '30px'
      },
      secret: '',
      canvasLoading: false,
      buildingFloor: localStorage.getItem('buildingFloor'),
      onlyMessage: false,
      exhibitionBaseInformation: {
        information: {},
      },
      pointData: [],
      instance: {},
      radioList: [
        {
          value: '显示全部信息点',
          label: '1'
        },
        {
          value: '显示有值信息点',
          label: '2'
        }
      ],
      radio: '1'
    }
  },
  components: {
    eqToSpaceTable,
    syInSpaceTable,
    exhibitionBaseInformation
  },
  beforeRouteEnter(to, from, next) {
    if (to.query.RoomID && to.query.zone) {
      next();
    }
  },
  created() {
    if (this.$route.name === "spaceLedger" && this.$route.query.RoomID && this.$route.query.zone) {
      this.getData();
    }
  },

  updated() {
  },
  computed: {},
  methods: {
    getData() {
      //获取表头
      let params1 = {
        orders: "sort asc",
        pageNumber: 1,
        pageSize: 1000,
        type: this.$route.query.zone
      }
      // 获取空间数据
      let params2 = {
        Filters: `RoomID="${this.$route.query.RoomID}"`,
        ZoneType: this.$route.query.zone
      }
      this.params = this.$route.query;
      let promise1 = new Promise((resolve, reject) => {
        getDataDictionary(params1, res => {
          resolve(res)
        })
      })
      let promise2 = new Promise((resolve, reject) => {
        zoneQuery(params2, res => {
          resolve(res)
        })
      })
      Promise.all([promise1, promise2]).then(values => {
        this.pointData = values[0].content;
        this.spaceDetails = values[1].Content[0];
        this.getOutline();
        // if (this.spaceDetails.Outline && this.spaceDetails.Outline[0] && this.spaceDetails.Outline[0].length) {
        //   this.getSpaceFloor();
        // }
        let obj = values[1].Content[0] ? this.deepCopy(values[1].Content[0]) : values[1].Content[0];
        obj = tools.flattenKeys(obj);
        for (let key in obj) {
          if (Array.isArray(obj[key]) && !obj[key].length) {
            delete obj[key]
          }
        }
        this.instance = obj;
        this.getInFormationPoitnName();
        this.handleRadios(this.radio);
      })
    },
    getOutline() {
      zoneQueryOutline({
        Filters: `RoomID="${this.$route.query.RoomID}"`,
        ZoneType: this.$route.query.zone
      }, res => {
        if (res.Content[0] && res.Content[0].Outline && res.Content[0].Outline.length) {
          this.spaceDetails.Outline = res.Content[0].Outline;
          this.getSpaceFloor();
        }
      })
    },
    deepCopy(obj) {
      return JSON.parse(JSON.stringify(obj))
    },
    getSpaceFloor() {
      // 获取业务空间楼层
      let params = {
        filters: `id='${this.spaceDetails.FloorId}'`
      }
      floorQuery(params, res => {
        if (res.content[0] && res.content[0].structureInfo && res.content[0].structureInfo.floorMap) {
          this.FloorMap = res.content[0].structureInfo.floorMap;
          this.getGraphy();
        }
      })
    },
    getGraphy() {// 绘制空间位置图片
      let that = this;
      that.clearGraphy()
      that.scene = new DivideFloorScene();
      this.canvasLoading = true;
      that.scene.loadUrl(`/image-service/common/file_get?systemId=revit&key=${this.FloorMap}`).then(res => {
        that.canvasLoading = false;
        if (res == 'error') {
          this.FloorMap = '';
          this.$message.warning('数据解析异常');
          return;
        }
        that.view.scene = that.scene;
        that.view.fitSceneToView();
        let tempArr = {
          RoomLocalName: this.spaceDetails.RoomLocalName,
          OutLine: this.spaceDetails.Outline,
          RoomID: this.spaceDetails.RoomID,
          Color: "#F56C6C",
          HighLightFlag: true
        }
        that.scene.addZoneList([tempArr]);
        this.scene.isSpaceSelectable = false;
      })
    },
    clearGraphy() {
      if (this.view && this.view.scene) {
        this.view.scene = null;
        return
      }
      this.view = new FloorView('floorCanvas')
    },
    getInFormationPoitnName() {// 获取动态数据
      let proId = localStorage.getItem('projectId');
      let secret = localStorage.getItem('secret');
      let params = {
        filters: 'inputMode in ["L1","L2","L","M"]',
        orders: "sort asc",
        pageNumber: 1,
        pageSize: 500,
        type: this.$route.query.zone
      }
      let param = {
        groupCode: "WD",
        appId: "datacenter",
        projectId: this.projectId,
        data: []
      };

      getDataDictionary(params, res => {// 获取表号功能号
        // this.tableData = res.Content;
        if (this.onlyMessage) {
          this.tableData = res.content.filter(i => i.visible)
        } else {
          this.tableData = res.content
        }
        this.tableData.map(item => {
          let cur = tools.dataForKey(this.spaceDetails, item.path);
          if(cur) {
            param.data.push({
              objectId: this.spaceDetails.RoomID,
              infoCode: item.code
            });
          }
        })
        BeatchQueryParam(param, res => {// 获取动态数据
          res.data.forEach((item, index) => {
            this.$set(this.tableData[index], 'functionNo', item.data)
            this.$set(this.tableData[index], 'functionNoTime', item.time)
            tools.setDataForKey(
              this.spaceDetails,
              this.tableData[index].path,
              // this.$set(this.tableData[index], "functionNoDynamicData", item.interrupt ? '已断数' : (item.error ? item.value ? "表号功能号不存在" : "未维护" : "暂未采集到实时数据"))
              this.$set(this.tableData[index], "functionNoDynamicData", item.error)
            );
          })
        });
      })
    },
    handleCheckbox(val) {
      this.onlyMessage = val
      this.getInFormationPoitnName()
    },
    displayData(arr) {//对数据进行处理传给组件展示
      const result = {}
      const resultEnergy = {};
      arr.forEach(i => {
        if (this.instance && this.instance.hasOwnProperty(i.Path) && this.currentRadio != 2) {
          i.value = this.instance[i.Path]
        }
        if (i.InputMode == 'C5') {
          if (this.instance && this.instance.hasOwnProperty(i.Path)) {
            let time = this.instance[i.Path]
            i.value = this.formatDate(time)
          }
        }
        if (i.DataSource && i.DataSource.length) {
          let source = JSON.parse(i.DataSource)
          //判断输入类型
          if (i.InputMode == 'D1L') {
            let d1l = tools.formatDataSource(i.DataSource)
            d1l.forEach(k => {
              if (k.Code == this.instance[i.Path]) {
                i.value = k.Name
              }
            })
          } else if (i.InputMode == 'D2' || i.InputMode == 'C6') {
            if (this.instance && this.instance.hasOwnProperty(i.Path)) {
              if (!Array.isArray(this.instance[i.Path])) {
                let transArray = this.instance[i.Path].split(',')
                i.value = source.filter(item => transArray.includes(item.Code)).map(item => item.Name).join(',')
              }
            }
          }
          source.forEach(j => {
            if (this.instance && j.Code == this.instance[i.Path]) {
              i.value = j.Name
            }
          })
        }
        switch (i.InputMode) {
          case "L":
          case "L1":
          case "L2":
          case "M":
            break;
          default:
            if (result[`${i.FirstName}${i.SecondName ? '/' + i.SecondName : ''}`]) {
              result[`${i.FirstName}${i.SecondName ? '/' + i.SecondName : ''}`].paths.push({
                Path: i.Path,
                InfoPointName: i.InfoPointName,
                InfoPointCode: i.InfoPointCode,
                Value: i.value,
                Visible: i.Visible,
                KeyWord: i.KeyWord,
                InputMode: i.InputMode
              })
            } else {
              result[`${i.FirstName}${i.SecondName ? '/' + i.SecondName : ''}`] = {
                paths: [{
                  Path: i.Path,
                  InfoPointName: i.InfoPointName,
                  InfoPointCode: i.InfoPointCode,
                  Value: i.value,
                  Visible: i.Visible,
                  KeyWord: i.KeyWord,
                  InputMode: i.InputMode
                }]
              }
            }

        }
      })
      this.exhibitionBaseInformation.information = result
    },
    changRadio(val) {
      this.handleRadios(val)
      this.radio = val
    },
    handleRadios(val) {
      let arr = []
      if (val == 1) {
        arr = this.pointData
      } else {
        let list = this.pointData
        list.map(j => {
          if (this.instance.hasOwnProperty(j.path)) {
            return {
              ...j,
              value: this.instance[j.path]
            }
          }
        })
        arr = list.filter(k => k.value)
      }
      this.displayData(arr)
    }
  },
  watch: {
    // 监听路由地址，并判断有RoomID和zone，重新请求空间数据
    "$route"(to, from) {
      if (this.$route.name === "spaceLedger" && this.$route.query.RoomID && this.$route.query.zone) {
        this.getData();
      }
    }
  }
}
</script>

<style lang="less" scoped>
/*.box{*/
/*  .content-box{*/
/*    width: 100%;*/
/*    height: calc(100% - 90px);*/
/*  }*/
/*}*/
.box.screen-router {
  padding: 0;

  section {
    .el-container {
      padding: 0;
    }
  }
}

.el-header {
  padding: 0;
  height: 30px !important;
  margin-top: -10px;

  .boxName {
    color: #fff;
    font-size: 16px;
    line-height: 50px;
    height: 50px !important;
    padding: 0 10px;
    background-color: #3f4f62;
  }

  .spaceName {
    font-size: 14px;
    line-height: 30px;
    border-bottom: 1px solid #e4e7ed;
    box-sizing: border-box;
  }
}

.el-aside {
  color: #333;
  border: 1px solid #e4e7ed;
  margin-top: 10px;
  padding: 10px;
  box-sizing: border-box;
  height: calc(100% - 10px);
  overflow: hidden;

  .aside-top {
    overflow: hidden;
    display: flex;

    .aside-top-left {
      flex: 3;
    }

    .aside-top-right {
      float: right;

      img {
        margin-left: -10px;
        width: 140px;
        height: 140px;
      }
    }
  }

  .space-img {
    width: 100%;

    .img-box {
      float: left;
      position: relative;
      width: 47%;
      height: 180px;
      margin: 10px 10px 0 0;
      overflow: hidden;

      img {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
      }
    }
  }
}

.el-scrollbar {
  width: 430px;
  height: 100%;
  overflow-x: hidden !important;
}

.el-main {
  color: #333;
  /*text-align: center;*/
  overflow: hidden;
  width: 100%;
  padding: 10px 0 0 10px;
}

.el-tabs.el-tabs--card.el-tabs--top {
  height: 100% !important;
  width: 100%;
}

.objectRelationship {
  height: 100%;
  width: 100%;
  display: flex;

  .objectRelationship-left,
  .objectRelationship-center,
  .objectRelationship-right {
    flex: 1;
    margin-right: 10px;
    text-align: left;
    height: 100% !important;
  }
}

#pane-dynamicData {
  height: calc(100% - 10px);
}

.el-tab-pane {
  height: 100%;
}

#pane-staticData {
  div {
    height: 100%;
  }
}

.unit {
  color: rgb(167, 167, 167);
}

#floorCanvas {
  position: static;
}

/deep/ .el-scrollbar__wrap {
  height: 100%;
  overflow-x: hidden !important;
  overflow-y: auto !important;
}

.objectRelationship {
  height: calc(100% - 46px) !important;
}

/deep/ .el-tabs__content {
  height: 100%;
}
</style>
