<template >
    <el-container style="padding:0px;height:77.6vh;">
      <el-header class="el_header-style">
        <span class="title-bold title-left-color">巡查机管理</span>
        <el-popover placement="bottom" width="150" >
              <el-button slot="reference" size='mini' type="primary" icon="el-icon-s-tools" style='float:right;transform:translateY(6px)'> 筛选</el-button>
              <el-checkbox-group v-model="checkList">
                  <el-col :span="24">
                      <el-checkbox v-for="(item,index) in tableHeader" :label="item" :key="index"  >
                        {{item.label}}
                      </el-checkbox>
                  </el-col>
              </el-checkbox-group>
        </el-popover>
      </el-header>
      <el-main class="box_main">
        <el-card>
            <el-form :inline="true" :model="dataForm" size="mini">
              <el-form-item>
                <el-input v-model="dataForm.keywords" placeholder="搜索巡查机名称、编码、所属部门" ></el-input>
              </el-form-item>
              <el-button @click="getDataList()" type="primary"  size="mini" icon="el-icon-search">查询</el-button>
              <span style="float:right">
                <!-- <el-button type="primary" size="mini" v-prevent-re-click>导入</el-button> -->
                <el-button v-if="isAuth('patrol:machine:export')" type="primary" @click="downClick()" v-loading.fullscreen.lock="fullscreenLoading" size="mini" v-prevent-re-click>导出</el-button>
                <el-button v-if="isAuth('patrol:machine:register')" type="primary" @click="addMachine" size="mini">注册</el-button>
              </span>
            </el-form>
            <drag-table :data="dataList" :header="checkList" :option="tableOption"  @getDataList="getDataList" v-loading="dataListLoading" :operationNum="2"  :isShowOperate="true" >

              <!-- 插槽  -->
              <el-table-column slot="fixed"  fixed  prop=""  label="序号"  width="80"  header-align="center" align="center" >
                  <template slot-scope="scope">
                    <span>{{scope.$index+(pageIndex - 1) * pageSize + 1}}</span>
                  </template>
              </el-table-column>

              <!-- 操作项 -->
              <template slot-scope="scope">
                <el-button v-if="isAuth('patrol:machine:update')" size="mini" type="text" @click="editMachine(scope.row)">编辑</el-button>
                <el-button v-if="isAuth('patrol:machine:delete')" size="mini" type="text" @click="deleteClick(scope.row)">删除</el-button>
              </template>

            </drag-table>
          </el-card>
      </el-main>
      <el-footer class="box_footer">
        <el-pagination @size-change="sizeChangeHandle" background @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" layout="total, sizes, prev, pager, next, jumper" ></el-pagination>
      </el-footer>
      <query-detail v-if='queryDetailVisible' ref='queryDetail' @closeQ="closeQueryDetailVisible"></query-detail>
    </el-container>
</template>

