<template>
  <div class="report-index">
    <div class="statistics">
      <div class="building">
        <p>建筑模型文件夹：<b>{{ModelFileCount}}</b></p>
      </div>
      <div class="includefloor">
        <p>包含楼层模型文件:<b>{{modelFloorCount}}</b></p>
      </div>
      <div class="problematic">
        <p>检查出问题的楼层模型文件：<b>{{problemCount}}</b></p>
      </div>
    </div>
    <div class="main-content">
      <div class="tab-box">
        <el-tabs v-model="activeTab" type='card' @tab-click="getData">
          <template v-for="(item,index) in tableList">
            <el-tab-pane :name="item.Code" :key="index" :label="item.Name">
              <span slot="label">
                <i :class="item.flag?'msg-icon el-icon-success success-color':'msg-icon el-icon-error error-color'" style="font-size:14px;"></i>
                <span>{{ item.Name }}</span>
              </span>
            </el-tab-pane>
          </template>
        </el-tabs>
      </div>
      <div class="content-box">
        <div class="button">
          <el-button @click="del"  :disabled="toBeDelCount?false:true" :title="toBeDelCount ? '':'没有待删除的设备'">需从模型中删除的设备
          </el-button>
          <el-button @click="supplement" :disabled="toBeSuppCount?false:true" :title="toBeSuppCount ? '':'没有待补充的设备'">模型待补充的设备
          </el-button>
          <el-button :loading="load" @click='getExportReport'>导出模型问题报告</el-button>
        </div>
        <div class="table"
             :style="tableList&&tableList.length?'width: 100%;height: calc(100% - 47px)':'width: 100%;height: calc(100% - 10px)'">
          <el-table
            ref="multipleTable"
            :data="tableData"
            stripe
            height="100%"
            :header-cell-style="headerStyle"
            v-loading='loading'
            :row-class-name="tableRowClassName"
            :cell-style="cellStyle"
          >
            <el-table-column prop="FloorName" label="模型楼层" fixed width="150"></el-table-column>
            <el-table-column prop="functionNo" label="待删除设备数量" fixed width="150">
              <template slot-scope="scope">
                <el-badge :value="scope.row.toBeDel" class="item" :type='scope.row.toBeDel?"danger":"success"'>
                </el-badge>
              </template>
            </el-table-column>
            <el-table-column prop="toBeSupplement" label="待补充设备数量" fixed width="150">
              <template slot-scope="scope">
                <el-badge :value="scope.row.toBeSupplement" class="item"
                          :type='scope.row.toBeSupplement?"danger":"success"'>
                </el-badge>
              </template>
            </el-table-column>
            <el-table-column prop="questionItem" label="有问题的检查项" fixed width="150" style="border-right:1px solid red">
              <template slot-scope="scope">
                <el-badge :value="scope.row.questionItem" class="item" :type='scope.row.questionItem?"warning":"success"'>
                </el-badge>
              </template>
            </el-table-column>
            <el-table-column prop="ElementRangeCheck" label='构件范围检查' width="200">
              <template slot-scope="scope">
                <el-badge :value="scope.row.ElementRangeCheck" class="item" type='danger'
                          v-if="scope.row.ElementRangeCheck"/>
                <i class="msg-icon el-icon-success success-color1" style="font-size:20px;"
                   v-if="scope.row.ElementRangeCheck<=0"></i>
              </template>
            </el-table-column>
            <el-table-column prop="FamilyNameCheck" label='设备族编码检查' width="200">
              <template slot-scope="scope">
                <el-badge :value="scope.row.FamilyNameCheck" class="item" type='danger'
                          v-if="scope.row.FamilyNameCheck"/>
                <i class="msg-icon el-icon-success success-color1" style="font-size:20px;"
                   v-if="scope.row.FamilyNameCheck<=0"></i>
              </template>
            </el-table-column>
            <el-table-column prop="EquipPartLocationCheck" label='部件所在位置检查' width="200">
              <template slot-scope="scope">
                <el-badge :value="scope.row.EquipPartLocationCheck" class="item" type='danger'
                          v-if="scope.row.EquipPartLocationCheck"/>
                <i class="msg-icon el-icon-success success-color1" style="font-size:20px;"
                   v-if="scope.row.EquipPartLocationCheck<=0"></i>
              </template>
            </el-table-column>
            <el-table-column prop="ColumnCheck" label='柱边界检查' width="200">
              <template slot-scope="scope">
                <el-badge :value="scope.row.ColumnCheck" class="item" type='danger' v-if="scope.row.ColumnCheck"/>
                <i class="msg-icon el-icon-success success-color1" style="font-size:20px;"
                   v-if="scope.row.ColumnCheck<=0"></i>
              </template>
            </el-table-column>
            <el-table-column prop="ConnectorCheck" label='连接件检查' width="200">
              <template slot-scope="scope">
                <el-badge :value="scope.row.ConnectorCheck" class="item" type='danger' v-if="scope.row.ConnectorCheck"/>
                <i class="msg-icon el-icon-success success-color1" style="font-size:20px;"
                   v-if="scope.row.ConnectorCheck<=0"></i>
              </template>
            </el-table-column>
            <el-table-column prop="SystemNameCheck" label='系统类型名称检查' width="200">
              <template slot-scope="scope">
                <el-badge :value="scope.row.SystemNameCheck" class="item" type='danger'
                          v-if="scope.row.SystemNameCheck"/>
                <i class="msg-icon el-icon-success success-color1" style="font-size:20px;"
                   v-if="scope.row.SystemNameCheck<=0"></i>
              </template>
            </el-table-column>
            <el-table-column prop="EquipInSpaceCheck" label='未在空间中的设备' width="200">
              <template slot-scope="scope">
                <el-badge :value="scope.row.EquipInSpaceCheck" class="item" type='danger'
                          v-if="scope.row.EquipInSpaceCheck"/>
                <i class="msg-icon el-icon-success success-color1" style="font-size:20px;"
                   v-if="scope.row.EquipInSpaceCheck<=0"></i>
              </template>
            </el-table-column>
            <el-table-column prop="PipeCheck" label='管段检查' width="200">
              <template slot-scope="scope">
                <el-badge :value="scope.row.PipeCheck" class="item" type='danger' v-if="scope.row.PipeCheck"/>


                <i class="msg-icon el-icon-success success-color1" style="font-size:20px;"
                   v-if="scope.row.PipeCheck<=0"></i>
              </template>
            </el-table-column>
            <el-table-column prop="SystemReferEquipCheck" label='管网及相关设备检查' width="200">
              <template slot-scope="scope">
                <el-badge :type='scope.row.SystemReferEquipCheck?"danger":"success"' :value="scope.row.SystemReferEquipCheck"
                          class="item"
                          v-if="scope.row.SystemReferEquipCheck"/>
                <i class="msg-icon el-icon-success success-color1" style="font-size:20px;"
                   v-if="scope.row.SystemReferEquipCheck<=0"></i>
              </template>
            </el-table-column>
            <el-table-column prop="ParameterIntegrityCheck" label='Revit族参数完整性检查' width="200">
              <template slot-scope="scope">
                <el-badge :value="scope.row.ParameterIntegrityCheck" class="item" type='danger'
                          v-if="scope.row.ParameterIntegrityCheck"/>

                <i class="msg-icon el-icon-success success-color1" style="font-size:20px;"
                   v-if="scope.row.ParameterIntegrityCheck<=0"></i>
              </template>
            </el-table-column>
            <el-table-column prop="XyzOverlapCheck" label='xyz坐标重叠检查' width="200">
              <template slot-scope="scope">
                <el-badge :value="scope.row.XyzOverlapCheck" class="item" type='danger'
                          v-if="scope.row.XyzOverlapCheck"/>
                <i class="msg-icon el-icon-success success-color1" style="font-size:20px;"
                   v-if="scope.row.XyzOverlapCheck<=0"></i>
              </template>
            </el-table-column>
            <template slot="empty">
              <div style="height: 60%;transform: translate(-40%,50%);">
                <i class="icon-wushuju iconfont"></i>
                暂无数据
              </div>
            </template>
          </el-table>
          <el-pagination class="right" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.pageNumber"
                         :page-sizes="page.pageSizes" :page-size="page.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import dasBoard from "@/views/dasboard/index";
