<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">
            <dept-select v-model="listQuery.deptid" :need-top="deptShowTop" dept-type="03" placeholder="选择权属单位"/>
          </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('/liquidConfig/batchExport')" class="edit_btn" size="small" @click="batchExport">导出记录</el-button>
          <download-template :filename="filename"/>
          <el-upload
            v-if="hasPerm('/liquidConfig/batchImport')"
            :limit="1"
            :show-file-list="false"
            :http-request="uploadFile"
            :file-list="fileList"
            action="string"
            accept=".xls,.xlsx"
            class="edit_btn">
            <el-button v-if="hasPerm('/liquidConfig/batchImport')" slot="trigger" size="small">批量导入</el-button>
          </el-upload>
          <el-button v-if="hasPerm('/liquidConfig/config')" 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 label="操作" align="center" width="60">
          <template slot-scope="scope">
            <el-button type="text" @click="edit(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-liquid-config v-show="editShow" ref="editconfig" @watchChild="fetchData"/>
  </div>
</template>

<script>
import { judgeTree, toTreeList } from '@/utils/structure'
import selectTree from '@/components/SelectTree/singleSelect'
import { getLiquidConfigList, batchImportLiquidConfig, batchExportLiquidConfig } from '@/api/liquidconfig'
import { getDeptTreeList } from '@/api/dept'
import EditLiquidConfig from './editLiquidConfig'
import DownloadTemplate from '@/components/DownloadTemplate/index'
import DeptSelect from '@/components/DeptSelect/index'

export default {
  name: 'ListLiquidConfig',
  components: { DeptSelect, DownloadTemplate, EditLiquidConfig, selectTree },
  data() {
    return {
      listQuery: {
        keywords: '',
        offset: 1,
        limit: 20,
        sort: '',
        order: ''
      }, // 筛选条件
      columns: [
        {
          text: '设备编号',
          value: 'devcode',
          align: 'center'
        },
        // {
        //   text: '设备名称',
        //   value: 'deviceName',
        //   align: 'center'
        // },
        // {
        //   text: '设备类型',
        //   value: 'deviceTypeName',
        //   align: 'center'
        // },
        {
          text: '重传次数',
          value: 'retryTimes',
          align: 'center'
        },
        {
          text: '报警阈值(m)',
          value: 'threshold',
          align: 'center'
        },
        {
          text: '井深百分比(%)',
          value: 'percent',
          align: 'center'
        },
        {
          text: '安装高度(m)',
          value: 'installHeight',
          align: 'center'
        },
        {
          text: 'IP地址',
          value: 'ip',
          align: 'center'
        },
        {
          text: '端口',
          value: 'port',
          align: 'center'
        },
        {
          text: '最大尝试次数',
          value: 'attemptsMax',
          align: 'center'
        },
        {
          text: '已尝试次数',
          value: 'attemptsCurrent',
          align: 'center'
        },
        {
          text: '下发状态',
          value: 'statusName',
          width: 80,
          align: 'center'
        }
      ], // 显示列
      multipleSelection: [], // 多选选中项
      list: [], // 列表数据
      total: 0, // 数据总数
      deviceTypeList: [], // 液位配置类型列表
      deptProps: {
        parent: 'pid',
        value: 'id',
        label: 'name',
        children: 'children'
      }, // 权属单位树形下拉菜单
      deptTreeList: null, // 组织树列表数据
      showDeptTree: 0, // 是否显示权属单位下拉
      showDeviceType: true, // 是否显示设备类型下拉
      listLoading: true, // 加载动画
      fullscreenLoading: false, // 全屏加载动画
      editShow: false, // 是否显示编辑框
      detailShow: false, // 是否显示编辑框
      filename: 'config_template.xlsx',
      deptShowTop: false,
      fileList: []
    }
  },
  created() {
    this.fetchDeptTree()// 获取部门树
    this.fetchData()// 获取数据
  },
  methods: {
    // 打开详情对话框
    checkSelection() {
      if (this.multipleSelection.length === 0) {
        return false
      } else {
        return true
      }
    },
    // 新增设备
    add() {
      this.dialogFormVisible = true
      this.editShow = true
      this.$refs.editconfig.initDialog('create', this.dialogFormVisible)
    },
    // 编辑液位配置信息
    edit(row) {
      this.dialogFormVisible = true
      this.editShow = true
      this.$refs.editconfig.initDialog('update', this.dialogFormVisible, row)
    },
    // 批量导入液位配置
    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)'
      })
      // 发起导入请求
      batchImportLiquidConfig(_file).then(res => {
        loading.close() // 关闭加载动画
        if (res.code === 200) {
          this.$message.success('导入成功')
          this.fetchData(false)
        } else {
          this.$message.error(res.message)
        }
      }).catch(error => {
        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)'
      })
      batchExportLiquidConfig(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)
      })
    },
    // 查询数据
    search() {
      this.fetchData(false)
    },
    // 获取液位配置数据
    fetchData(isNowPage = true) {
      this.listLoading = true
      if (!isNowPage) { // 是否显示当前页，否则跳转第一页
        this.listQuery.offset = 1
      }
      getLiquidConfigList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = parseInt(response.data.total)
        this.listLoading = false
      })
    },
    // 加载组织机构树形下拉菜单
    fetchDeptTree: function() {
      getDeptTreeList().then(response => {
        if (response.data.list) {
          if (response.data.list.length > 1) {
            console.log(this.$store.getters.deptId)
            if (judgeTree(response.data.list)) {
              this.deptTreeList = toTreeList(response.data.list)
              this.showDeptTree = 1
            } else {
              this.deptTreeList = response.data.list
              this.showDeptTree = 2
            }
            console.log(this.deptTreeList)
          } else {
            this.showDeptTree = 0
          }
        }
      })
    },
    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>
  .app-container{
    padding: 10px;
  }
  $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>
