<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 v-if="showWellType" class="selectForm-container-item" prop="wellType">
            <el-select v-model="listQuery.wellType" placeholder="选择井类型" clearable>
              <el-option
                v-for="item in wellTypeList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </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="18" class="edit_btns">
          <el-button v-if="hasPerm('/well/batchExport')" :disabled="total===0" class="edit_btn" size="small" @click="batchExport">
            导出记录
          </el-button>
          <!--<el-button v-if="hasPerm('/template/download')" class="edit_btn" size="small" @click="downloadTemplate">批量导入模板下载</el-button>-->
          <download-template v-if="hasPerm('/well/batchImport')" :filename="filename" />
          <el-upload
            v-if="hasPerm('/well/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('/well/batchBfcf')" class="edit_btn" size="small" @click="batchBf">
            一键布防
          </el-button>
          <el-button v-if="hasPerm('/well/batchBfcf')" class="edit_btn" size="small" @click="batchCf">
            一键撤防
          </el-button>
          <el-button v-if="hasPerm('/well/delete')" class="edit_btn" size="small" @click="del">
            删除
          </el-button>
          <el-button v-if="hasPerm('/well/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">
            <el-button v-if="column.type=='Button' && scope.row.deviceCount>0" type="text" @click="goDeviceList(scope.row)">
              {{ scope.row[column.value] }}
            </el-button>
            <span v-else :class="column.class">{{ scope.row[column.value] }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="hasPerm('/well/bfcf')" label="布撤防" align="center" width="80">
          <template slot-scope="scope">
            <el-button :type="btnStatus[scope.row.bfztName]" size="mini" @click="bfcf(scope.row)">
              {{ btnNames[scope.row.bfztName] }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template slot-scope="scope">
            <el-button type="text" @click="detail(scope.row)">
              详情
            </el-button>
            <el-button v-if="hasPerm('/well/update')" type="text" @click="edit(scope.row)">
              编辑
            </el-button>
            <el-button type="text" @click="goAlarmRecords(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-well ref="editwell" @watchChild="fetchData" />
    <detail-well ref="detailwell" />
  </div>
</template>

<script>
import editWell from '@/views/wellManage/editWell'
import detailWell from '@/views/wellManage/detailWell'
import { getWellList, getWellType, delWell, batchImportWell, batchExportWell, batchBfcf, bfcf } from '@/api/well/well'
import DeptSelect from '@/components/DeptSelect'
import DownloadTemplate from '@/components/DownloadTemplate/index'

export default {
  name: 'ListWell',
  components: { DownloadTemplate, editWell, detailWell, DeptSelect },
  data() {
    return {
      listQuery: {
        keywords: '',
        wellType: '',
        deptid: '',
        offset: 1,
        limit: 20,
        sort: 'wellCode',
        order: 'asc'
      }, // 筛选条件
      columns: [
        {
          text: '井编号',
          value: 'wellCode',
          align: 'center'
        },
        {
          text: '井名称',
          value: 'wellName',
          align: 'center'
        },
        {
          text: '井深(m)',
          value: 'deep',
          align: 'center'
        },
        {
          text: '详细地址',
          value: 'position',
          align: 'center'
        },
        {
          text: '井类型',
          value: 'wellTypeName',
          align: 'center'
        },
        {
          text: '权属单位',
          value: 'deptName',
          align: 'center'
        },
        {
          text: '设备数量',
          value: 'deviceCount',
          align: 'center',
          type: 'Button'
        },
        {
          text: '布防状态',
          value: 'bfztName',
          align: 'center'
        }
      ], // 显示列
      multipleSelection: [], // 多选选中项
      list: [], // 列表数据
      total: 0, // 数据总数
      showWellType: true, // 是否显示井类型下拉
      wellTypeList: null, // 井类型列表
      deptProps: {
        parent: 'pid',
        value: 'id',
        label: 'name',
        children: 'children'
      }, // 权属单位树形下拉菜单
      deptTreeList: null, // 组织树列表数据
      deptShowTop: false, // 权属单位下拉是否显示顶级
      listLoading: true, // 加载动画
      fullscreenLoading: false, // 全屏加载动画
      editShow: false, // 是否显示编辑框
      detailShow: false, // 是否显示详情框
      filename: 'sluicewell_template.xlsx',
      fileList: [],
      btnNames: {
        '布防': '撤防',
        '撤防': '布防'
      },
      btnStatus: {
        '撤防': 'success',
        '布防': 'danger'
      }
    }
  },
  created() {
    this.fetchWellType()// 获取井列表
    this.fetchData()// 获取数据
  },
  activated() {
    console.log('activated')
    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.$router.push({ path: 'addWell', query: { type: 'add' }})
    },
    // 编辑井信息
    edit(row) {
      console.log(row, '===row====')
      this.dialogFormVisible = true
      this.editShow = true
      this.$refs.editwell.initDialog(this.dialogFormVisible, row)
    },
    // 删除井
    del() {
      if (this.checkSelection()) {
        const wellIds = []
        this.multipleSelection.forEach(function(value, index) {
          wellIds.push(value.id)
        })
        this.$confirm(
          '确定要删除所选井吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          delWell(wellIds).then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.fetchData()
            }
          })
        })
      } else {
        this.$message.error('至少选中一项')
      }
    },
    // 批量导入井
    uploadFile(param) {
      console.log('uploadFile')
      // 判断文件大小是否符合要求
      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)'
      })
      // 发起导入请求
      batchImportWell(_file).then(res => {
        loading.close() // 关闭加载动画
        if (res.code === 200) {
          this.$message.success('导入成功')
          this.fileList = []
          this.fetchData()
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {
        loading.close()
      })
      this.fileList = []
    },
    // 批量导出
    batchExport() {
      // 全屏加载动画
      const loading = this.$loading({
        lock: true,
        text: '下载中,请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const _this = this
      const config = {
        // 获取下载进度
        onDownloadProgress(progressEvent) {
          console.log(progressEvent)
          var percent = parseInt(100 * (progressEvent.loaded / progressEvent.total))
          console.log('percent:' + percent, 'total:' + progressEvent.total)
          // 渲染dom
          _this.$nextTick(() => {
            _this.percent = percent
          })
        }
      }
      batchExportWell(this.listQuery, config).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()
      })
    },
    // 布防撤防
    bfcf(row) {
      if (row.bfzt === '1') {
        // 需要撤防
        this.$confirm(
          '确定要对该井进行撤防吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          bfcf(row.id, '0').then(response => {
            if (response.code === 200) {
              this.$message.success('撤防成功')
              this.fetchData()
            }
          })
        })
      } else {
        // 需要布防
        this.$confirm(
          '确定要对该井进行布防吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          bfcf(row.id, '1').then(response => {
            if (response.code === 200) {
              this.$message.success('布防成功')
              this.fetchData()
            }
          })
        })
      }
    },
    // 批量布防
    batchBf() {
      const listQuery = {
        keywords: this.listQuery.keywords,
        owner: this.listQuery.owner,
        position: this.listQuery.position,
        wellType: this.listQuery.wellType,
        deptid: this.listQuery.deptid,
        notes: this.listQuery.notes,
        bfzt: '1'
      }
      this.$confirm(
        '确定要对列表中的全部井进行布防吗？',
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        batchBfcf(listQuery).then(response => {
          if (response.code === 200) {
            this.$message.success('布防成功')
            this.fetchData()
          }
        })
      })
    },
    // 批量撤防
    batchCf() {
      const listQuery = {
        keywords: this.listQuery.keywords,
        owner: this.listQuery.owner,
        position: this.listQuery.position,
        wellType: this.listQuery.wellType,
        deptid: this.listQuery.deptid,
        notes: this.listQuery.notes,
        bfzt: '0'
      }
      this.$confirm(
        '确定要对列表中的全部井进行撤防吗？',
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        batchBfcf(listQuery).then(response => {
          if (response.code === 200) {
            this.$message.success('撤防成功')
            this.fetchData()
          }
        })
      })
    },
    // 查询数据
    search() {
      this.fetchData(false)
    },
    // 获取井数据
    fetchData(isNowPage = true) {
      this.listLoading = true
      if (!isNowPage) { // 是否显示当前页，否则跳转第一页
        this.listQuery.offset = 1
      }
      getWellList(this.listQuery).then(response => {
        console.log(response)
        this.list = response.data.rows
        this.total = parseInt(response.data.total)
        this.listLoading = false
      })
    },
    // 获取井类型
    fetchWellType() {
      getWellType().then(response => {
        this.wellTypeList = []
        const wellTypes = this.$store.getters.wellTypes
        for (const wellType of response.data) {
          if (wellTypes.indexOf(wellType.value) !== -1) {
            this.wellTypeList.push(wellType)
          }
        }
        if (this.wellTypeList.length <= 1) {
          this.showWellType = false
        }
      })
    },
    // 去设备列表页
    goDeviceList(row) {
      this.$router.push({ name: 'DeviceList', query: { wellCode: row.wellCode }})
    },
    goAlarmRecords(row) {
      this.$router.push({ name: 'AlarmRecords', query: { wellCode: row.wellCode }})
    },
    handleSuccess() {
      console.log('handleSuccess')
    },
    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>
