<template>
  <div class="table-container">
    <div class="table-list" :style="tableData && tableData.length?'height:calc(100% - 50px);':'height:100%;'">
      <el-table :data="tableData" style="width: 100%" height="100%" v-loading="loading" :header-cell-style="headerStyle">
        <el-table-column label="所属建筑楼层" show-overflow-tooltip min-width="100">
          <template slot-scope="scope">
            <div>
              {{scope.row.Building?scope.row.Building.BuildLocalName?scope.row.Building.BuildLocalName:'':''}} -
              {{scope.row.Floor?scope.row.Floor.FloorLocalName?scope.row.Floor.FloorLocalName:'':''}}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="`${inSpaceType}本地名称`" show-overflow-tooltip min-width="100">
          <template slot-scope="scope">
            <div>
              {{scope.row.EquipLocalName}}
              <el-badge v-if="scope.row.Equipment?scope.row.Equipment.Component?scope.row.Equipment.Component.length:false:false" 
                :value="scope.row.Equipment?scope.row.Equipment.Component?scope.row.Equipment.Component.length:0:0" class="item" type="warning">
              </el-badge>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="EquipLocalID" :label="`${inSpaceType}本地编码`" show-overflow-tooltip min-width="100"></el-table-column>
        <el-table-column prop="EquipCategory.EquipName" :label="`${inSpaceType}类型`" show-overflow-tooltip min-width="100"></el-table-column>
        <el-table-column prop="InstallLocation" label="安装位置" show-overflow-tooltip min-width="100"></el-table-column>
        <el-table-column prop="TaskState" label="任务执行情况" show-overflow-tooltip min-width="100"></el-table-column>
        <el-table-column prop="action" label="操作" min-width="100">
          <template slot-scope="scope">
            <i v-if="scope.row.TaskState == '待验证' || scope.row.TaskState == '未找到'" title="查看详情" class="iconfont icon-xiangqing table-button" @click="handleDetail(scope.$index, scope.row)"></i>
            <i v-if="scope.row.TaskState == '未找到'" title="重新生成任务" class="iconfont icon-Update table-button" @click="handleRegenerate(scope.$index, scope.row)"></i>
            <i v-if="scope.row.TaskState == '待验证'" title="删除任务" class="iconfont icon-delete table-button" @click="handleDelete(scope.$index, scope.row)"></i>
            <i v-if="scope.row.TaskState == '未找到'" title="认可此任务执行情况" class="iconfont icon-lijiqueren table-button" @click="handleConfirm(scope.$index, scope.row)"></i>
          </template>
        </el-table-column>
        <template slot="empty">
          <div style="height: 60%;transform: translateY(50%);">
            <i class="icon-wushuju iconfont"></i>
            数据暂无
          </div>
        </template>
      </el-table>
    </div>
    <el-pagination class="right" 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>
    <el-drawer title="任务详情" :visible.sync="drawer" direction="rtl" size="600px">
      <device-detail :detail="detailDevice"></device-detail>
    </el-drawer>
  </div>
</template>

<script>
import { queryDeviceTask, deleteDeviceTask, createDeviceTask, updateDeviceTask } from "@/api/data_admin/buildTaskApi"
import tools from "@/utils/tools"
import { mapGetters } from "vuex"
import deviceDetail from '../detail/deviceDetail'
export default {
  components: {
    deviceDetail
  },
  computed: {
    ...mapGetters("layout", ["projectId"])
  },
  props: {
    paramsData: Object,
  },
  data() {
    return {
      inSpaceType: '设备',
      loading: false, // loading
      drawer: false, // 详情侧弹窗
      detailDevice: {},
      tableData: [], //列表数据
      page: {
        pageSize: 50,
        pageSizes: [10, 20, 50, 100],
        pageNumber: 1,
        total: 0
      },
      taskStateMap: {
        '-1': '未找到',
        '0': '已完成',
        '1': '待验证'
      },
      headerStyle: {
        backgroundColor: '#e1e4e5',
        color: '#2b2b2b',
        lineHeight: '30px'
      }, // 列表样式
    };
  },
  methods: {
    // 获取列表数据
    getTableData() {
      let params = {
        Filters: `ProjectId='${this.projectId}'`,
        Cascade: [
          {
            Name: 'component'
          }, {
            Name: 'scanScheme'
          }, {
            Name: 'building',
          }, {
            Name: 'floor',
          }, {
            Name: 'equipCategory'
          }
        ],
        Orders: "CreateTime desc, TaskId asc",
        PageNumber: this.page.pageNumber,
        PageSize: this.page.pageSize
      }
      if (this.paramsData.buildfloor[0] == "noKnow") {
        params.Filters += `;BuildingId isNull`
      } else if (this.paramsData.buildfloor[0] && this.paramsData.buildfloor[0] != "all") {
        params.Filters += `;BuildingId='${this.paramsData.buildfloor[0]}'`
        if (this.paramsData.buildfloor[1] == "noKnow") {
          params.Filters += `;FloorId isNull`
        } else if (this.paramsData.buildfloor[1] && this.paramsData.buildfloor[1] != "all") {
          params.Filters += `;FloorId='${this.paramsData.buildfloor[1]}'`
        }
      }
      if(this.paramsData.taskState !== ''){
        params.Filters += `;TaskState=${this.paramsData.taskState}`
      }
      if(this.paramsData.deviceCategory){
        params.Filters += `;Category='${this.paramsData.deviceCategory}'`
      }
      queryDeviceTask(params, res => {
        this.page.total = res.Total;
        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.TaskState = this.taskStateMap[item.TaskState]
          return item
        })
      })
    },
    // 删除关系
    handleDelete(index, row) {
      this.$confirm("确认删除该任务？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = [{TaskId: row.TaskId}]
        deleteDeviceTask(params, res => {
          this.$message.success('删除成功')
          this.getTableData()
        })
      }).catch(() => {
        this.$message("取消删除")
      })
    },
    //重新生成任务
    handleRegenerate(index, row){
      let params = {
        Content: [{
          EquipId: row.EquipId,
          TaskState: -1
        }]
      }
      createDeviceTask(params, res => {
        this.$message.success('重新生成任务成功！')
        this.getTableData()
      })
    },
    //认可此任务执行情况
    handleConfirm(index, row){
      let params = {
        Content: [{
          TaskId: row.TaskId,
          TaskState: 0
        }]
      }
      updateDeviceTask(params, res => {
        this.$message.success('更新成功！')
        this.getTableData()
      })
    },
    //查看任务详情
    handleDetail(index, row) {
      this.drawer = true
      this.detailDevice = row
    },
    // 改变pagesize
    handleSizeChange(pageSize) {
      this.page.pageNumber = 1
      this.page.pageSize = pageSize;
      this.getTableData()
    },
    // 改变pageno
    handleCurrentChange(pageNo) {
      this.page.pageNumber = pageNo;
      this.getTableData()
    }
  },
  watch: {
    paramsData: {
      handler(newName, oldName) {
        if(!tools.isSimilarly(newName, oldName)){
          this.page.pageNumber = 1
          this.getTableData()
        }
      },
      immediate: true,
      deep: true
    },
    projectId() {
      this.page.pageNumber = 1
      this.getTableData()
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .el-drawer__body {
  height: calc(100% - 80px);
  border-top: 1px solid #c9c9c9;
}
/deep/ .el-drawer__header {
  margin-bottom: 12px;
}
.table-container {
  height: 100%;
  background: #fff;
  .table-button{
    cursor: pointer;
    margin-right: 15px;
  }
}
</style>