<template>
  <div class="first-pages">
    <div class="myfirst-head" v-if="false">
      <div class="f-left"></div>
      <div class="f-right">
        <p class="f-salarm">近期以下设备或空间状态异常，请多加关注！</p>
        <p class="f-sroom"><span>风机盘管0001号-二层空调机房、风机盘管0001号-工作大厅、制冷机房-01号 </span>连续多次出现报警</p>
        <p class="f-longalarm"><span>新风机19号-一楼新风机房</span>出现超长时间报警</p>
        <Icon type="md-close" class="close-btn" @click="closeBox"/>
      </div>
    </div>
	<div class="f-tab">
    <div class="s-tab" :class="{clearness: clear == 0}" @click="onClickTab(0)" v-if="unrecoveredCount!=0">
			<img src="/static/img/alarm.png" alt="">当前未恢复<strong>{{unrecoveredCount}}</strong><span class="s-info">其中严重报警<strong>{{urgencyCount}}</strong></span>
    </div>
    <div class="s-tab" :class="{clearness: clear == 0}" @click="onClickTab(0)" v-if="unrecoveredCount==0">
			<img src="/static/img/alarm.png" alt="">全部报警已恢复
    </div>
    <div class="deal-tab" :class="{clearness: clear == 1}" @click="onClickTab(1)" v-if="manualCount!=0">
      <img src="/static/img/deal.png" alt="">需手动处理<strong>{{manualCount}}</strong>
    </div>
    <div class="deal-tab" :class="{clearness: clear == 1}" @click="onClickTab(1)" v-if="manualCount==0">
      <img src="/static/img/deal.png" alt="">报警全部自动处理
    </div>
    <div class="detect-tab" :class="{clearness: clear == 2}" @click="onClickTab(2)">
      <img src="/static/img/auto.png" alt="">累计为您监测报警数<strong>{{totalCount}}</strong><span v-if="totalCount">其中已帮您自动处理<strong class="deal-info">{{(autoHandledCount/totalCount*100).toFixed(1)}}%</strong></span>
			<button class="history-alarm">查找历史报警</button>
    </div>
  </div>
  <div class="f-select-table">
		<my-select ref="mySelect" @setSelectParams="setSelectParams" :datePickerKey='datePickerKey' :dateLimitDays="dateLimitDays"></my-select>
		<p class="my-alarm">
			<span>您在报警消息功能中设定过报警通知内容</span>
			<Checkbox v-model="isAlarm" label="只看通知给我的报警" name="type" @on-change="getDataList"></Checkbox>
		</p>
		<table-alarm v-if="clear==0" :tableData='tableData'  @setSort='setSort'></table-alarm>
		<status-table v-if="clear==1" :tableData='tableData'  @setSort='setSort'></status-table>
		<history-table v-if="clear==2" :historyTableData='historyTableData' :total='total' :Current='pageCurrent'
		:pageSize='pageSize' @changeCurrentPage='changeCurrentPage' @setSort='setSort'></history-table>
  </div>
  </div>
</template>

