<template>
  <div class="navbar">
    <hamburger id="hamburger-container" :is-active="sidebar.opened" class="hamburger-container"
               @toggleClick="toggleSideBar"
    />

    <breadcrumb id="breadcrumb-container" class="breadcrumb-container" v-if="!topNav"/>
    <top-nav id="topmenu-container" class="topmenu-container" v-if="topNav"/>

    <div class="right-menu">
      <template v-if="device!=='mobile'">
        <search id="header-search" class="right-menu-item"/>

        <!--        <el-tooltip content="源码地址" effect="dark" placement="bottom">-->
        <!--          <ruo-yi-git id="ruoyi-git" class="right-menu-item hover-effect" />-->
        <!--        </el-tooltip>-->

        <!--        <el-tooltip content="文档地址" effect="dark" placement="bottom">-->
        <!--          <ruo-yi-doc id="ruoyi-doc" class="right-menu-item hover-effect" />-->
        <!--        </el-tooltip>-->
        <el-tooltip content="异常处理" class="right-menu-item hover-effect">
          <span
            class="exceptionHandling"
            :class="{ warnTxt: alarmDataList && alarmDataList.length > 0, 'red-yellow-blink': alarmDataList && alarmDataList.length > 0 }"
            @click="getAlarmData(true)"
          >
            <i class="el-icon-message"></i>{{
              (alarmDataList && alarmDataList.length > 0 && alarmDataList.length) || ''
            }}
          </span>
        </el-tooltip>
        <screenfull id="screenfull" class="right-menu-item hover-effect"/>

        <el-tooltip content="布局大小" effect="dark" placement="bottom">
          <size-select id="size-select" class="right-menu-item hover-effect"/>
        </el-tooltip>

      </template>

      <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
        <div class="avatar-wrapper">
          <img :src="avatar" class="user-avatar">
          <i class="el-icon-caret-bottom"/>
        </div>
        <el-dropdown-menu slot="dropdown">
          <router-link to="/user/profile">
            <el-dropdown-item>个人中心</el-dropdown-item>
          </router-link>
          <el-dropdown-item @click.native="setting = true">
            <span>布局设置</span>
          </el-dropdown-item>
          <el-dropdown-item divided @click.native="logout">
            <span>退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <!-- 告警对话框 -->
    <el-dialog
      :title="alarmTitle"
      :visible.sync="alarmOpen"
      width="1000px"
      append-to-body
    >
      <el-tabs v-model="activeTab" type="card">
        <!-- 告警列表标签页 -->
        <el-tab-pane label="告警列表" name="alarmList">
          <el-table
            v-loading="alarmLoading"
            :data="alarmDataList"
            @selection-change="handleSelectionChangeAlarm"
            @row-click="handleRowClick"
            highlight-current-row
          >
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="异常设备" align="center" prop="deviceName"/>
            <el-table-column label="异常类型" align="center" prop="cause"/>
            <el-table-column label="异常数据" align="center" prop="alarmData"/>
            <el-table-column label="异常状态" align="center" prop="alarmStatus">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.alarm_status" :value="scope.row.alarmStatus"/>
              </template>
            </el-table-column>
            <el-table-column label="记录时间" align="center" prop="collectTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click.stop="viewActionSteps(scope.row)"
                >查看措施</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="alarmDataTotal > 0"
            :total="alarmDataTotal"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getAlarmDataList"
          />
        </el-tab-pane>

        <!-- 处置措施标签页 -->
        <el-tab-pane label="处置措施" name="actionSteps" :disabled="!currentAlarmData">
          <div v-if="currentAlarmData">
            <el-alert
              :title="`设备：${currentAlarmData.deviceName} | 异常类型：${currentAlarmData.cause} | 异常数据：${currentAlarmData.alarmData}`"
              type="warning"
              :closable="false"
              style="margin-bottom: 20px;"
            />
            
            <div v-loading="actionStepsLoading">
              <div v-if="actionSteps.length === 0" class="no-steps">
                <el-empty description="该告警规则暂无配置处置措施"></el-empty>
              </div>
              
              <div v-else>
                <el-timeline>
                  <el-timeline-item
                    v-for="(step, index) in actionSteps"
                    :key="step.objId"
                    :timestamp="`步骤 ${step.stepSequence}`"
                    placement="top"
                    type="primary"
                    size="large"
                  >
                    <el-card class="step-card">
                      <div slot="header" class="clearfix">
                        <span class="step-title">第{{ step.stepSequence }}步</span>
                      </div>
                      
                      <!-- 步骤描述 -->
                      <div class="step-description">
                        <p>{{ step.description }}</p>
                      </div>
                      
                      <!-- 步骤图片 -->
                      <div v-if="step.stepImages && step.stepImages.length > 0" class="step-images">
                        <div class="images-title">参考图片：</div>
                        <div class="image-gallery">
                          <div
                            v-for="image in step.stepImages"
                            :key="image.objId"
                            class="image-item"
                            @click="previewImage(image.imageUrl)"
                          >
                            <img :src="image.imageUrl" :alt="image.description" />
                            <div v-if="image.description" class="image-desc">{{ image.description }}</div>
                          </div>
                        </div>
                      </div>
                      
                      <!-- 步骤备注 -->
                      <div v-if="step.remark" class="step-remark">
                        <el-tag type="info" size="small">备注：{{ step.remark }}</el-tag>
                      </div>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="jumpProcessing" :disabled="objIds.length === 0">
          标记已处理 ({{ objIds.length }})
        </el-button>
        <el-button @click="closeDialog">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="imagePreviewVisible"
      width="80%"
      append-to-body
      center
    >
      <div class="image-preview-container">
        <img :src="previewImageUrl" style="max-width: 100%; max-height: 70vh;" />
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Breadcrumb from '@/components/Breadcrumb'
import TopNav from '@/components/TopNav'
import Hamburger from '@/components/Hamburger'
import Screenfull from '@/components/Screenfull'
import SizeSelect from '@/components/SizeSelect'
import Search from '@/components/HeaderSearch'
import RuoYiGit from '@/components/RuoYi/Git'
import RuoYiDoc from '@/components/RuoYi/Doc'
import settings from '@/settings'
import { handleExceptions, listRecordAlarmData } from '@/api/ems/record/recordAlarmData'
import { getEmsAlarmActionStepsByRuleId, getEmsAlarmActionStepsByAlarmInfo } from '@/api/ems/base/emsAlarmActionStep'

