<template>
  <div class="equipment">
      <div class="eq-top">
           <img src="/static/img/backIcon.jpg" alt="" @click="back">
           <span>设备详情 / </span>
            <strong>{{eqName}}-{{objectId}}报警详情</strong>
      </div>
      <div class="eq-head" v-if="false">
        <div class="f-left"></div>
        <div class="f-right">
			<p class="f-salarm">近期多次出现以下报警：“电流谐波畸变率过高”、“室温温度传感器出错”、“电压过压”。可能存在设备或零件老化，请多加关注！</p>
			<Icon type="md-close" class="close-btn" @click="closeBox"/>
        </div>
    </div>
      <div class="eq-bottom">
          <div class="alarm-top">
            <span @click="onClickTab(0)" :class="{active: activeIndex== 0}">当前未恢复报警</span>
            <span @click="onClickTab(1)" :class="{active: activeIndex== 1}">历史报警记录</span>
            <span @click="onClickTab(2)" :class="{active: activeIndex== 2}">手动处理备注</span>
          </div>
          <div v-if="activeIndex==0">
              <table-alarm :tableData='tableData' @setSort='setSort'></table-alarm>
          </div>
          <div v-if="activeIndex==1">
               <div class="my-select-type">
                    <my-select  @setSelectParams="setSelectParams" @setChangeAlarm='setChangeAlarm' :datePickerKey='datePickerKey'
                    :dateLimitDays='dateLimitDays' :alarmNameList='alarmNameList'></my-select>
               </div>
               <history-table v-if="show" :historyTableData='historyTableData' :total='total' :Current='pageCurrent'
		:pageSize='pageSize' @changeCurrentPage='changeCurrentPage'  @setSort='setSort'></history-table>
          </div>
          <div v-if="activeIndex==2">
              <my-handle v-show="show" :objectId='objectId'></my-handle>
          </div>
      </div>
  </div>
</template>

