<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="keywords">
            <el-input v-model.trim="listQuery.keywords" placeholder="集中器编号/安装位置" clearable />
          </el-form-item>
          <el-form-item class="selectForm-container-item" prop="wellType">
            <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-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 v-if="hasPerm('/concentrator/batchExport')" class="edit_btn" size="small" @click="batchExport">
            导出记录
          </el-button>
          <download-template v-if="hasPerm('/concentrator/batchImport')" :filename="filename" />
          <el-upload
            v-if="hasPerm('/concentrator/batchImport')"
            :limit="1"
            :show-file-list="false"
            :http-request="uploadFile"
            :file-list="fileList"
            action="string"
            accept=".xls,.xlsx"
            class="edit_btn"
          >
            <el-button slot="trigger" size="small">
              批量导入
            </el-button>
          </el-upload>
          <el-button v-if="hasPerm('/concentrator/delete')" class="edit_btn" size="small" @click="del">
            删除
          </el-button>
          <el-button v-if="hasPerm('/concentrator/add')" 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 align="center" type="selection" width="55" />
        <el-table-column :index="indexMethod" align="center" type="index" />
        <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">
            {{ scope.row[column.value] }}
          </template>
        </el-table-column>
        <el-table-column v-if="showOperate" label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button v-if="hasPerm('/concentrator/update')" type="text" @click="edit(scope.row)">
              编辑
            </el-button>
            <!--<el-button type="text" @click="detail(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]"
        :page-size="listQuery.limit"
        :total="total"
        align="center"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <edit-concentrator v-show="editShow" ref="editconcen" @watchChild="fetchData" />
  </div>
</template>

<script>
import editConcentrator from '@/views/concentrator/editConcentrator'
import { getConcenList, getStatusType, delConcen, batchImportConcen, batchExportConcen } from '@/api/device/concentrator'
import DownloadTemplate from '../../components/DownloadTemplate/index'

export default {
  name: 'ListConcentrator',
  components: { DownloadTemplate, editConcentrator },
  data() {
    return {
      listQuery: {
        keywords: '',
        status: '',
        offset: 1,
        limit: 20,
        sort: 'concencode',
        order: 'asc'
      }, // 筛选条件
      columns: [
        {
          text: '集中器编号',
          value: 'concencode',
          align: 'center'
        },
        {
          text: '集中器SIM卡号',
          value: 'simid',
          align: 'center'
        },
        {
          text: '权属单位',
          value: 'deptName',
          align: 'center'
        },
        {
          text: '安装位置',
          value: 'position',
          align: 'center'
        },
        {
          text: '在线状态',
          value: 'statusName',
          width: 90,
          align: 'center'
        },
        {
          text: '设备数量',
          value: 'devices',
          width: 90,
          align: 'center'
        },
        {
          text: '最新在线时间',
          value: 'lasttimeFormat',
          align: 'center'
        },
        {
          text: '安装日期',
          value: 'setupdate',
          width: 100,
          align: 'center'
        }
      ], // 显示列
      multipleSelection: [], // 多选选中项
      list: [], // 列表数据
      total: 0, // 数据总数
      statusList: [], // 集中器类型列表
      listLoading: true, // 加载动画
      fullscreenLoading: false, // 全屏加载动画
      editShow: false, // 是否显示编辑框
      detailShow: false, // 是否显示编辑框
      filename: 'busConcentrator_template.xlsx', // 集中器模板文件
      fileList: []
    }
  },
  computed: {
    'showOperate': function() { // 判断是否显示操作列，如果编辑和删除的权限都没有则不显示操作列
      return this.hasPerm('/concentrator/update')
    }
  },
  created() {
    this.fetchStatusType()// 获取部门树
    this.fetchData()// 获取数据
  },
  methods: {
    // 打开详情对话框
    detail(row) {
      this.detailShow = true
      this.$refs.detailwell.initDialog(true, row)
    },
    checkSelection() {
      if (this.multipleSelection.length === 0) {
        return false
      } else {
        return true
      }
    },
    // 新增集中器
    add() {
      this.dialogFormVisible = true
      this.editShow = true
      this.$refs.editconcen.initDialog('create', this.dialogFormVisible)
    },
    // 编辑集中器信息
    edit(row) {
      this.dialogFormVisible = true
      this.editShow = true
      this.$refs.editconcen.initDialog('update', this.dialogFormVisible, row)
    },
    // 删除集中器
    del() {
      if (this.checkSelection()) {
        // let wellNames = ''
        const concenIds = []
        this.multipleSelection.forEach(function(value, index) {
          // wellNames += value.wellCode + ','
          concenIds.push(value.id)
        })
        // wellNames = wellNames.slice(0, wellNames.length - 1)
        this.$confirm(
          '确定要删除所选集中器吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          delConcen(concenIds).then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.fetchData()
            }
          })
        })
      } else {
        this.$message.error('至少选中一项')
      }
    },
    // 批量导入集中器
    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)'
      })
      // 发起导入请求
      batchImportConcen(_file).then(res => {
        loading.close() // 关闭加载动画
        if (res.code === 200) {
          this.$message.success('导入成功')
          this.fetchData()
        } else {
          this.$message.error(res.message)
        }
      }).catch(_ => {
        loading.close() // 关闭加载动画
        // this.$message.error(error.message)
      })
      this.fileList = []
    },
    // 批量导出
    batchExport() {
      console.log('批量导出集中器')
      // 全屏加载动画
      const loading = this.$loading({
        lock: true,
        text: '数据处理中,请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      batchExportConcen(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()
      })
    },
    // 查询数据
    search() {
      this.fetchData(false)
    },
    // 获取集中器数据
    fetchData(isNowPage = true) {
      this.listLoading = true
      if (!isNowPage) { // 是否显示当前页，否则跳转第一页
        this.listQuery.offset = 1
      }
      getConcenList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = parseInt(response.data.total)
        this.listLoading = false
      })
    },
    // 获取在线状态类型
    fetchStatusType() {
      getStatusType().then(response => {
        this.statusList = 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;
  .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>
