<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"
        @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 prop="EquipLocalName" label="设备本地名称" show-overflow-tooltip width="100"></el-table-column>
        <el-table-column prop="EquipLocalID" label="设备本地编码" show-overflow-tooltip width="100"></el-table-column>
        <el-table-column prop="EquipCategory.EquipName" 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/scan/request"
  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: ["EquipCode", "EquipName"]
          },
          {
            Name: "component",
            Cascade: [{ Name: "equipCategory" }]
          },
          {
            Name: "building",
            Projection: ["BuildLocalName", "BuildName", "BuildID"]
          },
          {
            Name: "floor",
            Projection: ["FloorLocalName", "FloorName", "FloorID"]
          }
        ],
        Filters: `ProjectId='${this.projectId}'`,
        Orders: "CreateTime desc, EquipID 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)`
      } else {
        params.Filters += `;(TaskState!=1)`
      }

      if (this.params.device) {
        params.Filters += `;Category='${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,
          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.map(item => {
        if (item.Component && item.Component.length) {
          item.ComponentCount = []
          item.Component.map(parts => {
            if (parts.EquipCategory && parts.EquipCategory.EquipCode && parts.EquipCategory.EquipName) {
              let index = item.ComponentCount.findIndex(c => { return c.code == parts.EquipCategory.EquipCode })
              if (index != -1) {
                item.ComponentCount[index].count++
              } else {
                item.ComponentCount.push({
                  name: parts.EquipCategory.EquipName,
                  code: parts.EquipCategory.EquipCode,
                  count: 1
                })
              }
            }
          })
        }
        item.FolderName = this.params.modelFolderName
        item.FolderId = this.params.modelFolderId
        item.FileName = this.params.modelFileName
        item.FileId = this.params.CurrentModelId
        // 后端定义默认值(前端取消默认值设定)
        // item.SchemeId = "1"
        return item
      })
      this.page.total = res.Total
    },
    //选中项修改
    handleSelectionChange(val) {
      this.selections = val;
    },
    savaRelation() {
      if (this.selections.length) {
        let list = this.selections.map((item) => {
          if (item.SchemeId) {
            return {
              EquipId: item.EquipID,
              FileId: item.FileId,
              FileName: item.FileName,
              FolderId: item.FolderId,
              FolderName: item.FolderName,
              SchemeId: item.SchemeId
            }
          } else {
            return {
              EquipId: item.EquipID,
              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;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  margin-left: 120px;
  width: 100%;
}
</style>
