<!--报警记录-->
<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.alarmCode" placeholder="报警编号" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item class="selectForm-container-item">
                <el-select v-model="listQuery.alarmContent" placeholder="报警内容" clearable>
                  <el-option v-for="item in alarmContents" :key="item.value" :label="item.name" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item class="selectForm-container-item">
                <el-select v-model="listQuery.areaId" placeholder="区域" clearable filterable>
                  <el-option v-for="item in regions" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item class="selectForm-container-item">
                <el-date-picker
                  v-model="timeRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期" />
              </el-form-item>
            </el-col>

            <el-col :span="4" class="search-right">
              <el-button class="filter-item" type="primary" icon="el-icon-search" @click="fetchData()">搜索</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 class="edit_btn" size="small" @click="batchExport" :disabled="list.length===0">导出</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="listLoading" :data="list" class="table" row-class-name="small-row-class" border>
        <!--序号列-->
        <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">
            <el-button v-if="column.value === 'alarmCode'" type="text" @click="detailAlarm(scope.row)">{{ scope.row[column.value] }}</el-button>
            <el-button v-else-if="column.value === 'devcode'" type="text" @click="detailDevice(scope.row)">{{ scope.row[column.value] }}</el-button>
            <span v-else-if="column.value === 'valid'" :class="column.class">{{ formatStatus(scope.row[column.value]) }}</span>
            <span v-else :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" @click="position(scope.row)">位置</el-button>
            <el-button v-if="hasPerm('/car/update')" type="text" @click="video(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>

    <device-detail ref="devDetail" />
    <alarm-detail ref="alarmDetail" />
  </div>
</template>

<script>
import { alarmExport } from '@/api/batch'
import { getAlarmList } from '@/api/alarm'
import { getRegion, getAreaTypeBySubSystem } from '@/api/area'
import { getDetailDevice } from '@/api/device'
import { getAlarmContent } from '@/api/allDict'
import { formatToString } from '@/utils/calendarUtil'
import DeviceDetail from '@/views/deviceManage/deviceDetail'
import AlarmDetail from '@/views/alarm/alarmDetail'

export default {
  name: 'CarList',
  components: { DeviceDetail, AlarmDetail },
  data() {
    return {
      listQuery: {
        alarmCode: '',
        alarmContent: '',
        areaType: '',
        areaId: '',
        valid: 0,
        startTime: '',
        endTime: '',
        offset: 1,
        limit: 20,
        sort: '',
        order: ''
      }, // 筛选条件
      columns: [
        {
          text: '报警编号',
          value: 'alarmCode',
          align: 'center'
        },
        {
          text: '报警内容',
          value: 'alarmContent',
          align: 'center'
        },
        {
          text: '区域名称',
          value: 'areaPosition',
          align: 'center'
        },
        {
          text: '设备编号',
          value: 'devcode',
          align: 'center'
        },
        {
          text: '报警时间',
          value: 'alarmTime',
          align: 'center',
          width: 160
        },
        {
          text: '报警状态',
          value: 'valid',
          align: 'center'
        }
      ], // 显示列
      list: [], // 列表数据
      total: 0, // 数据总数
      alarmContents: [],
      regions: [],
      timeRange: [],
      listLoading: false, // 加载动画
      fullscreenLoading: false, // 全屏加载动画
      dialogFormVisible: false,
      dialogDetailVisible: false
    }
  },
  watch: {
    timeRange: function(newV) {
      if (newV) {
        this.listQuery.startTime = formatToString(newV[0], 'DATE')
        this.listQuery.endTime = formatToString(newV[1], 'DATE')
      } else {
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      }
      this.fetchData()
    }
  },
  created() {
    // 获取当前系统对应的区域id
    this.listQuery.areaType = getAreaTypeBySubSystem(this.$store.getters.currentSystem.code)
    this.fetchAlarmContentsData()
    this.fetchRegionsData()
  },
  activated() {
    this.fetchData() // 获取数据
  },
  methods: {
    video(row){
      const code = this.$store.getters.currentSystem.code
      this.$router.push({ path: '/' + code + '/alarm/video', query: { id: row.deviceId }})
    },
    position(row){
      const code = this.$store.getters.currentSystem.code
      this.$router.push({ path: '/' + code + '/alarm/position', query: {  id: row.deviceId }})
    },
    batchExport() {
      // 全屏加载动画
      const loading = this.$loading({
        lock: true,
        text: '下载中,请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      alarmExport(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)
      })
    },
    detailAlarm(row) {
      this.dialogDetailVisible = true
      this.$refs.alarmDetail.initDialog('detail', this.dialogDetailVisible, row)
    },
    detailDevice(row) {
      getDetailDevice(row.deviceId).then(response => {
        if (response.code === 200) {
          this.dialogFormVisible = true
          this.$refs.devDetail.initDialog('detail', this.dialogFormVisible, response.data)
        }
      })
    },
    formatStatus(valid) {
      if (valid === 1) {
        return '正在报警'
      } else if (valid === 0) {
        return '已消警'
      } else {
        return '-'
      }
    },
    // 查询数据
    search() {
      this.fetchData(false)
    },
    fetchAlarmContentsData() {
      getAlarmContent().then(response => {
        this.alarmContents = response.data
      })
    },
    fetchRegionsData() {
      getRegion({ limit: 1000, areaType: this.listQuery.areaType }).then(response => {
        this.regions = response.data.rows
      })
    },
    // 获取列表
    fetchData(isNowPage = true) {
      this.listLoading = true
      if (!isNowPage) { // 是否显示当前页，否则跳转第一页
        this.listQuery.offset = 1
      }
      getAlarmList(this.listQuery).then(response => {
        if (response.code === 200) {
          this.list = response.data.rows
          console.log('&&&')
          console.log(this.list)
          this.total = parseInt(response.data.total)
        } else {
          this.$message.error(response.message)
        }
        this.listLoading = false
      })
    },
    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()
    }
  }
}
</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>