export default {
  dicts: ['alarm_type', 'alarm_status'],
  data() {
    return {
      poolNameList: [],
      poolName: '',
      alarmTitle: '异常处理',
      alarmOpen: false,
      alarmLoading: false,
      alarmDataList: [],
      alarmDataTotal: 0,
      // 选中数组
      objIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        alarmStatus: '1'
      },
      // 措施步骤相关
      currentAlarmData: null,
      showActionSteps: false,
      actionSteps: [],
      actionStepsLoading: false,
      activeTab: 'alarmList',
      imagePreviewVisible: false,
      previewImageUrl: ''
    }
  },
  created() {
    localStorage.setItem('this.alarmDataTotal', 0)
  },
  mounted() {
    // 定时获取提示路由信息
    this.getAlarmData()
    setInterval(() => this.getAlarmData(), 1000 * 60);
  },
  components: {
    Breadcrumb,
    TopNav,
    Hamburger,
    Screenfull,
    SizeSelect,
    Search,
    RuoYiGit,
    RuoYiDoc
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'device'
    ]),
    setting: {
      get() {
        return this.$store.state.settings.showSettings
      },
      set(val) {
        this.$store.dispatch('settings/changeSetting', {
          key: 'showSettings',
          value: val
        })
      }
    },
    topNav: {
      get() {
        return this.$store.state.settings.topNav
      }
    }
  },
  methods: {
    // 打开右下角异常
    openAlarm() {
      this.$notify({
        title: '异常数据提示',
        position: 'bottom-right',
        message: this.$createElement(
          'div',
          {
            on: {
              click: () => {
                this.getAlarmData(true)
              }
            }
          },
          [this.$createElement('el-button', {}, ['点击查看'])]
        )
      })
    },
    /** 报警列表 */
    getAlarmData(open) {
      this.alarmOpen = open
      this.alarmLoading = true
      this.getAlarmDataList()
    },
    getAlarmDataList() {
      listRecordAlarmData(this.queryParams).then((response) => {
        this.alarmDataList = response.rows
        this.alarmDataTotal = response.total
        this.alarmLoading = false
        if (localStorage.getItem('this.alarmDataTotal') != this.alarmDataTotal) {
          localStorage.setItem('this.alarmDataTotal', this.alarmDataTotal)
          this.openAlarm()
        }
      })
    },
    /** 跳转处理 */
    jumpProcessing(row) {
      if (this.objIds.length === 0) {
        this.$modal.msgWarning('请勾选设备进行异常处理！')
        return
      }
      handleExceptions(this.objIds).then(response => {
        this.$modal.msgSuccess('处理成功')
        this.alarmOpen = false
      })
    },
    // 多选框选中数据
    handleSelectionChangeAlarm(selection) {
      this.objIds = selection.map((item) => item.objId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
    logout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('LogOut').then(() => {
          if (!settings.casEnable) {
            location.href = '/index'
          }
        })
      }).catch(() => {
      })
    },
    handleRowClick(row) {
      this.currentAlarmData = row
      this.activeTab = 'actionSteps'
      this.getActionSteps(row)
    },
    getActionSteps(alarmData) {
      this.actionStepsLoading = true
      getEmsAlarmActionStepsByAlarmInfo(alarmData.monitorId, alarmData.cause).then((response) => {
        this.actionSteps = response.data || []
        this.actionStepsLoading = false
      }).catch(() => {
        this.actionSteps = []
        this.actionStepsLoading = false
      })
    },
    viewActionSteps(row) {
      this.currentAlarmData = row
      this.activeTab = 'actionSteps'
      this.getActionSteps(row)
    },
    previewImage(url) {
      this.previewImageUrl = url
      this.imagePreviewVisible = true
    },
    closeDialog() {
      this.alarmOpen = false
      this.activeTab = 'alarmList'
    }
  }
}
</script>

