<template>
  <div class="app-container">
    <div class="search-div">
      <el-form ref="selectForm" :inline="true" :model="listQuery" class="form-container">
        <el-row>
          <el-form-item class="selectForm-container-item" prop="keyword">
            <el-input v-model.trim="listQuery.keywords" placeholder="设备编号" clearable/>
          </el-form-item>
          <el-form-item class="selectForm-container-item">
            <area-select-tree v-model="listQuery.areaid" :need-top="false" :dept-show="true" placeholder="区域"/>
          </el-form-item>
          <el-form-item class="selectForm-container-item">
            <el-select v-model="listQuery.status" placeholder="设备状态" clearable>
              <el-option label="在线" value="1"/>
              <el-option label="离线" value="0"/>
            </el-select>
          </el-form-item>
          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        </el-row>
      </el-form>
    </div>
    <!--查询结果Table显示-->
    <div>
      <el-row class="table-title">
        <el-col :span="6"><div class="title-header"><i class="el-icon-menu"/>设备列表</div></el-col>
        <el-col :span="12" :offset="6" class="edit_btns">
          <!--<el-button class="edit_btn" size="small" @click="syncRecords">同步识别记录</el-button>-->
          <!--<el-button class="edit_btn" size="small" @click="updateData">设备数据初始化</el-button>-->
          <el-button class="edit_btn" size="small" @click="del">删除</el-button>
          <el-button class="edit_btn" size="small" @click="add">新增</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="listLoading" :data="list" class="table" border @selection-change="handleSelectionChange">
        <el-table-column v-if="hasPerm('/device/delete')" align="center" type="selection" width="55"/>
        <el-table-column :index="indexMethod" align="center" type="index" label="序号" width="55"/>
        <el-table-column v-for="column in columns" :key="column.value" :label="column.text" :width="column.width" :align="column.align" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="column.type!='Button'" :class="column.class">{{ scope.row[column.value] }}</span>
            <el-button v-if="column.type=='Button'" type="text" @click="showWellDetail(scope.row)">{{ scope.row[column.value] }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template slot-scope="scope">
            <el-button v-if="hasPerm('/device/update')" type="text" @click="edit(scope.row)">编辑</el-button>
            <!--<el-button v-if="hasPerm('/device/update')" type="text" @click="del(scope.row)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页-->
    <div class="pagination-container">
      <el-pagination
        v-show="total>listQuery.limit"
        :current-page="listQuery.offset"
        :page-sizes="[20,30,50,100]"
        :page-size="listQuery.limit"
        :total="total"
        align="center"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>
    <edit-device v-show="editShow" ref="editdevice" @watchChild="fetchData"/>
    <detail-device v-show="detailShow" ref="detaildevice"/>
    <sync-record v-show="syncRecordShow" ref="syncRecord"/>
  </div>
</template>

<script>
import editDevice from '@/views/deviceManage/editDevice'
import detailDevice from '@/views/deviceManage/detailDevice'
import syncRecord from '@/views/deviceManage/syncRecord'
import selectTree from '@/components/SelectTree/singleSelect'
import { getDeviceList, delDevice, updateDB } from '@/api/device'
import DownloadTemplate from '@/components/DownloadTemplate'
import DeptSelect from '@/components/DeptSelect/index'
import AreaSelectTree from '@/components/AreaSelect/areaSelectTree'
export default {
  name: 'ListDevice',
  components: { DeptSelect, DownloadTemplate, editDevice, detailDevice, syncRecord, selectTree, AreaSelectTree },
  data() {
    return {
      listQuery: {
        areaid: '',
        keywords: '',
        devType: '',
        status: '',
        offset: 1,
        limit: 20,
        sort: 'id',
        order: 'asc'
      }, // 筛选条件
      columns: [
        {
          text: '设备编号',
          value: 'devCode',
          align: 'center',
          width: 140
        },
        {
          text: '设备名称',
          value: 'devName',
          align: 'center'
        },
        {
          text: '安装位置',
          value: 'description',
          align: 'center'
        },
        {
          text: '控制器类型',
          value: 'devTypeName',
          align: 'center'
        },
        {
          text: '设备IP',
          value: 'devIp',
          align: 'center'
        },
        {
          text: '设备状态',
          value: 'status',
          align: 'center'
        },
        {
          text: '关联门禁编号',
          value: 'doorCode',
          align: 'center'
        },
        {
          text: '关联门禁名称',
          value: 'doorName',
          align: 'center'
        }
      ], // 显示列
      multipleSelection: [], // 多选选中项
      list: [], // 列表数据
      total: 0, // 数据总数
      deviceTypeList: [], // 设备类型列表
      deptProps: {
        parent: 'pid',
        value: 'id',
        label: 'name',
        children: 'children'
      }, // 权属单位树形下拉菜单
      deptTreeList: null, // 组织树列表数据
      showDeptTree: 0, // 是否显示权属单位下拉
      showDeviceType: true, // 是否显示设备类型下拉
      fileList: [],
      listLoading: true, // 加载动画
      fullscreenLoading: false, // 全屏加载动画
      editShow: false, // 是否显示编辑框
      detailShow: false, // 是否显示编辑框
      syncRecordShow: false, // 是否显示同步记录框
      filename: 'device_template.xlsx',
      deptShowTop: false, // 是否显示顶级
      wellShow: false
    }
  },
  mounted() {
    // this.fetchDeviceType()// 获取设备类别
    if (this.$route.query.devType !== null && this.$route.query.devType !== '' && this.$route.query.devType !== undefined) {
      this.listQuery.devType = this.$route.query.devType // 接收路由参数
    }
    if (this.$route.query.status !== null && this.$route.query.status !== '' && this.$route.query.status !== undefined) {
      this.listQuery.status = this.$route.query.status // 接收路由参数
    }
    this.fetchData()// 获取数据
    // this.websocket()
  },
  methods: {
    websocket() {
      console.log(this.$store.state)
      if (!this.$store.state.websocket.wsStatus) {
        this.$store.dispatch('initWebSocket')
      }
    },
    // 检查选择情况
    checkSelection() {
      if (this.multipleSelection.length === 0) {
        return false
      } else {
        return true
      }
    },
    // 新增设备
    add() {
      this.dialogFormVisible = true
      this.editShow = true
      this.$refs.editdevice.initDialog('create', this.dialogFormVisible)
    },
    // 编辑设备信息
    edit(row) {
      this.dialogFormVisible = true
      this.editShow = true
      this.$refs.editdevice.initDialog('update', this.dialogFormVisible, row)
    },
    // 删除设备
    del() {
      if (this.checkSelection()) {
        const deviceIds = []
        this.multipleSelection.forEach(function(value, index) {
          deviceIds.push(value.id)
        })
        // wellNames = wellNames.slice(0, wellNames.length - 1)
        this.$confirm(
          '确定要删除所选设备吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          delDevice(deviceIds).then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.fetchData(false)
            }
          })
        })
      } else {
        this.$message.error('至少选中一项')
      }
    },
    // 删除设备
    updateData() {
      if (this.checkSelection()) {
        const deviceIds = []
        this.multipleSelection.forEach(function(value, index) {
          deviceIds.push(value.id)
        })
        this.$confirm(
          '确定要将数据下发到所选设备吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          updateDB(deviceIds).then(response => {
            if (response.code === 200) {
              this.$message.success('下发更新指令成功，等待设备更新数据')
              this.fetchData()
            }
          })
        })
      } else {
        this.$message.error('至少选中一项')
      }
    },
    syncRecords() {
      if (this.checkSelection()) {
        const deviceIds = []
        this.multipleSelection.forEach(function(value, index) {
          deviceIds.push(value.id)
        })
        console.log(deviceIds)
        this.dialogFormVisible = true
        this.syncRecordShow = true
        this.$refs.syncRecord.initDialog(this.dialogFormVisible, deviceIds)
      } else {
        this.$message.error('至少选中一项')
      }
    },
    // 查询数据
    search() {
      this.fetchData(false)
    },
    // 获取设备列表
    fetchData(isNowPage = true) {
      this.listLoading = true
      if (!isNowPage) { // 是否显示当前页，否则跳转第一页
        this.listQuery.offset = 1
      }
      getDeviceList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = parseInt(response.data.total)
        this.listLoading = false
      })
    },
    showWellDetail(row) {
      this.wellShow = true
      this.$refs.wellInfo.initDialog(row.wellId)
    },
    indexMethod(index) {
      return this.listQuery.limit * (this.listQuery.offset - 1) + index + 1
    },
    // 改变页容量
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    // 改变当前页
    handleCurrentChange(val) {
      this.listQuery.offset = val
      this.fetchData()
    },
    // 多选触发方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  $tableTitleHeight:46px;
  .table{
    margin-bottom: 20px;
  }
  .pagination-container{
    margin-bottom: 50px;
  }
  .table-title{
    background-color:rgba(243, 243, 243, 1);
    height: $tableTitleHeight;
    .title-header{
      line-height:$tableTitleHeight;
      color: #606266;
      font-size: 15px;
      i{
        margin-left: 5px;
        margin-right: 5px;
      }
    }
  }
  .edit_btns{
    .edit_btn{
      float:right;
      margin:7px 3px;//为了需要居中显示margin-top和bottom要用$tableTitleHeight减去按钮原高度除以2
    }
  }
</style>
