<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>
        <floor-cascader ref="floorCascader" @change="changeFloor"></floor-cascader>
        <my-cascader ref="cascader" @change="changeDevice"></my-cascader>
        <el-input placeholder="请输入安装位置" style="width: 200px;margin-left:20px;" v-model="keycode" clearable @keyup.enter.native="getTableData">
          <i slot="suffix" class="el-input__icon el-icon-search" style="cursor:pointer;" @click="getTableData"></i>
        </el-input>
        <el-button style="float:right;margin-top:1px;" @click="handleClickCreate">创建已选</el-button>
      </div>
      <div class="main" :style="tableData && tableData.length?'height: calc(100% - 96px);':'height: calc(100% - 46px);'">
        <el-table ref="multipleTable" :data="tableData" v-loading='loading' stripe height="100%" @selection-change="handleSelectionChange" :header-cell-style="headerStyle">
          <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 label="所属建筑楼层" width="200"></el-table-column>
          <el-table-column prop="EquipLocalName" label="设备本地名称" show-overflow-tooltip>
             <template slot-scope="scope">
              <div>
                {{scope.row.EquipLocalName}}
                <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="EquipLocalID" label="设备本地编码" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column prop="EquipCategory.EquipName" label="设备类"></el-table-column>
          <el-table-column prop="LedgerParam.Siteinstall.InstallLocation" label="安装位置"></el-table-column>
          <el-table-column prop="type" label="现场验证操作规定" width="200">
            <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>
      </div>
      <div class=footer>
        <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>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex"
//组件
import floorCascader from "@/components/ledger/lib/floorCascader"
import myCascader from "@/components/ledger/lib/cascader"
//api
import { queryEquip } from "@/api/scan/request"
import { createDeviceTask } from "@/api/data_admin/buildTaskApi"
export default {
  data() {
    return {
      params: {},
      loading: false,
      keycode: '',
      page: {
        pageSize: 50,
        pageSizes: [10, 20, 50, 100],
        pageNumber: 1,
        total: 0
      },
      options: [{//方案
        value: '1',
        label: '标准'
      }],
      tableData: [],
      multipleSelection:[],
      headerStyle: {
        backgroundColor: '#e1e4e5',
        color: '#2b2b2b',
        lineHeight: '30px'
      }, // 列表样式
    }
  },
  computed: {
    ...mapGetters("layout", ["projectId", "userId", "secret"])
  },
  components: {
    floorCascader,
    myCascader
  },
  created() {
    this.params = this.$route.query
    console.log(this.params)
  },
  mounted() {
    this.getTableData()
  },
  watch: {
    projectId() {
      this.page.pageNumber = 1
      this.multipleSelection = []
      this.getTableData()
    }
  },
  methods: {
    //返回
    goBack() {
      this.$router.push({ name: "buildTask" })
    },
    //选择设备或部件
    changeDevice(val) {
      if(val.code) {
        this.params.category = val.code
      } else {
        this.params.category = ''
      }
      this.page.pageNumber = 1
      this.getTableData()
    },
    //选择建筑楼层
    changeFloor(value) {
      if (value[0]) {
        this.params.buildId = value[0]
      }
      if (value[1]) {
        this.params.floorId = value[1]
      } else {
        this.params.floorId = ''
      }
      this.page.pageNumber = 1
      this.getTableData()
    },
    //获取表格数据
    getTableData() {
      this.loading = true
      let param = this.formatFilter()
      queryEquip(param, 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.SchemeId = "1"
          return item
        })
        this.page.total = res.Total
        this.loading = false
      })
    },
    //格式化条件
    formatFilter() {
      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`
      }

      if(this.keycode){
        params.Filters += `;LedgerParam.Siteinstall.InstallLocation contain '${this.keycode}'`
      }

      if(this.params.category){
        params.Filters += `;Category='${this.params.category}'`
      }

      if (this.params.buildId == "noKnow") {
        params.Filters += `;BuildingId isNull`
      } else if (this.params.buildId && this.params.buildId != "all") {
        params.Filters += `;BuildingId='${this.params.buildId}'`
      }

      if (this.params.floorId == "noKnow") {
        params.Filters += `;FloorId isNull`
      } else if (this.params.floorId && this.params.floorId != "all") {
        params.Filters += `;FloorId='${this.params.floorId}'`
      }
      return params
    },
    //选择的设备或部件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //切换每页显示多少条数据
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    //切换页数
    handleCurrentChange(val) {
      this.page.pageNumber = val
      this.getTableData()
    },
    //创建已选
    handleClickCreate() {
      let list = this.multipleSelection.map((item) => {
        return {EquipId: item.EquipID}
      })
      let param = {
        Content: list
      }
      createDeviceTask(param, res => {
        this.$message.success("创建成功!")
        this.$router.push({ name: "buildTask",query:{ newTaskTypes:this.$route.query.newTaskTypes } })
      })
    }
  }
};
</script>

<style scoped lang='less'>
.box {
  .condition {
    padding: 10px;
    display: flex;
    height: 100%;
    flex-direction: column;
    border: 1px solid #dfe6ec;
    background: #fff;
    .header{
      padding-bottom: 10px;
      border-bottom: 1px solid #bcbcbc;
    }
    .main{
      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>