<script>
import tableAlarm from '../main/TableAlarm.vue'
import historyTable from '../main/HistoryTable'
import mySelect from './EqSelect.vue'
import myHandle from './Handle.vue'
import {formatTime, secondsToDay} from '../../tools/formatTime.js'
import dataPickerConfig from '../../tools/dataPickerConfig.js'
// import {mapActions, mapMutations, mapGetters, mapState} from 'vuex'
import axios from 'axios'
// import { setTimeout } from 'timers'
export default {
  components: {
    tableAlarm,
    mySelect,
    myHandle,
    historyTable
  },

  mixins: [],

  props: {

  },

  data () {
    return {
      show: false,
      datePickerKey: 'oneMonth',
      dateLimitDays: Number.MAX_SAFE_INTEGER,
      activeIndex: 0,
      pageSize: 15,
      historyTableData: [],
      tableData: [],
      total: null,
      pageCurrent: 1,
      order: { // 选填，没有order字段时按照默认顺序排序
        column: "", // 要排序的列名，只支持level，duration，ctime
        asc: true // true升序，false降序
      },
      status: 'alarm', // 区分3个tab的状态
      autoHandle: null, // 区分3个tab的手动自动
      selectParams: { // 所有下拉框的默认值
        selectedLevel: [], // 级别
        selectedDurationTime: "", // 持续时间
        selectedStartTime: { // 开始时间
          dStart: "",
          dEnd: ""
        },
        alarmName: []
      },
      alarmNameList: [],
      objectId: "Eq1101080002001ACATFC031",
      eqName: ""
    }
  },

  computed: {

  },

  mounted () {
    this.getEqNameAndId()
  },

  methods: {
    // 监控到如果时间改变，重新触发请求报警条目的函数
    setChangeAlarm () {
      this.saveAlarmName()
    },
    // 根据路由得到设备名称和id
    getEqNameAndId () {
      let hostUrl = location.search
      if(hostUrl){
        let pid = hostUrl.split('&')[1].toString().split('=')[1]
        this.$store.commit('setProId', pid)
        this.$store.commit(`setSecret`, '')
        this.eqName = decodeURI(location.hash)
        this.objectId = hostUrl.split("&")[2]
      }
      this.getDataList()
      this.saveAlarmName()
      this.show = true
    },
    // 存储条目数
    saveAlarmName () {
      let ctime = {}
      if (Object.values(this.selectParams.selectedStartTime).some(i => i.length)) {
        ctime = {
          $gte: this.selectParams.selectedStartTime.dStart,
          $lte: this.selectParams.selectedStartTime.dEnd
        }
      } else {
        ctime = null
      }
      let params = {
        objectId: this.objectId,
        ctime: ctime
      }
      axios.post(`/dp-auxiliary/alarm-system/alarm/alarmName/list?projectId=${this.$store.state.projId}&secret=${this.$store.state.secret}`, params).then(res => {
        let data = res.data
        if (data.Result == 'success') {
          this.alarmNameList = data.Content
          this.alarmNameList = Array.from(new Set(this.alarmNameList)).map(el => {
            return {value: el, text: el}
          })
        }
      })
    },
    back () {
      history.go(-1)
    },
    closeBox () {
      document.querySelector('.eq-head').style.display = 'none'
    },
    // 请求得到报警条目列表，传给后台 objectId ctime

    // 每个下拉框值变化触发表格数据的返回值
    setSelectParams (obj) {
      this.selectParams = obj
      if (this.activeIndex == 0) {
        this.status = 'alarm'
        this.autoHandle = null
      } else if (this.activeIndex == 2) {
        this.status = 'alarm'
        this.autoHandle = false
      } else {
        this.status = null
        this.autoHandle = null
      }
      this.getDataList()
    },
    // 触发排序函数
    setSort (col) {
      this.order.column = col.key
      this.order.asc = col.order == 'asc'
      this.getDataList()
    },
    // 3个按钮的点击传参数
    onClickTab (status) {
      this.activeIndex = status
      if (status == 0) {
        this.status = 'alarm'
        this.autoHandle = null
        this.getDataList()
        this.dateLimitDays = Number.MAX_SAFE_INTEGER
      } else if (status == 2) {
        this.status = 'alarm'
        this.autoHandle = false
        this.dateLimitDays = Number.MAX_SAFE_INTEGER
      } else {
        this.status = null
        this.autoHandle = null
        this.selectParams.selectedStartTime.dStart = dataPickerConfig[this.datePickerKey].dStart // 20181215000000
        this.selectParams.selectedStartTime.dEnd = dataPickerConfig[this.datePickerKey].dEnd
        this.dateLimitDays = 30
        this.getDataList()
        this.saveAlarmName()
      }
    },
    // 默认未恢复的请求函数
    getDataList () {
      // 得到项目id和secret
      let params
      // 排序
      let order = null
      if (Object.values(this.order).some(i => i.length)) {
        order = this.order
      }

      // 持续时间的转换
      let duration = {}
      if (Object.values(this.selectParams.selectedDurationTime).some(i => i.length)) {
        if (this.selectParams.selectedDurationTime == '5m') {
          duration.$lt = 5 * 60
        } else if (this.selectParams.selectedDurationTime == '2h') {
          duration.$gte = 300
          duration.$lte = 2 * 60 * 60
        } else if (this.selectParams.selectedDurationTime == '24h') {
          duration.$gte = 2 * 60 * 60
          duration.$lte = 24 * 60 * 60
        } else if (this.selectParams.selectedDurationTime == '1d') {
          duration.$gt = 24 * 60 * 60
        }
      } else {
        duration = null
      }
      // 开始时间的转换
      let ctime = {}

      if (Object.values(this.selectParams.selectedStartTime).some(i => i.length)) {
        ctime = {
          $gte: this.selectParams.selectedStartTime.dStart,
          $lte: this.selectParams.selectedStartTime.dEnd
        }
      } else {
        ctime = null
      }
      // 参数的添加
      if (this.activeIndex == 0) {
        params = {
          criteria: {
            objectId: this.objectId,
            status: this.status
          },
          order: order
        }
      } if (this.activeIndex == 1) {
        params = {
          criteria: {
            levels: this.selectParams.selectedLevel.length > 0 ? this.selectParams.selectedLevel : null, // 选填，报警等级
            objectId: this.objectId,
            ctime: ctime,
            duration: duration,
            status: this.status,
            autoHandle: this.autoHandle,
            alarmName: this.selectParams.alarmName.length > 0 ? this.selectParams.alarmName : null // 报警条目
          },
          order: order
        }
      }
      // 请求表格数据
      axios.post(`/dp-auxiliary/alarm-system/alarm/list?projectId=${this.$store.state.projId}&secret=${this.$store.state.secret}`, params)
        .then(res => {
          let data = res.data
          //   let vm = this
          if (data.Result == 'success') {
            this.tableData = data.Content
            this.total = data.Count
            console.log(this.tableData)
            this.tableData.forEach(el => {
              el.cTime = formatTime(el.ctime)
              el.durationT = secondsToDay(el.duration)
              el.alarmName = el.alarmName || ""
              el.location = el.source ? el.source : ""
              el.content = el.alarmName + "/" + el.location
              if (!el.autoHandle) {
                el.deal = 0
              } else {
                if (el.event.type == 1) {
                  el.deal = 1
                } else if (el.event.type == 2) {
                  el.deal = 2
                } else {
                  el.deal = 3
                }
              }
            })
            // 自己分页
            if (this.activeIndex == 1) {
              this.changeCurrentPage(this.pageCurrent)
            }
          }
        })
    },
    // 分页 点击的是哪页
    changeCurrentPage (index) {
      this.historyTableData = []
      // 需要显示开始数据的index,(因为数据是从0开始的，页码是从1开始的，需要-1)
      let _start = (index - 1) * this.pageSize
      // 需要显示结束数据的index
      let _end = index * this.pageSize
      // 截取需要显示的数据
      this.historyTableData = this.tableData.slice(_start, _end)
      this.pageCurrent = index
    }
  }
}
</script>

