<!--路灯列表-->
<template>
  <div class="app-container">
    <!--筛选条件-->
    <div class="search-div">
      <div class="search-left">
        <el-form ref="selectForm" :inline="true" :model="listQuery" class="form-container">
          <el-row>
            <el-col :span="4">
              <el-form-item class="selectForm-container-item">
                <el-input v-model.trim="listQuery.keyword" placeholder="关键词" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item class="selectForm-container-item">
                <el-select v-model="listQuery.lampType" placeholder="路灯类型" clearable>
                  <el-option v-for="item in typeList" :key="item.id" :label="item.typeName" :value="item.id"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item class="selectForm-container-item">
                <el-select v-model="listQuery.streetId" placeholder="所在道路" filterable clearable>
                  <el-option v-for="item in streetList" :key="item.id" :label="item.streetName" :value="item.id"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item class="selectForm-container-item">
                <el-select v-model="listQuery.status" placeholder="路灯状态" clearable>
                  <el-option v-for="item in statusList" :key="item.value" :label="item.name" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6" class="search-right">
              <el-button class="filter-item" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </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 v-if="hasPerm('/lamp/delete')" class="edit_btn" size="small" @click="del">删除</el-button>
          <el-button class="edit_btn" size="small" @click="add">新增</el-button>
          <el-button class="edit_btn" size="small" @click="batchExport">导出</el-button>
          <el-upload
            :limit="1"
            :show-file-list="false"
            :http-request="uploadFile"
            :file-list="fileList"
            class="edit_btn"
            style=" display: inline;"
            action="string"
            accept=".xls,.xlsx">
            <el-button size="small">批量导入</el-button>
          </el-upload>
        </el-col>
      </el-row>
      <el-table v-loading="listLoading" :data="list" class="table" border @selection-change="handleSelectionChange">
        <!--拥有删除权限则显示复选框-->
        <el-table-column v-if="hasPerm('/lamp/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 :class="column.class">{{ scope.row[column.value] }}</span>
          </template>
        </el-table-column>
        <!--操作列-->
        <el-table-column label="操作" align="center" width="160">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="detail(scope.row)">详情</el-button>
            <el-button v-if="hasPerm('/lamp/edit')" type="text" size="small" @click="edit(scope.row)">编辑</el-button>

            <el-button v-if="hasPerm('/lamp/remoteOn')" type="text" size="small">开灯</el-button>
            <el-button v-if="hasPerm('/lamp/remoteOff')" type="text" size="small">关灯</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]"
        :page-size="listQuery.limit"
        :total="total"
        align="center"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>
    <edit-Lamp ref="editLamp" @watchChild="fetchData"/>
  </div>
</template>