<script>
import QueryDetail from './query-detail'
import dragTable from '../../components/tab'
export default {
  data() {
    return {
      queryDetailVisible: true,
      dataForm: {
        stationId: localStorage.getItem('stationId'),
        subCode: '01',
        keywords: ''
      },
      dialogDataForm: {
        operation: '1'
      },
      fullscreenLoading: false,
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      state1: '',
      restaurants: [],
      sort: '',
      order: '',
      checkList: [], //筛选数据
      tableHeader: [
        { label: '巡查机名称', prop: 'name' }, //是否插槽
        { label: '巡查机编码', prop: 'code' },
        { label: '所属部门', prop: 'orgName' },
        { label: '启用时间', prop: 'startTime' },
        { label: '巡查次数', prop: 'patrolTimes' },
        { label: '使用总时长(分)', prop: 'duration' }
        // {label:'操作',prop:''},
      ],
      tableOption: {
        border: false, //是否边框
        maxHeight: 500 //高度
      }
    }
  },
  components: {
    QueryDetail,
    dragTable
  },
  watch: {
    totalPage() { //注意这个函数的名字必须和你监听data中的属性的名字一样，这样才能当你data中的属性发生变化时，触发这个函数
      let pages = Math.ceil(this.totalPage / this.pageSize)//新数据总页数
      //总页数小于当前页数则重新加载列表数据
      if (pages < this.pageIndex) {
          this.pageIndex = pages || 1
          this.getDataList()//获取表格数据的方法
      }
    }
  },
  created() {
    this.checkList = [...this.tableHeader]
    this.pageIndex = 1
    this.getDataList()
  },
  methods: {
    tabRowClick() {

    },
    querySearch(queryString, cb) {
      let restaurants = this.restaurants
      let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleSelect() {

    },
    editMachine(res) {
      this.$refs.queryDetail.init(this.dataForm.stationId, JSON.parse(JSON.stringify(res)))
    },
    addMachine() {
      this.$refs.queryDetail.init(this.dataForm.stationId)
    },
    downClick() {
      this.fullscreenLoading = true
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolMachine/export'),
        method: 'get',
        responseType: 'arraybuffer',
        params: {
          stationId: this.dataForm.stationId,
          keywords: this.dataForm.keywords
        }
      }).then(data => {
        let dd = localStorage.getItem('headers')
        let headers = JSON.parse(dd)

        let type = headers['content-type'].trim().split(';')[0]
        let filename = decodeURI(headers['content-disposition'].trim().split(';')[1].split('=')[1])
        const blob = new Blob([data], { type: type })
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, filename)
        } else {
          const link = document.createElement('a')
          link.download = filename
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click()
          URL.revokeObjectURL(link.href)
          document.body.removeChild(link)
        }
        this.fullscreenLoading = false
      })
    },
    // 获取数据列表
    getDataList(sort, order) {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolMachine/list'),
        method: 'post',
        data: {
          stationId: this.dataForm.stationId,
          page: this.pageIndex,
          rows: this.pageSize,
          keywords: this.dataForm.keywords,
          sort: sort,
          order: order
        }
      }).then(data => {
        //console.log('data', data)
        if (data && data.code === 0) {
          this.dataList = data.page.rows
          this.totalPage = data.page.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    closeQueryDetailVisible() {
      this.getDataList()
    },
    deleteClick(row) {
      this.$confirm('确认删除该巡查机?', '删除巡查机', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
              this.$http({
              url: this.$http.adornUrlEq('/epPatrolMachine/delete'),
              method: 'get',
              params: { id: row.id, stationId: row.stationId }
            }).then(data => {
              this.$message.success('删除成功')
              this.getDataList()
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //转化时间
    formatTime(date, format) {
        if (date) {
          date = new Date(date)
          var o = {
              'M+': date.getMonth() + 1, //月份
              'd+': date.getDate(), //日
              'h+': date.getHours(), //小时
              'm+': date.getMinutes(), //分
              's+': date.getSeconds(), //秒
              'q+': Math.floor((date.getMonth() + 3) / 3), //季度
              'S': date.getMilliseconds() //毫秒
          }
          var fmt = format || 'yyyy-MM-dd hh:mm'
          if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) }
          for (var k in o) {
 if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) }
}
          return fmt
        } else {
          return ''
        }
    },
    sortChange (column) {
      if (column.order === 'descending') {
        this.order = 'desc'
      } else {
        this.order = 'asc'
      }
      if (column.column.columnKey) {
        this.sort = column.column.columnKey
      } else {
        this.sort = column.prop
      }
      this.getDataList()
    }
  }
}
</script>
<style lang='scss'>
.inputWidth {
  width: 130px;
}
.instuctions_header{
  height: 42px;
  background:#EDEEF1;
  border:1px solid rgba(195, 195, 195, 1);
  h1{
    font-size:16px;
    line-height: 42px;
    height: 42px;
    margin: 0;
    font-family:Adobe Heiti Std;
    font-weight:bold;
    color:rgba(51,51,51,1);
    float: left;
  }
  span{
    width:5px;
    height:16px;
    background:rgba(33,172,252,1);
    float: left;
    margin: 13px 10px 0 20px;
  };
}
.instuctions_content{
  padding: 20px;
  background: #fff;
  table{
    th{
      background: #eef8ff !important;
      color: #333333 !important;
    }
  }
}
</style>