<style scoped lang="less" >
.equipment {
    .eq-top {
        margin-bottom: 20px;
        >img {
            //vertical-align: middle;
            cursor: pointer;
            border: 1px solid #CACACA;
            border-radius: 2px;
        }
        >span {
            font-size: 16px;
            color: #728DEE;
        }
    }
    .eq-head {
        width: 100%;
        background: #FFF6F5;
        border-radius: 2px;
        font-size: 14px;
        display: flex;
        margin:10px 0 20px 0;
        //height: 60px;
        position: relative;
        .f-left {
          width: 8px;
          background: #F08378;
          display: inline-block;
        }
        .f-right {
          padding: 20px 0 20px 38px;
          display: inline-block;
          .close-btn {
            position: absolute;
            right: 12px;
            top: 22px;
          }
          .f-salarm {
            font-size: 16px;
            color: #F08378;
            font-weight: bold;
          }
        }
    }
    .eq-bottom {
        background: #FFFFFF;
        box-shadow: 0 2px 10px 0 rgba(44,48,62,0.06);
        border-radius: 2px;
        padding-top:30px;
        .alarm-top {
            margin-bottom: 40px;
            display: flex;
            justify-content: center;
            span {
            text-align: center;
            padding: 6px 20px;
            color: #62697b;
            cursor: pointer;
            border: 1px solid #cacaca;
            border-right: none;
            &:last-child {
                border-right: 1px solid #cacaca;
                border-top-right-radius: 3px;
                border-bottom-right-radius: 3px;
            }
            &:first-child {
                border-top-left-radius: 3px;
                border-bottom-left-radius: 3px;
            }
            &:hover,
            &.active {
                background: #728DEE;
                color: #fff;
            }
            }
        }
        .my-select-type {
            padding-left: 30px;
            padding-right: 20px;
        }
    }
}

</style>