<style lang="scss" scoped>

@keyframes redYellowBlink {
  0% {
    color: red;
  }
  50% {
    color: rgb(186, 186, 16);
  }
  100% {
    color: red;
  }
}

.red-yellow-blink {
  animation: redYellowBlink 1s infinite;
}

.navbar {
  height: 50px;
  overflow: hidden;
  position: relative;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, .08);

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background .3s;
    -webkit-tap-highlight-color: transparent;

    &:hover {
      background: rgba(0, 0, 0, .025)
    }
  }

  .breadcrumb-container {
    float: left;
  }

  .topmenu-container {
    position: absolute;
    left: 50px;
  }

  .errLog-container {
    display: inline-block;
    vertical-align: top;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 50px;

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;

      &.hover-effect {
        cursor: pointer;
        transition: background .3s;

        &:hover {
          background: rgba(0, 0, 0, .025)
        }
      }
    }

    .avatar-container {
      margin-right: 30px;

      .avatar-wrapper {
        margin-top: 5px;
        position: relative;

        .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
        }

        .el-icon-caret-bottom {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }
      }
    }
  }
}

// 措施步骤相关样式
.step-card {
  margin-bottom: 20px;
  
  .step-title {
    font-weight: bold;
    font-size: 16px;
    color: #409EFF;
  }
  
  .step-description {
    margin-bottom: 15px;
    
    p {
      line-height: 1.6;
      margin: 0;
      color: #606266;
    }
  }
  
  .step-images {
    margin-bottom: 15px;
    
    .images-title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 10px;
    }
    
    .image-gallery {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      
      .image-item {
        cursor: pointer;
        border: 2px solid #f0f0f0;
        border-radius: 4px;
        overflow: hidden;
        transition: all 0.3s;
        max-width: 200px;
        
        &:hover {
          border-color: #409EFF;
          transform: scale(1.02);
        }
        
        img {
          width: 100%;
          height: 150px;
          object-fit: cover;
          display: block;
        }
        
        .image-desc {
          padding: 8px;
          font-size: 12px;
          color: #666;
          background: #f9f9f9;
          text-align: center;
        }
      }
    }
  }
  
  .step-remark {
    margin-top: 10px;
  }
}

.no-steps {
  text-align: center;
  padding: 40px;
}

.image-preview-container {
  text-align: center;
}

</style>