<script>
import DeptSelect from '@/components/DeptSelect'
import EditLamp from '@/views/deviceManage/editLamp'
import { getLampList, batchDelLamp, batchExportLamp } from '@/api/system/device'
import { getAllLampType } from '@/api/system/base'
import { getAllStreet } from '@/api/system/area'
import { batchImportLamp } from '@/api/system/fileImport'
export default {
  name: 'BusLamp',
  components: { EditLamp, DeptSelect },
  data() {
    return {
      fileList: [], // 批量导入
      listQuery: {
        keyword: '',
        lampType: '',
        streetId: '',
        status: '',
        offset: 1,
        limit: 20,
        sort: '',
        order: ''
      }, // 筛选条件
      columns: [
        {
          text: '路灯编号',
          value: 'lampCode',
          align: 'center',
          width: 140
        },
        {
          text: '路灯名称',
          value: 'lampName',
          align: 'center'
        },
        {
          text: '路灯类型',
          value: 'lampTypeName',
          align: 'center'
        },
        // {
        //   text: '电信设备编号',
        //   value: 'teleId',
        //   align: 'center'
        // },
        {
          text: '所在道路',
          value: 'streetName',
          align: 'center'
        },
        {
          text: '关联控制器',
          value: 'controllerCode',
          align: 'center'
        },
        {
          text: '关联灯杆',
          value: 'lamppostName',
          align: 'center'
        },
        {
          text: '路灯状态',
          value: 'statusName',
          align: 'center'
        }
      ], // 显示列
      list: [], // 列表数据
      total: 0, // 数据总数
      typeList: [], // 灯杆类型列表
      streetList: [], // 道路列表
      multipleSelection: [], // 多选选中项
      statusList: [{ value: '1', name: '开灯' }, { value: '2', name: '关灯' }, { value: '3', name: '报警' }, { value: '4', name: '离线' }],
      listLoading: false, // 加载动画
      fullscreenLoading: false, // 全屏加载动画
      dialogFormVisible: false
    }
  },
  created() {
    this.fetchLampType()// 获取设备类别
    this.fetchStreetList() // 获取道路列表
    this.fetchData()// 获取数据
  },
  methods: {
    // 批量导入
    uploadFile(param) {
      // 判断文件大小是否符合要求
      const _file = param.file
      const isLt5M = _file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('请上传5M以下的excel文件')
        return false
      }
      // 全屏加载动画
      const loading = this.$loading({
        lock: true,
        text: '导入中,请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // 批量导入上传请求
      batchImportLamp(_file).then(res => {
        loading.close() // 关闭加载动画
        if (res.code === 200) {
          this.$message.success('导入成功')
          this.fileList = []
          this.fetchData()
        } else {
          this.$message.error(res.message)
        }
      }).catch(err => {
        loading.close()
        this.$message.error(err.message)
      })
      this.fileList = []
    },
    batchExport() {
      // 全屏加载动画
      const loading = this.$loading({
        lock: true,
        text: '下载中,请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      batchExportLamp(this.listQuery).then(res => {
        loading.close() // 关闭加载动画
        console.log('download===', res)
        const blob = new Blob([res.data])
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = `路灯列表.xlsx` // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放blob对象
      }).catch((res) => {
        loading.close()
        this.$message.error(res.message)
      })
    },
    // 检查选择情况
    checkSelection() {
      if (this.multipleSelection.length === 0) {
        return false
      } else {
        return true
      }
    },
    // 重置
    clearInput() {
      this.listQuery = {
        keyword: '',
        lampType: '',
        streetId: '',
        status: '',
        offset: 1,
        limit: 20,
        sort: '',
        order: ''
      }
      this.fetchData(false)
    },
    // 新增设备
    add() {
      this.dialogFormVisible = true
      this.$refs.editLamp.initDialog('create', this.dialogFormVisible)
    },
    detail(row) {
      this.dialogFormVisible = true
      this.$refs.editLamp.initDialog('detail', this.dialogFormVisible, row)
    },
    // 编辑设备信息
    edit(row) {
      this.dialogFormVisible = true
      this.$refs.editLamp.initDialog('update', this.dialogFormVisible, row)
    },
    // 删除设备
    del() {
      if (this.checkSelection()) {
        const devIds = []
        this.multipleSelection.forEach(function(value, index) {
          devIds.push(value.id)
        })
        this.$confirm(
          '确定要删除所选路灯吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          batchDelLamp(devIds).then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.fetchData()
            }
          })
        })
      } else {
        this.$message.error('至少选中一项')
      }
    },
    // 查询数据
    search() {
      this.fetchData(false)
    },
    // 获取设备列表
    fetchData(isNowPage = true) {
      this.listLoading = true
      if (!isNowPage) { // 是否显示当前页，否则跳转第一页
        this.listQuery.offset = 1
      }
      getLampList(this.listQuery).then(response => {
        if (response.code === 200) {
          this.list = response.data.rows
          this.total = parseInt(response.data.total)
        } else {
          this.$message.error(response.message)
        }
        this.listLoading = false
      })
    },
    fetchLampType() {
      getAllLampType().then(response => {
        if (response.code === 200) {
          this.typeList = response.data
        }
      })
    },
    fetchStreetList() {
      getAllStreet().then(response => {
        if (response.code === 200) {
          this.streetList = response.data
        }
      })
    },
    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;
  .app-container{
    margin-bottom:20px
  }
  .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>
