<template>
  <div class="box">
    <div class="condition">
      <div class="header">
        <el-button style="float:left;" size="small" type="default" icon="el-icon-back" @click="goBack"></el-button>
        <span>{{ exampleData ? exampleData.localName || exampleData.name : '' }}</span>
      </div>
      <el-row class="spaceTypes">
        <div class="types">
          <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"></el-tab-pane>
            </template>
          </el-tabs>
        </div>
        <div class="deleBtn">
          <el-button size="small" @click="deleteSpace">删除业务空间</el-button>
        </div>
      </el-row>
      <div v-if="activeTab=='detail'" class="content">
        <!-- <iframe v-if="params.isMyTab == 1" height="100%" width="100%" :src="iframeSrc"></iframe> -->
        <el-scrollbar style="height:100%;">
          <div class="content-scrollbar">
            <div class="content-left">
              <div class="content-showType">
                <selectRadio
                  :selectRadio="selectRadio"
                  @changeRadio="changeRadio"
                />
              </div>
              <div class="content-point">
                <div class="content-point-left">
                  <exhibitionBaseInformation :exhibitionBaseInformation="exhibitionBaseInformation"/>
                </div>
                <div class="content-point-right">
                  <exhibitionEnergy :exhibitionEnergy="exhibitionEnergy"/>
                </div>
              </div>
            </div>
            <div class="content-right">
              <div class="content-repair">
                <exhibitionMaintain :exhibitionMaintain="exhibitionMaintain"/>
              </div>
              <div class="content-media">
                <exhibitionImage :exhibitionImage="exhibitionImage" v-if="isShowImage"/>
                <exhibitionVideo :exhibitionVideo="exhibitionVideo" v-if="isShowVideo"/>
                <exhibitionFile :exhibitionFile="exhibitionFile" v-if="isShowFile"/>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
      <!-- 空间内设备列表--服务于空间的设备 -->
      <eqToSpaceTable v-else-if="activeTab=='equipment' || activeTab=='equipmentFor'" :params="params"
                      :type="activeTab"></eqToSpaceTable>
      <!-- 空间内系统 -->
      <syInSpaceTable v-else-if="activeTab=='generalSystem'" :params="params" :type="activeTab"></syInSpaceTable>

    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import tools from "@/utils/scan/tools";
import { BeatchQueryParam, zoneDelete, zoneQuery } 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 exhibitionBaseInformation from "@/components/ledger/details/detail/exhibitionBaseInformation";
import exhibitionFile from "@/components/ledger/details/detail/exhibitionFile";
import exhibitionImage from "@/components/ledger/details/detail/exhibitionImage";
import exhibitionVideo from "@/components/ledger/details/detail/exhibitionVideo";
import exhibitionCrux from "@/components/ledger/details/detail/exhibitionCrux";
import exhibitionEnergy from "@/components/ledger/details/detail/exhibitionEnergy";
import exhibitionMaintain from "@/components/ledger/details/detail/exhibitionMaintain";
import selectRadio from "@/components/ledger/details/detail/selectRadio";


