<template>
  <div class="pomp-box">
      <p class="box-title"><i class="box-header" v-if='itemsData.content'>报警详情：{{itemsData.content.split('/')[0]}}<span>{{itemsData.content.split('/')[1]}}</span></i><Icon type="md-close" class='close-btn' @click="closeMask"/></p>
      <div class="box-content">
          <p :class="`${classStyle}`">{{itemsData.status=='alarm'?(itemsData.deal==0?"待手动处理":"未恢复"):"已恢复"}}</p>
          <p class="notification"><i v-if="messageName.length>0"><img src="/static/img/message.png" alt="">已短信通知 {{messageName.join("、")}}</i>
          <span v-if="emailName.length>0"><img src="/static/img/email.png" alt="">已邮件通知 {{emailName.join("、")}}</span></p>
          <p class="my-time">报警开始时间<span v-if="itemsData.ctime">{{formatTime(itemsData.ctime)}}</span></p>
          <p class="my-time">报警持续时间<span>{{secondsToDay(itemsData.duration)}}
              <!-- <img src="/static/img/video.png" alt="">
              <i class="my-video">报警时间内有视频监控</i> -->
              </span>
          </p>
          <div class="alarm-deal-info">
              <p class="deal-title"><span class="sign-icon"></span>报警处理信息</p>
              <div v-if="itemsData.deal==1">
                  <p class="my-time">处理详情<span>已自动转工单</span></p>
                  <p class="my-time">工单状态<span>{{itemsData.event.status}}</span></p>
                  <p class="my-time">工单编号<span>{{itemsData.event.id}}</span></p>
              </div>
              <div v-if="itemsData.deal==2">
                  <p class="my-time">处理详情<span>已自动转事件</span></p>
                  <p class="my-time">工单状态<span>{{itemsData.event.status}}</span></p>
                  <p class="my-time">工单编号<span>{{itemsData.event.id}}</span></p>
              </div>
              <div v-if="itemsData.deal==3">
                  <p class="my-time">处理详情<span>上级线路已断，此条自动隐藏</span></p>
              </div>
              <div v-if="itemsData.deal==0 && itemsData.status=='recovered' && detailData.history && detailData.history.length>0">
                   <table class="deal-detail" v-for="(item,index) in detailData.history" :key='index'>
                       <tr>
                           <td class="name">处理详情</td>
                           <td class="describ"> {{item.staffName}}手动处理-报警已解决</td>
                       </tr>
                        <tr>
                            <td class="name">处理备注</td>
                            <td class="describ">
                                <p >{{item.note}}</p>
                                <template v-if="item.attachment">
                                    <div style="display:inline-block" v-for="(item2,index2) in item.attachment" :key='index2'>
                                        <p class="attach" v-if="item2.type=='file'"><a :href="$store.state.baseUrl + item2.url">非图片附件名称</a></p>
                                        <div class="pic" v-if="item2.type=='image'">
                                            <img :src="$store.state.baseUrl + item2.url" alt="">
                                        </div>
                                    </div>
                                </template>
                            </td>
                        </tr>
                    </table>
              </div>
             <div v-if="itemsData.deal==0 && itemsData.status=='alarm' ">
                   <div  class="collspan-box"  v-if="detailData.history && detailData.history.length>0">
                       <p class="deal-remind">此设备历史上出现过同样的报警，相关备注供您参考：</p>
                        <table class="deal-detail"  v-for="(item,index) in detailData.history" :key="index">
                            <tr>
                                <td>{{formatTime(item.rtime)}}</td>
                                <td class="name">{{item.staffName}}</td>
                                <td class="describ">
                                    <p>{{item.note}}</p>
                                    <template v-if="item.attachment">
                                        <div style="display:inline-block" v-for="(item2,index2) in item.attachment" :key='index2'>
                                            <p class="attach" v-if="item2.type=='file'"><a :href="$store.state.baseUrl + item2.url">非图片附件名称</a></p>
                                            <div class="pic" v-if="item2.type=='image'">
                                                <img :src="$store.state.baseUrl + item2.url" alt="">
                                            </div>
                                        </div>
                                    </template>
                                </td>
                            </tr>
                        </table>
                   </div>
                     <Button class="check-line" v-if="detailData.history && detailData.history.length>3 && showHeight" @click="getMoreDetail">查看更多</Button>
                     <Button class="check-line" v-if="detailData.history && detailData.history.length>3 && !showHeight" @click="closeMoreDetail">收起</Button>
                    <p class="remarks" v-if='!recentNote && detailData' @click="showRecentAlarmNote" ><img src="/static/img/warn.png"> 查看近期其他设备的此类报警备注</p>
                   <div class="recent-detail" v-if='recentNote'>
                         <Button class="check-line"  @click="closeRecentAlarmNote">收起</Button>
                        <div v-for="(el,ind) in RecentAlarm" :key="ind">
                             <p class="deal-remind">{{locationT(el)}} {{el.object?el.object.name:""}} {{el.object?el.object.id : ''}}</p>
                         <table class="deal-detail" v-for="(item, index1) in el.alarmList"  :key="index1">
                            <tr>
                                <td>{{formatTime(item.rtime)}}</td>
                                <td class="name">{{item.staffName}}</td>
                                <td class="describ">
                                    <p>{{item.alarmName}}</p>
                                    <template v-if="item.attachment">
                                        <div style="display:inline-block" v-for="(item2,index2) in item.attachment" :key="index2">
                                            <p class="attach" v-if="item2.type=='file'"><a :href="$store.state.baseUrl + item2.url">非图片附件名称</a></p>
                                            <div class="pic" v-if="item2.type=='image'">
                                                <img :src="$store.state.baseUrl + item2.url" alt="">
                                            </div>
                                        </div>
                                    </template>
                                </td>
                            </tr>
                        </table>
                        </div>
                   </div>
                    <div class="manual">
                        <p class="manual-alarm-title">请手动处理报警</p>
                        <div class="manual-alarm-radio">
                            <span>处理方式<i>*</i></span>
                            <RadioGroup v-model="radio">
                                <Radio label="此条报警是误报"></Radio>
                                <Radio label="报警已解决"></Radio>
                            </RadioGroup>
                            <span v-if="false"><i>请选择处理方式</i></span>
                        </div>
                        <div class="manual-alarm-mode">
                            <span>填写备注</span>
                            <div>
                                <Input v-model="note" type="textarea" :rows="4" :maxlength="100"/>
                            </div> <span> ({{note.length}}/100)</span>
                        </div>
                        <div class="manual-upload">
                            <span>上传附件</span>
                            <Button class="my-btn"><label class="my-label">点击上传</label>
                            <input multiple name="file" type="file" id="file" @change="getFile($event)"/></Button> <span> ({{attachment.length}}/3)</span>
                        </div>
                         <div class="upload-filename">
                             <p v-for="(item, index) in attachment" :key="index"><span>{{item.fileName}}</span><Icon type="ios-close-circle" @click="deleteFile(index)" /></p>
                             <span v-if="loading">uploading...</span>
                             <span v-if="fileMsg">上传文件不能超过3个</span>
                        </div>
                        <div class="deal-button"><Button type="primary" size='large' @click="upload(itemsData.id)">确认处理</Button>
                        <span v-if="sucMsg" class="success-message">报警处理成功！</span><span v-if="errMsg" class="error-message">报警处理失败！</span></div>
                    </div>
             </div>
          </div>
          <div class="alarm-deal-info" v-if="detailData.algorithmType || detailData.algorithmType=='sump'">
            <p class="deal-title"><span class="sign-icon"></span>报警触发详情</p>
            <div class="my-range" v-if="detailData.algorithmType=='threshold'">
                <sgy-range :alarmVal="`${detailData.algorithmInfo.triggerValue}`" :min="`${detailData.algorithmInfo.threshold.lower}`"
                :max="`${detailData.algorithmInfo.threshold.upper}`" :currentValue='`${detailData.algorithmInfo.currentValue}`' :unit='detailData.unit'></sgy-range>
            </div>
            <div style="margin-top:20px">
                <Button class="check-line" v-if="startBtn" @click="showEcharts">查看报警时间段内数值曲线</Button>
                <Button class="check-line" v-else  @click="closeEcharts">收起</Button>
            </div>
            <alarm-charts v-if="tag && charts.length>0" :charts="charts" :detailData='detailData'></alarm-charts>
          </div>
      </div>
  </div>