<script>
import tableAlarm from './TableAlarm'
import statusTable from './StatusTable.vue'
import historyTable from './HistoryTable'
import mySelect from './Select.vue'
import axios from 'axios'
import {formatTime, secondsToDay} from '../../tools/formatTime.js'
import dataPickerConfig from '../../tools/dataPickerConfig.js'
import Bus from '../../tools/bus.js'
export default {
  components: {
    tableAlarm,
    mySelect,
    statusTable,
    historyTable
  },

  mixins: [],

  props: [],

  data () {
    return {
      datePickerKey: 'all',
      dateLimitDays: Number.MAX_SAFE_INTEGER,
      isAlarm: false, // 您在报警消息功能中设定过报警通知内容 复选框的默认值
      unrecoveredCount: 0,
      urgencyCount: 0,
      manualCount: 0,
      totalCount: 0,
      autoHandledCount: 0,
      phoneNum: "13546321876",
      tableData: [
      ],
      selectParams: { // 所有下拉框的默认值
        selectedLevel: [], // 级别
        selectedType: [], // 类型
        selectedPosition: {
          buildingId: [],
          floorId: [],
          spaceId: []
        }, // 位置
        selectedDurationTime: "", // 持续时间
        selectedStartTime: { // 开始时间
          dStart: "", // 20181115000000
          dEnd: "" // 20181215000000
        }
      },
      order: { // 选填，没有order字段时按照默认顺序排序
        column: "", // 要排序的列名，只支持level，duration，ctime
        asc: true // true升序，false降序
      },
      status: 'alarm', // 区分3个tab的状态
      autoHandle: null, // 区分3个tab的手动自动
      clear: 0, // 自定义3个tab的样式区分 opcity
      total: 20, // 分页显示多少条数据
      pageSize: 10, // 每页显示多少条数据
      pageCurrent: 1, // 当前页
      historyTableData: [], // 历史报警的表格数据
      AlarmList: [] // 报警条目列表
    }
  },

  computed: {

  },
  mounted () {
    Bus.$on('main-init', this.init)
    this.init()
  },
  methods: {
    // 初始化调用
    init () {
      this.query_statistics()
      this.getDataList()
    },
    // 触发排序函数
    setSort (col) {
      this.order.column = col.key
      this.order.asc = col.order == 'asc'
      this.getDataList()
    },
    // 每个下拉框值变化触发表格数据的返回值
    setSelectParams (obj) {
      this.selectParams = obj
      if (this.clear == 0) {
        this.status = 'alarm'
        this.autoHandle = null
      } else if (this.clear == 1) {
        this.status = 'alarm'
        this.autoHandle = false
      } else {
        this.status = null
        this.autoHandle = null
      }
      this.getDataList()
    },
    // 区分点击的tab,并且传不同的参数的函数
    onClickTab (status) {
      if (status == 0) {
        this.clear = 0
        this.status = 'alarm'
        this.autoHandle = null
        this.datePickerKey = 'all'
        this.dateLimitDays = Number.MAX_SAFE_INTEGER
      } else if (status == 1) {
        this.clear = 1
        this.status = 'alarm'
        this.autoHandle = false
        this.datePickerKey = 'all'
        this.dateLimitDays = Number.MAX_SAFE_INTEGER
      } else {
        this.clear = 2
        this.status = null
        this.autoHandle = null
        this.datePickerKey = 'oneMonth'
        this.dateLimitDays = 30
      }
      this.selectParams.selectedStartTime.dStart = dataPickerConfig[this.datePickerKey].dStart // 20181215000000
      this.selectParams.selectedStartTime.dEnd = dataPickerConfig[this.datePickerKey].dEnd
      console.log(this.selectParams.selectedStartTime)
      this.getDataList()
    },
    // 查询3个tab中涉及到的数据
    query_statistics () {
      axios.get(`/dp-auxiliary/alarm-system/alarm/statistics/query?projectId=${this.$store.state.projId}&secret=${this.$store.state.secret}`)
        .then(res => {
          let data = res.data
          if (data.Result == 'success') {
            this.unrecoveredCount = data.unrecoveredCount
            this.urgencyCount = data.urgencyCount
            this.manualCount = data.manualCount
            this.totalCount = data.totalCount
            this.autoHandledCount = data.autoHandledCount
          }
        })
    },
    // 默认未恢复的请求函数
    getDataList () {
      // 持续时间的转换
      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 = null
      if (Object.values(this.selectParams.selectedStartTime).some(i => i.length)) {
        ctime = {
          $gte: this.selectParams.selectedStartTime.dStart,
          $lte: this.selectParams.selectedStartTime.dEnd
        }
      }
      let objectId = null
      if (Object.values(this.selectParams.selectedPosition).some(i => i.length > 0)) {
        objectId = [...this.selectParams.selectedPosition.buildingId, ...this.selectParams.selectedPosition.floorId, ...this.selectParams.selectedPosition.spaceId].join(',')
      }

      let order = null
      if (Object.values(this.order).some(i => i.length)) {
        order = this.order
      }
      let phoneNum = null
      if (this.isAlarm == false) {
        phoneNum = null
      } else {
        phoneNum = this.phoneNum
      }
      // 参数的添加
      let params = {
        criteria: {
          levels: this.selectParams.selectedLevel.length > 0 ? this.selectParams.selectedLevel : null, // 选填，报警等级
          labels: this.selectParams.selectedType.length > 0 ? this.selectParams.selectedType : null, // 选填，报警类型
          objectId: objectId,
          objectName: this.selectParams.keyword == '' ? null : this.selectParams.keyword, // 选填，设备名称，模糊匹配
          ctime: ctime,
          duration: duration,
          status: this.status,
          autoHandle: this.autoHandle,
          phoneNum: phoneNum
        },
        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
          if (data.Result == 'success') {
            this.tableData = []
            this.tableData = data.Content
            this.total = data.Count
            this.tableData.forEach(el => {
              el.cTime = formatTime(el.ctime)
              el.durationT = secondsToDay(el.duration)
              el.alarmName = 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.clear == 2) {
              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
    },
    closeBox () {
      document.querySelector('.myfirst-head').style.display = 'none'
    }
  }

}
</script>

<style scoped lang="less" >
.first-pages {
	width: 100%;
	.myfirst-head {
		width: 100%;
		background: #FFF6F5;
		border-radius: 2px;
		font-size: 14px;
		display: flex;
		margin-bottom:20px;
		position: relative;
		.f-left{
			width: 8px;
			background: #F08378;
			display: inline-block;
		}
		.f-right{
			padding: 20px 0 20px 38px;
			display: inline-block;
			>p{
				margin-bottom:0;
			}
			.close-btn{
				position: absolute;
				right: 12px;
				top: 12px;
			}
			.f-salarm {
				font-size: 16px;
				color: #F08378;
				font-weight: bold;
			}
			.f-sroom {
				padding: 20px 0;
				&>span {
					color: #728DEE;
				}
			}
			.f-longalarm >span {
				color: #728DEE;
			}
		}
	}
	.f-tab {
		font-size: 14px;
		color: #6D747C;
		display: flex;
		justify-content:space-between;
		img{
			width: 50px;
			height: 50px;
			margin-right: 40px;
			//vertical-align: middle;
		}
		strong{
			font-family: DIN-Medium;
			font-size: 24px;
			padding: 0 30px 0 20px;
		}
		div{
			padding: 30px 0 30px 30px;
			background: #fff;
			cursor: pointer;
			border-radius: 2px;
			display: inline-block;
			margin-bottom: 20px;
		}
		.s-tab {
			width: 572px;
			margin-right: 20px;
			.s-info{
				color: #E98576;
			}
		}
		.deal-tab{
			width: 360px;
			margin-right: 20px;
		}
		.detect-tab{
			width: 730px;
			position: relative;
			.deal-info{
				color: #4EC59E;
			}
			.history-alarm{
				font-size: 14px;
        color: #728DEE;
        background: #fff;
				position: absolute;
				top: 20px;
				right: 18px;
				cursor: pointer;
			}
		}
		.clearness {
			box-shadow: 0 2px 10px 0 rgba(44,48,62,0.16);
		}
	}
	.f-select-table{
		background: #FFFFFF;
		box-shadow: 0 2px 10px 0 rgba(44,48,62,0.06);
		border-radius: 2px;
		.my-alarm {
			padding: 20px 0 20px 24px;
			font-size: 14px;
			background: #FFFFFF;
			display: flex;
        >span{
           color: #6D747C;
           margin-right: 30px;
        }
    }
	}
}
</style>
<style lang='less'>

</style>