export default {
  data() {
    return {
      params: {}, //参数-包含空间id 分区类型 进入方式（1-平面图 2-列表）
      tabsList: [
        { Code: 'detail', Name: '空间详情' },
        { Code: 'equipment', Name: '空间内设备' },
        { Code: 'equipmentFor', Name: '服务于空间的设备' },
        { Code: 'generalSystem', Name: '空间内系统' },
      ], //tab页
      activeTab: 'detail', //当前选中的tab
      pointData: [], //信息点数据
      exampleData: {}, //实例数据
      currentRadio: '1',//当前选中的select
      criterias: [], //动态参数
      instance: {},
      iframeSrc: '', //空间详情iframe
      selectRadio: {
        information: '设备信息点',
        initRadio: '1',
        radioList: [
          {
            value: '显示需采集信息点',
            label: '1'
          },
          {
            value: '显示有值信息点',
            label: '2'
          },
          {
            value: '显示全部信息点',
            label: '3'
          }
        ]
      },
      exhibitionBaseInformation: {
        information: {}
      },
      exhibitionEnergy: {
        title: '能耗信息',
        firstName: '',
        dynamic: [],
        list: {}
      },
      exhibitionMaintain: {
        title: '维修/维保记录'
      },
      exhibitionFile: {
        title: '文件',
        list: {}
      },
      exhibitionCrux: {
        title: '关键信息点：',
        cruxArray: [],
        allMessage: [],//全部信息点
      },
      exhibitionImage: {
        title: '图片',
        list: {},
        arr: []
      },
      exhibitionVideo: {
        title: '视频',
        list: {}
      },
      isShowImage: false,
      isShowVideo: false,
      isShowFile: false,
    }
  },
  computed: {
    ...mapGetters("layout", ["projectId", "userId", "secret"])
  },
  components: {
    eqToSpaceTable,
    syInSpaceTable,
    exhibitionBaseInformation,
    exhibitionFile,
    exhibitionVideo,
    exhibitionImage,
    exhibitionMaintain,
    selectRadio,
    exhibitionCrux,
    exhibitionEnergy
  },
  created() {
    this.params = this.$route.query;
    this.getData();
    this.setFrame();
  },
  mounted() {
  },
  watch: {
    projectId() {
    }
  },
  methods: {
    deepCopy(obj) {
      return JSON.parse(JSON.stringify(obj))
    },
    // 返回
    goBack() {
      this.$router.push({
        name: "spacelist",
        params: this.params
      })
    },
    // 查询空间详情
    getData() {
      let params1 = {
        orders: "sort asc",
        pageNumber: 1,
        pageSize: 1000,
        type: this.params.zone
      }, params2 = {
        filters: `id='${this.params.RoomID}'`,
        zoneType: this.params.zone
      };
      let promise1 = new Promise((resolve, reject) => {
        getDataDictionary(params1, res => {
          resolve(res)
        })
      })
      let promise2 = new Promise((resolve, reject) => {
        zoneQuery(params2, res => {
          resolve(res)
        })
      })
      // 数据初始化
      this.exhibitionEnergy.dynamic = [];
      this.criterias = [];

      Promise.all([promise1, promise2]).then(values => {
        this.pointData = values[0].content;
        this.exampleData = values[1].content[0];
        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.pointData.forEach(item => {
          if (item.inputMode == "L" || item.inputMode == "L1" || item.inputMode == "L2" || item.inputMode == "M") {
            let cur = tools.dataForKey(this.exampleData, item.path);
            if (cur) {
              this.criterias.push({
                id: this.exampleData.id,
                code: item.code
              })
            }
          }
        })
        let params = { //获取动态参数
          groupCode: "WD",
          appId: "datacenter",
          projectId: this.projectId,
          data: []
        }
        params.data = this.criterias
        if (this.criterias.length) {
          BeatchQueryParam(params, res => {
            // this.criteriasArray = res.Content;
            res.data.length && res.data.map(child => {
              this.pointData.map(head => {
                if (head.code == child.infoCode) {
                  if (head.dataSource) {
                    head.dataSource.forEach(i => {
                      if (i.code == child.data) {
                        this.$set(head, 'data', i.name)
                      }
                    })
                  } else {
                    this.$set(head, 'data', child.data)
                  }
                  this.$set(head, 'svalue', child.infoValue)
                  // this.$set(head, 'data', child.data)
                  this.$set(head, 'receivetime', child.time)
                  this.$set(head, 'error', child.error)
                }
                return head
              })
            })
            this.handleRadios(this.currentRadio);
            this.handleEnclosure() //处理图片视频文件信息
          })
        } else {
          this.handleRadios(this.currentRadio);
          this.handleEnclosure() //处理图片视频文件信息
        }
      })
    },
    handleEnclosure() {
      //图片文件处理，脱离radio控制
      let isList = this.pointData
      let isArr = []
      isList.map(j => {
        if (this.instance && this.instance.hasOwnProperty(j.path)) {
          j.value = this.instance[j.path]
          return j
        }
      })
      isArr = isList.filter(k => k.value)
      this.handlePicList(isArr)
      this.handleFileList(isArr)
    },
    handleRadios(val) { //判断radio的值显示关键信息，基本信息，图片，文件
      let arr = []
      //关键信息点
      this.exhibitionCrux.cruxArray = this.pointData.filter(i => i.keyWord)
      this.exhibitionCrux.cruxArray.map(i => {
        if (this.instance && this.instance.hasOwnProperty(i.path)) {
          return {
            ...i,
            value: this.instance[i.path]
          }
        }
      })
      if (val == 1) { //需采集信息
        arr = this.pointData.filter(i => i.visible)
        //  图片和的处理
        // this.handlePicList(arr)
        // //  文件处理
        // this.handleFileList(arr)

      } else if (val == 2) { //有值信息点
        let list = this.pointData
        list.map(j => {
          if (this.instance && this.instance.hasOwnProperty(j.path)) {
            return {
              ...j,
              value: this.instance[j.path]
            }
          }
          arr = list.filter(k => k.value)
          // this.handlePicList(arr)
          // this.handleFileList(arr)
        })
      } else { //全部信息点
        arr = this.pointData
        // this.handlePicList(arr)
        // this.handleFileList(arr)
      }
      this.displayData(arr)
    },
    handlePicList(arr) {
      let picObject = {}
      //处理数据格式
      arr.map(i => {
        if (i.inputMode == 'F2') {
          switch (i.Path) {
            case 'infos.drawing':
            case 'infos.installPic':
            case 'infos.installDrawing':
            case 'infos.nameplate':
            case 'infos.pic':
            case 'pic' :
              if (this.instance && this.instance.hasOwnProperty(i.path)) {
                i.PicList = this.instance[i.path]
              }
              if (picObject[i.name]) {
              } else {
                picObject[i.name] = []
              }
              picObject[i.name].push({
                ...i,
              })
              break;
          }
        }

      })
      //展示图片
      this.exhibitionImage.list = picObject
      let isArray = [] //获取图片数组
      for (let i in picObject) {
        if (Array.isArray(picObject[i])) {
          let list = picObject[i]
          list.forEach(i => {
            if (i.PicList) {
              isArray.push(...i.PicList)
            }
          })
        }
      }
      this.exhibitionImage.arr = isArray
      let video = isArray.filter(i => i.Type != 'image' && i.type != 'image')
      this.exhibitionVideo.list = video

      //判断是否显示图片组件
      this.isShowImage = isArray.length ? true : false

      //判断是否显示video组件
      this.isShowVideo = video.length ? true : false
    },
    handleFileList(arr) {
      let picObject = {}
      //处理数据格式
      arr.map(i => {
        if (i.inputMode == 'F2') {
          switch (i.path) {
            case 'infos.insuranceFile':
            case 'infos.archive':
            case 'infos.checkReport':
              if (this.instance && this.instance.hasOwnProperty(i.path)) {
                i.fileList = this.instance[i.path]
              }
              if (picObject[i.name]) {

              } else {
                picObject[i.name] = []
              }

              picObject[i.name].push({
                ...i,
              })
              break
          }
        }

      })
      //展示文件
      this.exhibitionFile.list = picObject
      let isArray = [] //获取文件数组
      for (let i in picObject) {
        if (Array.isArray(picObject[i])) {
          let list = picObject[i]
          list.forEach(i => {
            if (i.fileList) {
              isArray.push(...i.fileList)
            }
          })
        }
      }
      //判断是否显示文件组件
      this.isShowFile = isArray.length ? true : false
    },
    changeRadio(val) { //1,需采集，2，有值，3，全部
      this.handleRadios(val)
      this.currentRadio = val
    },
    formatDate(str) {
      if (str) {
        if (str.includes('-')) {
          return str
        } else {
          return str.substr(0, 4) + "-" + str.substr(4, 2) + "-" + str.substr(6, 2) + " " + str.substr(8, 2) + ":" + str.substr(10, 2) + ":" + str.substr(12, 2)
        }
      } else {
        return '--'
      }
    },
    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)
          let source = 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":
            if (resultEnergy[`${i.firstName}${i.secondName ? '/' + i.secondName : ''}`]) {
              resultEnergy[`${i.firstName}${i.secondName ? '/' + i.secondName : ''}`].paths.push({
                Path: i.path,
                InfoPointName: i.name,
                InfoPointCode: i.code,
                value: i.svalue,
                Visible: i.visible,
                KeyWord: i.keyWord,
                InputMode: i.inputMode,
                data: i.data,
                receivetime: i.receivetime,
                error: i.error,
                Unit: i.unit,
                FirstName: i.firstName,
              })
            } else {
              resultEnergy[`${i.firstName}${i.secondName ? '/' + i.secondName : ''}`] = {
                paths: [{
                  Path: i.path,
                  InfoPointName: i.name,
                  InfoPointCode: i.code,
                  value: i.svalue,
                  Visible: i.visible,
                  KeyWord: i.keyWord,
                  InputMode: i.inputMode,
                  data: i.data,
                  receivetime: i.receivetime,
                  error: i.error,
                  Unit: i.unit,
                  FirstName: i.firstName,
                }]
              }
            }
            break;
          default:
            if (result[`${i.firstName}${i.secondName ? '/' + i.secondName : ''}`]) {
              result[`${i.firstName}${i.secondName ? '/' + i.secondName : ''}`].paths.push({
                Path: i.path,
                InfoPointName: i.name,
                InfoPointCode: i.code,
                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.name,
                  InfoPointCode: i.code,
                  Value: i.value,
                  Visible: i.visible,
                  KeyWord: i.keyWord,
                  InputMode: i.inputMode,
                }]
              }
            }

        }
      })
      this.exhibitionBaseInformation.information = result
      this.exhibitionCrux.allMessage = result
      this.exhibitionEnergy.list = resultEnergy;
    },
    // 设置iframe
    setFrame() {
      this.iframeSrc = `${process.env.BASE_URL}:8889/#/changeMess?perjectId=${this.projectId}&secret=${this.secret}&id=${this.params.RoomID}&type=${this.params.zone}`;
      // this.iframeSrc = this.params.isMyTab == 2 ?
      //   `${process.env.BASE_URL}:8889/#/details?perjectId=${this.projectId}&secret=${this.secret}&FmId=${this.params.RoomID}&type=0&code=${this.params.zone}`
      //   : `${process.env.BASE_URL}:8889/#/changeMess?perjectId=${this.projectId}&secret=${this.secret}&id=${this.params.RoomID}&type=${this.params.zone}`;
    },
    // 删除业务空间
    deleteSpace() {
      this.$confirm("此操作将删除业务空间，是否继续？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let pa = [{ id: this.exampleData.id }];
        zoneDelete(pa, res => {
          this.$message.success('删除成功')
          this.goBack()
        })
      }).catch(() => {
        this.getData()
        this.$message("取消删除")
      })
    },

  }
};
</script>