</template>

<script>
import SgyRange from '../../common/SgyRange'
import alarmCharts from './alarmCharts.vue'
import axios from 'axios'
import {formatTime, secondsToDay, amendTime, date} from '../../tools/formatTime.js' // amendTime, date
import { setTimeout } from 'timers'
import Bus from '../../tools/bus.js'
export default {
  components: {
    SgyRange,
    alarmCharts
  },

  mixins: [],

  props: ['itemsData', 'messageName', 'emailName', 'detailData'],

  data () {
    return {
      formatTime,
      secondsToDay,
      radio: '此条报警是误报',
      tag: false,
      startBtn: true,
      recentNote: false,
      staffName: "王晓丽",
      note: "",
      sucMsg: false,
      errMsg: false,
      charts: [],
      fileList: [],
      loading: false,
      fileMsg: false,
      showHeight: true,
      RecentAlarm: [],
      attachment: []
    }
  },

  computed: {
    classStyle () {
      if (this.itemsData.status == 'alarm') {
        if (this.itemsData.deal == 0) {
          return 'handleAuto'
        } else {
          return 'state'
        }
      } else {
        return 'nostate'
      }
    }
  },

  mounted () {
  },

  methods: {
    locationT (RecentAlarm) {
      if (RecentAlarm.object && RecentAlarm.object.location) {
        return (RecentAlarm.object.location.buildingName ? RecentAlarm.object.location.buildingName : "") + (RecentAlarm.object.location.floorName ? RecentAlarm.object.location.floorName : "") +
        (RecentAlarm.object.location.spaceName ? RecentAlarm.object.location.spaceName : "") + RecentAlarm.object.location.equipmentName ? RecentAlarm.object.location.equipmentName : ""
      }
    },
    // 查看更多
    getMoreDetail () {
      this.showHeight = false
      let box = document.querySelector(".collspan-box")
      box.style.overflow = "visible"
      box.style.height = 'auto'
    },
    // 收起更多的信息
    closeMoreDetail () {
      this.showHeight = true
      let box = document.querySelector(".collspan-box")
      box.style.overflow = "hidden"
      box.style.height = '200px'
    },
    // 上传图片或文件
    getFile (event) {
      let baseUrl = this.$store.state.baseUrl
      const files = event.target.files
      let vm = this
      this.fileList = [...files]
      if (this.attachment.length + files.length > 3) {
        this.fileMsg = true
        setTimeout(function () {
          vm.fileMsg = false
        }, 3000)
        return
      }
      this.fileList.forEach((i) => {
        let fileName = new Date().getTime() + i.name
        let url
        let type = ""
        let url1 = ""
        if (i.type.toString().split("/")[0] == 'image') {
          type = 'image'
          url = `${baseUrl}/image-service/common/image_upload?systemId=dataPlatform&secret=9e0891a7a8c8e885&key=${fileName}`
          url1 = `/image-service/common/image_get?systemId=dataPlatform&key=${fileName}`
        } else {
          type = "file"
          url = `${baseUrl}/image-service/common/file_upload?systemId=dataPlatform&secret=9e0891a7a8c8e885&key=${fileName}`
          url1 = `/image-service/common/file_get?systemId=dataPlatform&key=${fileName}`
        }
        let obj = {
          fileName: fileName,
          type: type,
          url: url1
        }
        this.loading = true
        let _this = this
        let reader = new FileReader()
        reader.readAsArrayBuffer(i)
        reader.onload = function (e) {
          var xhr = new XMLHttpRequest()
          xhr.open('POST', url)
          xhr.send(reader.result)
          xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
              _this.loading = false
              if (xhr.status == 200) {
                _this.attachment.push(obj)
                console.log("图片上传成功！")
              }
            }
          }
        }
      })
    },
    deleteFile (index) {
      this.attachment.splice(index, 1)
    },
    // 修改或增加报警信息
    upload (mes) {
      let handleType = "1"
      if (this.radio == '此条报警是误报') {
        handleType = "1"
      } else {
        handleType = "2"
      }
      let params = {
        id: mes, // 报警id，必填
        staffName: this.staffName, // 处理人员姓名，必填
        handleType: handleType, // 处理方式，1此条报警是误报，2报警已经解决，必填
        note: this.note, // 备注，选填
        attachment: this.attachment
      }
      axios.post(`/alarm-system/alarm-system/alarm/manualHandle/create?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.sucMsg = true
          setTimeout(function () {
            vm.sucMsg = false
          }, 3000)
          this.note = ""
          this.attachment = []
          this.closeMask()
          Bus.$emit('main-init')
        } else {
          this.errMsg = true
          setTimeout(function () {
            vm.errMsg = false
          }, 3000)
        }
      })
    },
    // 查看近期报警备注
    showRecentAlarmNote () {
      this.recentNote = true
      let params = {
        objectId: this.detailData.objectId,
        typeCode: this.detailData.typeCode
      }
      axios.post(`/alarm-system/alarm-system/alarm/manualHandle/recentSameQuery/query?projectId=${this.$store.state.projId}&secret=${this.$store.state.secret}`, params).then(res => {
        let data = res.data
        if (data.Result == 'success') {
          this.RecentAlarm = data.Content
        }
      })
    },
    closeRecentAlarmNote () {
      this.recentNote = false
    },
    showEcharts () {
      if (this.itemsData && this.detailData) {
        this.tag = true
        this.startBtn = false
        let period1 = ""
        let receivetime = {
          $gte: "",
          $lt: ""
        }
        //  formatTime 将20190116174200 转换成2019-01-16 17:42:00  amendTime转换时间戳 然后减去10分钟，然后把时间戳转成时间再转成原来的格式
        if (this.itemsData.duration < 60) {
          period1 = "5min"
          receivetime.$gte = receivetime.$gte = date(amendTime(this.itemsData.cTime) - 10 * 60)
          if (this.itemsData.rime) {
            receivetime.$lt = date(amendTime(formatTime(this.itemsData.rtime)) + 10 * 60)
          } else {
            receivetime.$lt = date(amendTime(Date.parse(new Date())))
          }
        } else if (this.itemsData.duration < 60 * 60 * 24) {
          period1 = "15min"
          receivetime.$gte = receivetime.$gte = date(amendTime(this.itemsData.cTime) - 30 * 60)
          if (this.itemsData.rime) {
            receivetime.$lt = date(amendTime(formatTime(this.itemsData.rtime)) + 30 * 60)
          } else {
            receivetime.$lt = date(amendTime(Date.parse(new Date())))
          }
        } else if (this.itemsData.duration < 60 * 60 * 24 * 7) {
          period1 = "1h"
          receivetime.$gte = receivetime.$gte = date(amendTime(this.itemsData.cTime) - 3 * 60 * 60)
          if (this.itemsData.rime) {
            receivetime.$lt = date(amendTime(formatTime(this.itemsData.rtime)) + 3 * 60 * 60)
          } else {
            receivetime.$lt = date(amendTime(Date.parse(new Date())))
          }
        } else {
          period1 = "1d"
          receivetime.$gte = receivetime.$gte = date(amendTime(this.itemsData.cTime) - (3 * 24 * 60 * 60))
          if (this.itemsData.rime) {
            receivetime.$lt = date(amendTime(formatTime(this.itemsData.rtime)) + (3 * 24 * 60 * 60))
          } else {
            receivetime.$lt = date(amendTime(Date.parse(new Date())))
          }
        }

        let params = {
          criteria: {
            id: this.detailData.objectId,
            code: this.detailData.infoCode, // 信息点编码
            period: period1,
            receivetime: receivetime
          }
        }
        axios.post(`/data-platform-3/data-platform-3/hisdata/query_period_data?projectId=${this.$store.state.projId}&secret=${this.$store.state.secret}`, params).then(res => {
          let data = res.data
          if (data.Result == 'success') {
            this.charts = data.Content
            this.charts.forEach(el => {
              el.time = formatTime(el.data_time)
              el.value = parseInt(el.data_value)
            })
          } else {
            this.charts = []
          }
        })
      }
    },
    closeEcharts () {
      this.tag = false
      this.startBtn = true
    },
    closeMask () {
      this.recentNote = false
      this.tag = false
      this.startBtn = true
      this.$emit('onClose')
    }
  }

}
</script>

<style scoped lang="less" >
.pomp-box {
    font-size: 14px;
    color: #6D747C;
    .box-title {
        line-height: 60px;
        height: 60px;
        font-size: 16px;
        color: #FFFFFF;
        background: #728DEE;
        padding-left: 40px;
        margin-bottom: 0;
        .box-header{
            display: inline-block;
            width: 503px;
            height: 60px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .close-btn{
            float: right;
            margin-top: 20px;
            margin-right: 14px;
            cursor: pointer;
        }
        >span {
            opacity: 0.7;
            font-size: 7px;
            padding-left: 14px;
        }
    }
    .box-content {
        padding: 20px 0 0 40px;
        height: 520px;
        overflow-y: auto;
        .state {
          font-size: 16px;
          color: #F08378;
          font-weight: bold;
        }
        .handleAuto{
            font-size: 16px;
            color: #F3B767;
            font-weight: bold;
        }
        .nostate{
          font-size: 16px;
          color: #3BC6A1;
          font-weight: bold;
        }
        .notification{
            color: #6D747C;
            font-size: 12px;
            padding-top: 10px;
            img{
                //vertical-align: middle;
                margin-right: 8px;
            }
            >i{
                padding-right:180px;
            }
        }
        .my-time {
            font-size: 14px;
            padding-top: 14px;
            >span {
                padding-left: 14px;
                color:#212830;
            }
            img {
                vertical-align: middle;
                margin-left: 45px;
            }
            .my-video {
                color: #728DEE;
                padding-left: 8px;
            }
        }
        .alarm-deal-info {
            margin:20px 0 54px 0;
            .deal-title {
                font-size: 16px;
                color:#212830;
                .sign-icon {
                    display: inline-block;
                    width: 8px;
                    height: 16px;
                    background:#728DEE;
                    margin-right: 8px;
                    vertical-align: middle;
                }
            }
            .collspan-box{
                height: 200px;
                overflow: hidden;
            }
            .deal-remind {
                color: #6D747C;
                font-size: 14px;
                padding-top: 20px;
            }
            .deal-detail {
                margin-top: 20px;
               tr {
                   height: 38px;
                   vertical-align: top;
                   .name {
                       width: 72px;
                       text-align: center;
                   }
                   .describ{
                       color: #212830;
                       >p {
                           word-break: break-all;
                       }
                   }
                   .attach{
                       color:#728DEE;
                       padding:14px 0;
                       cursor: pointer;
                       display: block;
                   }
                   .pic{
                       display: inline-block;
                       width: 108px;
                       height: 108px;
                       background: #E9E9E9;
                       border-radius: 2px;
                       margin-right: 16px;
                       >img {
                           width: 107px;
                           height: 108px;
                       }
                   }
               }
            }
            .remarks {
                padding:30px 0 20px 0;
                color: #728DEE;
                cursor: pointer;
                img {
                    vertical-align: middle;
                    margin-right: 2px;
                    width: 16px;
                    height: 16px;
                }

            }
            .recent-detail{
                width: 640px;
                padding: 20px;
                border-radius: 2px;
                background:#F7F7F7;
                margin: 20px 0;
            }
            .manual {
                width: 640px;
                background: #F4F6FE;
                border-radius: 2px;
                padding: 0 20px 20px 20px;
                .manual-alarm-title {
                    text-align: center;
                    color: #212830;
                    padding: 20px 0 10px 0;
                }
                .manual-alarm-radio{
                    margin-bottom:20px;
                        span {
                        padding-right: 30px;
                        >i {
                            color: #F08378;
                            margin-left: 4px;
                        }
                    }
                }
                .manual-alarm-mode {
                    display: flex;
                    span {
                        padding-right: 45px;
                    }
                    >div {
                        width: 454px;
                        background: #FFFFFF;
                        border-radius: 2px;
                    }
                }
                .manual-upload {
                    //display: flex;
                    margin-top: 20px;
                    span {
                        padding-right: 30px;
                    }
                    .my-btn {
                      width: 440px;
                      height: 30px;
                      line-height: 13px;
                      text-align: center;
                      color: #728DEE;
                      border: 1px solid #728DEE;
                      border-radius: 2px;
                      position: relative;
                      cursor: pointer;
                      &:hover {
                            background-color:#efefef;
                          }
                      .my-label{
                          position: absolute;
                          left: 196px;
                          font-size: 14px;
                      }
                      input[type='file']{
                           cursor: pointer;
                           width: 454px;
                           display: inline;
                           opacity: 0;
                      }
                    }
                }
                .upload-filename{
                    margin-left: 100px;
                    margin-bottom: 20px;
                    background: #F4F6FE;
                    width: 454px;
                    line-height: 30px;
                    > p {
                        i {
                            font-size: 16px;
                            float: right;
                            margin: 6px 25px 0 0;
                            cursor: pointer;
                            &:hover {
                                color: red;
                                transform: scale(1.1)
                            }
                        }
                    }
                }
                .deal-button {
                    text-align: center;
                }
                .success-message{
                    padding-left: 20px;
                    color:#3BC6A1;
                }
                .error-message {
                    padding-left: 20px;
                    color:#F08378;
                }
            }
            .my-range {
                margin:30px 20px;
            }
            .check-line {
                color:#728DEE;
            }
        }
    }
}
</style>
