<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="isOperation()" class="selectForm-container-item" prop="alarmType">
            <el-select v-model="listQuery.alarmType" placeholder="告警类型" clearable>
              <el-option
                v-for="item in alarmTypeList"
                :key="item.value"
                :label="item.name"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item class="selectForm-container-item" prop="alarmType">
            <el-select :disabled="alarmContentTypeList.length>0?false:true" v-model="listQuery.alarmContentType" placeholder="告警内容" clearable="">
              <el-option
                v-for="item in alarmContentTypeList"
                :key="item.value"
                :label="item.name"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item class="selectForm-container-item" prop="beginTime">
            <el-date-picker
              v-model="timeRange"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="工单创建开始时间"
              end-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('/job/export')" class="edit_btn" size="small" @click="batchExport">导出记录</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="listLoading" :data="list" class="table" border @selection-change="handleSelectionChange">
        <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">
            <span v-if="column.type!='Button'" :class="column.class">{{ scope.row[column.value] }}</span>
            <el-button v-else-if="column.type=='Button'" type="text" @click="showWellDetail(scope.row)">{{ scope.row.wellCode }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="showJob(scope.row.id)">查看</el-button>
            <el-button v-if="scope.row.alarmType=='2'" :disabled="notFirstState(scope.row.jobStatus)" type="text" @click="handleJob(scope.row.id)">处理</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>
    <info-well v-show="wellShow" ref="wellInfo"/>
  </div>
</template>

<script>
import infoWell from '@/views/wellManage/infoWell'
import { getAlarmType, getAlarmContentType } from '@/api/alarm'
import { getOvertimeHandleJobList, exportOvertimeHandleJobList, handleJob } from '@/api/job'
import { isOperation } from '@/utils/permission'
let isFromDetail = false
export default {
  name: 'ListJobsOverTimeHandle',
  components: { infoWell },
  data() {
    return {
      listQuery: {
        keywords: '',
        alarmType: '',
        alarmContentType: '',
        beginTime: '',
        endTime: '',
        offset: 1,
        limit: 20,
        sort: '',
        order: ''
      }, // 筛选条件
      timeRange: [], // 时间范围
      columns: [
        {
          text: '工单编号',
          value: 'jobCode',
          width: 160,
          align: 'center'
        },
        {
          text: '窨井编号',
          value: 'wellCode',
          align: 'center',
          type: 'Button'
        },
        {
          text: '详细地址',
          value: 'position',
          align: 'center'
        },
        {
          text: '告警类型',
          value: 'alarmTypeName',
          align: 'center'
        },
        {
          text: '告警原因',
          value: 'alarmContentName',
          align: 'center',
          width: 120
        },
        {
          text: '告警数值',
          value: 'alarmValue',
          width: 80,
          align: 'center',
          class: 'warning'
        },
        {
          text: '工单创建时间',
          value: 'createTime',
          width: 170,
          align: 'center'
        },
        {
          text: '处理状态',
          value: 'jobStatusName',
          align: 'center'
        },
        {
          text: '处理人',
          value: 'jobBelongTo',
          align: 'center',
          format: true
        },
        {
          text: '接单时间',
          value: 'getJobTime',
          align: 'center'
        }
      ], // 显示列
      multipleSelection: [], // 多选选中项
      list: [], // 列表数据
      total: 0, // 数据总数
      deviceTypeList: [], // 集中器类型列表
      deptProps: {
        parent: 'pid',
        value: 'id',
        label: 'name',
        children: 'children'
      }, // 权属单位树形下拉菜单
      alarmTypeList: [], // 告警类型列表
      alarmContentTypeList: [], // 告警内容类型列表
      showAlarmType: true, // 是否显示告警类型下拉
      listLoading: true, // 加载动画
      fullscreenLoading: false, // 全屏加载动画
      wellShow: false, // 是否显示编辑框
      detailShow: false // 是否显示编辑框
    }
  },
  computed: {
    alarmType() {
      return this.listQuery.alarmType
    }
  },
  watch: {
    alarmType(val) {
      this.listQuery.alarmContentType = ''
      if (val && val !== '') {
        this.fetchAlarmContentType()
      } else {
        this.alarmContentTypeList = []
      }
    },
    timeRange(val) {
      if (val && val.length > 0) {
        this.listQuery.beginTime = val[0]
        this.listQuery.endTime = val[1]
      } else {
        this.listQuery.beginTime = ''
        this.listQuery.endTime = ''
      }
    }
  },
  created() {
    console.log('create')
    this.fetchAlarmType() // 告警类型下拉菜单
    this.fetchAlarmContentType() // 告警内容下拉菜单
  },
  beforeRouteEnter(to, from, next) {
    if (from.name) {
      if (from.name.indexOf('DetailJob') === -1) {
        isFromDetail = false
      } else {
        isFromDetail = true
      }
    } else {
      isFromDetail = false
    }
    next()
  },
  mounted() {
    this.fetchData()
  },
  activated() {
    if (!isFromDetail) {
      this.listQuery.keywords = ''
      this.listQuery.alarmType = ''
      this.listQuery.alarmContentType = ''
      this.listQuery.beginTime = ''
      this.listQuery.endTime = ''
      this.timeRange = []
      if (!isOperation()) {
        this.listQuery.alarmType = '1'
      }
      this.fetchData(false)
    }
  },
  methods: {
    // 处理显示处理人
    formatJobBelongTo(row, value) {
      debugger
      if (row.jobStatusName !== '待处理' && !value) {
        return '系统'
      } else {
        return value
      }
    },
    // 是不是待处理状态，是则返回false，返回true
    notFirstState(jobStatus) {
      if (jobStatus !== '0') {
        return true
      } else {
        return false
      }
    },
    // 显示窨井详情
    showWellDetail(row) {
      this.wellShow = true
      this.$refs.wellInfo.initDialog(row.wellId)
    },
    // 工单
    showJob(jobId) {
      console.log('showJob')
      this.$router.push({ path: '/detailJob/' + jobId, query: { jobId: jobId }})
    },
    // 批量导出
    batchExport() {
      // 全屏加载动画
      const loading = this.$loading({
        lock: true,
        text: '下载中,请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      exportOvertimeHandleJobList(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
      }
      getOvertimeHandleJobList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = parseInt(response.data.total)
        this.listLoading = false
      })
    },
    // 获取告警类型
    fetchAlarmType() {
      getAlarmType().then(response => {
        this.alarmTypeList = response.data
        if (!isOperation()) { // 如果不是管理员和运维人员
          this.showAlarmType = false
          this.listQuery.alarmType = '1'
        }
      })
    },
    // 获取告警内容类别
    fetchAlarmContentType() {
      this.alarmContentTypeList = []
      getAlarmContentType(this.listQuery.alarmType).then(response => {
        const supportDeviceTypes = this.$store.getters.deviceTypes
        for (const item of response.data.list) {
          if (supportDeviceTypes.indexOf(item.deviceType) !== -1) {
            this.alarmContentTypeList.push(item)
          }
        }
      })
    },
    handleJob(id) {
      this.$confirm(
        '确定后工单状态会转为处理中，您确定要执行此操作吗？',
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        handleJob(id).then(response => {
          if (response.code === 200) {
            this.$message.success('处理成功')
            this.fetchData()
          }
        })
      })
    },
    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
    }
  }
  .warning{
    color: red;
  }
</style>