import { queryFloorList, queryLostReportList, queryModel, queryReportList } from "@/api/model/report.js";
import { getSupplement, getToBeDelEquip } from "@/api/scan/request.js";
import axios from 'axios'

export default {
  components: {
    dasBoard
  },
  data() {
    return {
      params: null,
      ModelFileCount: null,// 模型文件夹数量
      modelFloorCount: null,// 包含楼层模型文件数量
      problemCount: 0,// 检查出问题的楼层模型文件数量
      tableList: [], // tab数据
      tableData: [],// 列表数据
      activeTab: '', // tab当前选中项
      headerStyle: { // 列表样式
        backgroundColor: '#e1e4e5',
        color: '#2b2b2b',
        lineHeight: '30px'
      },
      page: {
        pageSize: 50,
        pageSizes: [10, 20, 50, 100],
        pageNumber: 1,
        total: 0
      },
      loading: false,
      load: false,
      floorIconType: null,
      toBeSuppCount: 0,
      toBeDelCount: 0
    }
  },
  mounted() {
  },
  created() {
    this.params = {
      Orders: "Name asc"
    }
    this.getModelFileCount();
    this.getModelFloorCount();
  },
  computed: {
    ...mapGetters('layout', ['projectId'])
    },
    methods: {
      cellStyle({row, column, rowIndex, columnIndex}) {
        if (column.label !== '模型楼层' && column.label !== '待删除设备数量' && column.label !== '待补充设备数量' && column.label !== '有问题的检查项') {
          return {
            background: '#f3f3f3',
            lineHeight: '30px'
          }
        }
      },
      getModelFloorCount() {// 获取楼层模型文件数量，计算出检查出问题的模型文件
        let promise1 = new Promise(resolve => {
          queryFloorList({Filters:"Status=4",pageNumber:1,PageSize: 500}, res => {
            resolve(res);
          })
        })
        Promise.all([promise1]).then(response => {
          this.problemCount = 0;
          let res = response[0];
          this.modelFloorCount = res.Total;
          this.modelFloor = res.Content;
          this.getModelFileIcon();
          this.modelFloor.forEach(item => {
            if (!item.DataCheckResult) {
              this.problemCount++;
            }
          })
        })
      },
      getModelFileIcon() {// 计算文件夹的图标
        this.tableList.forEach(item => {
          this.modelFloor.forEach(it => {
            if (item.Code === it.FolderId) {
              if (!item.DataCheckResult) {
                item.flag = false;
              }
            }
          })
        })
      },
      getData(tab) {// 切换tab时执行
        this.getModelFloor();
      },
      getModelFileCount() {// 获取项目下所有模型文件夹
        queryModel(this.params, res => {
          this.ModelFileCount = res.Content.length;
          this.tableList = res.Content;
          if (this.tableList && this.tableList.length) {
            this.tableList.forEach((item, index) => {
              item.Code = item.Id;
            })
            this.activeTab = this.tableList[0].Code;// 默认选中第一个模型文件夹
          }
          this.getModelFloor();
        });
      },
      getModelFloor() {// 获取当前楼层下的模型楼层和各个检查项的数据
        let params = {
          ProjectId: this.projectId,
          Id: `${this.activeTab}`,
          PageNumber: this.page.pageNumber,
          PageSize: this.page.pageSize
        }
        queryReportList(params, res => {
          this.FloorName = res.Content;
          this.tableData = [];
          if (this.FloorName && this.FloorName.length) {
            this.loading = true;
            let i = 0;
            this.FloorName.forEach(item => {
              item.questionItem = 0;
              for (let key in item) {
                if (item[key] > 0 && key !== "FloorName" && key !== "questionItem") {
                  i += 1;
                  item.questionItem += 1;
                }
              }
            })
            this.floorIconType = i;
          }
          this.getLostModelFloor();
        })
      },
      getLostModelFloor() {// 获取缺失楼层
        let params = {
          ProjectId: this.projectId,
          Filters: `FolderId='${this.activeTab}';Status=4`
        }
        queryLostReportList(params, res => {
          this.LostFloorName = res.Content;
          this.getToBeCount();
        })
      },
      getToBeCount() {// 根据模型ID获取待删除数量和待补充数量
        let equipComDelList = [],
          toBeAdded = []
        this.equipComDelList = [];
        this.LostFloorName.forEach(item => {
          if (item.CurrentModelId) {
            equipComDelList.push({
              modelId: item.CurrentModelId
            });
            this.equipComDelList.push(item.CurrentModelId)
          } else {
            item.flag = 'lost';
            item.FloorName = `${item.Note + item.FloorName}`
          }
          if (item.Id) {
            toBeAdded.push({
              modelId: item.Id
            })
          }
        })
        let params = {
          projectId: this.projectId,
          data: equipComDelList
        }, paramsToBe = {
          projectId: this.projectId,
          data: toBeAdded
        }
        let promise1 = new Promise(resolve => {
          getToBeDelEquip(params, res => {
            resolve(res);
          })
        })
        let promise2 = new Promise(resolve => {
          getSupplement(paramsToBe, res => {
            resolve(res);
          })
        })
        Promise.all([promise1, promise2]).then(response => {
          let res = response[0];
          let res1 = response[1];
          this.toBeDelCount = 0;
          this.toBeSuppCount = 0;
          res.content.forEach(item => {
            if (item.count > 0) {
              this.toBeDelCount += 1;
            }
            this.LostFloorName.forEach(it => {
              if (item.modelId === it.CurrentModelId) {
                it.toBeDel = item.count;
              }
            })
          })
          res1.content.forEach(item => {
            if (item.count > 0) {
              this.toBeSuppCount += 1;
            }
            this.LostFloorName.forEach(it => {
              if (item.modelId === it.Id) {
                it.toBeSupplement = item.count;
              }
            })
          })
          if (this.LostFloorName && this.LostFloorName.length) {
            this.LostFloorName.forEach(item => {
              this.FloorName.forEach(it => {
                if (item.FloorName === it.FloorName) {
                  for (let key in it) {
                    item[key] = it[key];
                  }
                }
              })
            })
            this.tableData = this.LostFloorName;
          } else {
            this.tableData = [];
          }
          this.page.total = this.tableData.length;
          this.loading = false;
        })
      },
      del() {// 点击需从模型中删除的设备
        let equipComDelList = encodeURIComponent(JSON.stringify(this.equipComDelList));
        let jumpRouter = this.$router.resolve({ path: '/model/report/deleted', query: { equipComDelList: equipComDelList } })
        window.open(jumpRouter.href, '_blank')
      },
      supplement() {// 点击模型待补充的设备
        let equipComDelList = encodeURIComponent(JSON.stringify(this.equipComDelList));
        let jumpRouter = this.$router.resolve({ path: '/model/report/supplement', query: { equipComDelList: equipComDelList } })
        window.open(jumpRouter.href, '_blank')
      },
      getExportReport() {// 导出模型问题报告
        let that = this;
        this.load = true;
        axios({
          method: 'post',
          url: `/modelapi/report/non-blocking`,
          data: {
            Id: this.activeTab,
            ProjectId: this.projectId
          },
          headers: {
            ProjectId: this.projectId
          },
          responseType: 'blob'
        }).then(function (res) {
          if (res.data.type == 'application/vnd.ms-excel') {
            let blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8' });
            let fileName = decodeURI(res.headers['content-disposition']);
            if (fileName)
              fileName = fileName.substring(fileName.indexOf('=') + 1);
            if ('download' in document.createElement('a')) { // 非IE下载
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
              that.load = false;
            } else { // IE10+下载
              navigator.msSaveBlob(blob, fileName)
              that.load = false;
            }
          } else {
            let reader = new FileReader()
            reader.onload = e => {
              if (e.target.readyState === 2) {
                let res = {}
                that.load = false;
                res = JSON.parse(e.target.result)
                that.$message.error(res.Message);
              }
            }
            reader.readAsText(res.data)
          }
        })
      },
      tableRowClassName({ row, rowIndex, column }) {// 设置缺失楼层所在行的背景色
        if (row.flag && row.flag === 'lost') {
          return 'warning-row';
        }
      },
      handleSizeChange(val) {// 切换每页显示数量
        this.page.pageSize = val;
        this.getModelFloor();
      },
      handleCurrentChange(val) {// 切换页码
        this.page.pageNumber = val;
        this.getModelFloor();
      }
    },
    watch: {
      projectId() {
        this.getModelFileCount();
        this.getModelFloorCount();
      }
    }
  }
</script>

<style lang="less" scoped>
.report-index {
  .statistics {
    display: flex;
    width: 100%;
    padding: 20px 0;
    background: white;
    margin-bottom: 10px;

    div {
      flex: 1;
      text-align: center;

      p {
        b {
          font-size: 20px;
          margin-left: 20px;
        }
      }
    }
  }

  .main-content {
    width: 100%;
    height: calc(100% - 90px);
    background: white;

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

      .table {
        margin-top: 15px;
      }
    }
  }

  .button {
    padding-left: 10px;

  }

  .success-color {
    color: #67c23a;
  }

  .error-color {
    color: #f56c6c;
  }

  .success-color1 {
    color: #67c23a60;
  }

  .error-color1 {
    color: #f56c6c60;
  }

  /deep/ .el-table_1_column_4 {
    border-right: 1px solid #e2e2e2 !important;
  }

  /deep/ .el-table {
    .el-table__fixed {
      height: auto !important;
      bottom: 17px;
    }
  }

  /deep/ .el-table__row.warning-row {
    td {
      background: #f9f9f9 !important;
    }
  }

  /deep/ .el-badge__content--danger {
    background-color: #F56C6C60;
  }

}

</style>