<style scoped lang='less'>
@bgc: #fff;
.box {
  .condition {
    padding: 10px;
    display: flex;
    height: 100%;
    flex-direction: column;
    border: 1px solid #dfe6ec;
    box-sizing: border-box;
    background: #fff;

    .header {
      padding-bottom: 10px;

      span {
        line-height: 33px;
        margin-left: 15px;
      }
    }

    .spaceTypes {
      .types {
        float: left;
        width: calc(100% - 200px);

        /deep/ .el-tabs__item.is-top {
          border-top: 2px solid transparent;

          &.is-active {
            border-top: 2px solid #409eff;
          }
        }
      }

      .deleBtn {
        float: left;
        width: 200px;
        text-align: right;
        height: 40px;
        border-bottom: 1px solid #e4e7ed;
      }
    }

    .content {
      height: calc(100% - 99px);

      .content-scrollbar {
        display: flex;
        height: 100%;
        flex-direction: row;
        box-sizing: border-box;
        background-color: @bgc;

        .content-left {
          display: flex;
          flex-direction: column;
          flex: 1;

          .content-showType {
            height: 50px;
            border: 1px solid #ccc;
            border-bottom: none;
            box-sizing: border-box;
            background: @bgc;
          }

          .content-point {
            display: flex;
            flex-direction: row;
            border: 1px solid #ccc;
            box-sizing: border-box;
            background: @bgc;

            .content-point-left {
              flex: 1;
            }

            .content-point-right {
              width: 300px;
              border-left: 1px solid #ccc;
            }
          }
        }

        .content-right {
          width: 400px;
          margin-left: 10px;
          box-sizing: border-box;

          .content-repair {
            height: 50px;
            line-height: 50px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            background: @bgc;
            box-sizing: border-box;
          }

          .content-media {
            box-sizing: border-box;
          }
        }
      }
    }

    .main {
      margin-top: 10px;
      height: calc(100% - 96px);
    }

    .footer {
      margin-bottom: 10px;
    }

    /deep/ .el-scrollbar__wrap {
      overflow-x: hidden;
    }
  }
}
</style>

<style lang="less">
.el-table th {
  background-color: #d9d9d9;
  color: #000;
}
</style>
