<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose" width="900px" id="addEqDialog">
    <div class="table-box">
      <el-table :data="tableData" style="width: 100%" height="350" v-loading="loading" :header-cell-style="headerStyle"
                ref="multipleTable" :row-class-name="getRowClassName"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="expand">
          <template slot-scope="props">
            <p v-if="props.row.ComponentCount && props.row.ComponentCount.length"
               style="color:#99a9bf;line-height:32px;font-size:14px;">包含的部件：</p>
            <el-form label-position="left" label-width="auto" inline class="demo-table-expand"
                     v-if="props.row.ComponentCount && props.row.ComponentCount.length">
              <el-form-item v-for="item in props.row.ComponentCount?props.row.ComponentCount:[]" :key="item.code"
                            :label="`${item.name}：`">
                <span>{{ item.count }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="folderName" label="所属模型文件夹" width="110" show-overflow-tooltip></el-table-column>
        <el-table-column prop="fileName" label="模型文件名" width="80" show-overflow-tooltip></el-table-column>
        <el-table-column label="设备本地名称" show-overflow-tooltip width="100">
          <template slot-scope="scope">
            <div>
              {{ scope.row.localName }}
              <el-badge v-if="scope.row.component&&scope.row.component.length?true:false"
                        :value="scope.row.component&&scope.row.component.length?scope.row.component.length:0"
                        class="item" type="warning">
              </el-badge>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="localId" label="设备本地编码" show-overflow-tooltip width="100"></el-table-column>
        <el-table-column prop="equipCategory.name" label="设备类" show-overflow-tooltip width="120"></el-table-column>
        <el-table-column prop="bimId" label="BIM Id" show-overflow-tooltip width="80"></el-table-column>
        <el-table-column prop="type" label="现场验证操作规定" width="150">
          <template slot-scope="scope">
            <el-select style="width:100px;" v-model="scope.row.schemeId" placeholder="请选择">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <template slot="empty">
          <div style="height: 60%;transform: translateY(50%);">
            <i class="icon-wushuju iconfont"></i>
            暂无数据
          </div>
        </template>
      </el-table>
      <!-- 分页 -->
      <el-pagination class="fr" v-show="tableData && tableData.length" @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>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="$emit('update:dialogVisible',false)">返回重选</el-button>
      <el-button size="small" type="primary" @click="savaRelation">确认创建</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { queryEquip } from "@/api/object/equip";
import { createModelTask, queryModelDiglog } from "@/api/data_admin/buildTaskApi"
import { mapGetters } from "vuex"

export default {
  components: {},
  computed: {
    ...mapGetters("layout", ["projectId"])
  },
  data() {
    return {
      title: "确认创建任务",
      options: [{//方案
        value: '1',
        label: '极简'
      }, {
        value: '2',
        label: '标准'
      }],
      tableData: [],
      loading: false,
      selections: [], // 选中项
      page: {
        pageSize: 50,
        pageSizes: [10, 20, 50, 100],
        pageNumber: 1,
        total: 0
      },
      headerStyle: {
        backgroundColor: '#e1e4e5',
        color: '#2b2b2b',
        lineHeight: '30px'
      } // 列表样式
    };
  },
  props: {
    dialogVisible: Boolean,//是否显示弹窗
    params: Object, //模型和设备的信息
    newTaskTypes: Array
  },
  created() {

  },
  methods: {
    getTableData() {
      this.loading = true

      let params = {
        cascade: [
          {
            name: "equipCategory",
            projection: ["code", "name"]
          },
          {
            name: "component",
            cascade: [{ name: "equipCategory" }]
          },
          {
            name: "building",
            projection: ["localName", "name", "id"]
          },
          {
            name: "floor",
            projection: ["localName", "name", "id"]
          }
        ],
        filters: `projectId='${this.projectId}'`,
        orders: "createTime desc, id asc",
        pageNumber: this.page.pageNumber,
        pageSize: this.page.pageSize
      }

      if (this.params.isVerification) {
        // params.Filters += `;(TaskState isNull || TaskState=0 || TaskState=-1)`
        // params.Filters += `;(TaskState!=0 || TaskState!=-1 || TaskState!=1)`
        params.filters += `;taskState isnull`
      } else {
        // params.Filters += `;(TaskState!=1)`
        params.filters += `;(taskState isnull or taskState !=1 )`
      }

      if (this.params.device) {
        params.filters += `;classCode='${this.params.device}'`
      }

      if (this.params.spaceList && this.params.spaceList.length) {
        //通过平面图区域查询
        // console.log(this.params,'this.params')
        let arr = []
        this.params.spaceList.forEach(i => {
          let list = `${this.projectId}${this.params.modelFolderId}${this.params.modelFileName}:${i}`
          arr.push(list)
        })
        let param = {
          modelId: this.params.CurrentModelId,
          idList: arr,
          classCode: this.params.device || '',
          filters: this.params.device ? `classCode='${this.params.device}` : undefined,
          pageNumber: this.page.pageNumber,
          pageSize: this.page.pageSize
        }
        // console.log(param,'param')
        queryModelDiglog(param, res => {
          this.loading = false
          this.dataFormatter(res)
        })
      } else {
        params.filters += `;modelId='${this.params.CurrentModelId}'`
        queryEquip(params, res => {
          this.loading = false
          this.dataFormatter(res)
        })
      }

    },
    // 表格数据格式化
    dataFormatter(res) {
      this.tableData = res.content.length && res.content.map(item => {
        if (item.component && item.component.length) {
          item.ComponentCount = []
          item.component.map(parts => {
            if (parts.equipCategory && parts.equipCategory.code && parts.equipCategory.name) {
              let index = item.ComponentCount.findIndex(c => {
                return c.code == parts.equipCategory.code
              })
              if (index != -1) {
                item.ComponentCount[index].count++
              } else {
                item.ComponentCount.push({
                  name: parts.equipCategory.name,
                  code: parts.equipCategory.code,
                  count: 1
                })
              }
            }
          })
        }
        item.folderName = this.params.modelFolderName
        item.floorId = this.params.modelFolderId
        item.fileName = this.params.modelFileName
        item.fileId = this.params.CurrentModelId
        // 后端定义默认值(前端取消默认值设定)
        // item.SchemeId = "1"
        return item
      })
      this.page.total = res.total
    },
    getRowClassName({row, rowIndex}){
        if (!(row.ComponentCount && row.ComponentCount.length)) {
            return 'row-expand-cover';
        }
    },
    //选中项修改
    handleSelectionChange(val) {
      this.selections = val;
    },
    savaRelation() {
      if (this.selections.length) {
        let list = this.selections.map((item) => {
          if (item.schemeId) {
            return {
              equipId: item.id,
              fileId: item.fileId,
              fileName: item.fileName,
              folderId: item.folderId,
              folderName: item.folderName,
              schemeId: item.schemeId
            }
          } else {
            return {
              equipId: item.id,
              fileId: item.fileId,
              fileName: item.fileName,
              folderId: item.folderId,
              folderName: item.folderName,
            }
          }
        })
        let params = {
          content: list
        }
        createModelTask(params, res => {
          this.$emit('update:dialogVisible', false)
          this.$message.success('创建成功！')
          this.$router.push({ name: 'buildTask', query: { newTaskTypes: this.newTaskTypes } })//跳转回首页
        })
      } else {
        this.$message('请选择要创建的任务！')
      }
    },
    //改变pagesize
    handleSizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getTableData();
    },
    //改变pageno
    handleCurrentChange(pageNo) {
      this.page.pageNumber = 1
      this.page.pageNumber = pageNo;
      this.getTableData();
    },
    handleClose() {//关闭弹窗
      this.$emit('update:dialogVisible', false);
    }
  },
  watch: {
    dialogVisible(newData, oldData) {
      if (newData) {
        this.tableData = []
        this.page.pageNumber = 1
        this.getTableData()
      }
    }
  },
};
</script>
<style lang="less" scoped>
#addEqDialog {
  .filters {
    margin-bottom: 10px;

    /deep/ .el-input__inner {
      vertical-align: baseline;
    }
  }

  .table-box {
    height: 370px;

    .fr {
      margin-top: 10px;
    }
  }
}
</style>

<style>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.row-expand-cover .el-table__expand-icon{
    visibility:hidden;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  margin-left: 120px;
  width: 100%;
}
</style>
