<template>
  <div :class="['realTime-block', { 'full-block': drawerShow }]">
    <!-- 遮罩层 -->
    <div class="mask" v-if="drawerShow" @click="closeRealTimeEvents"></div>
    <div :class="['flex', { 'realTime-content': drawerShow }]">
      <!-- 实时事件按钮 -->
      <div class="realTime-btn-block" @click="openRealTimeEvents">
        实时事件<span class="num-block">{{ eventsCount }}</span>
      </div>
      <!-- 实时事件抽屉弹窗 -->
      <div :class="['list-block', { action: drawerShow }]">
        <div :style="appStyle" class="realTimeEvents">
          <!-- 搜索 -->
          <div class="search-block">
            <div class="inp-block">
              <span class="i-name">关键字：</span>
              <div class="i-content">
                <el-input
                  v-model="params.keyWord2"
                  class="x-inp"
                  placeholder="输入隧道方向、桩号位置"
                />
              </div>
            </div>

            <div class="inp-block">
              <span class="i-name">告警时间：</span>
              <div class="i-content">
                <el-date-picker
                  class="x-inp"
                  v-model="alarmTime"
                  type="datetimerange"
                  range-separator="⇀"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :teleported="false"
                  start-placeholder="请选择"
                  end-placeholder="请选择"
                />
              </div>
            </div>

            <div class="btns">
              <div class="reset-btn" @click="reset">重置</div>
              <div class="search-btn" @click="search">查询</div>
            </div>
          </div>

          <!-- 列表 -->
          <el-scrollbar ref="scrollbarRef" class="scrollbar-block" v-loading="loading">
            <div class="list-item" v-for="item in listData" :key="item.id">
              <Icon icon="ep:warn-triangle-filled" :size="25" color="#FF5151" />
              <div class="content">
                <div class="title">
                  【{{ typeCompute(item).nameStr }}】
                  <span class="time">
                    {{ item.eventStartTime.slice(5, -3) }}
                  </span>
                </div>
                <div class="text ellipsis">
                  {{ carPlateStr(item.eventCarPlate) + ' ' + item.eventSituation }}
                </div>
                <div class="foot">
                  <div :class="`status-${item.eventStatus}`">
                    {{ STATUS_MAP[item.eventStatus] }}
                  </div>
                  <div class="btn-block">
                    <span class="btn" @click="goEventDetail(item.id)">事件详情</span>
                    <span
                      class="btn-red"
                      v-if="[0, 3].includes(item.eventStatus)"
                      @click="goEventDetail(item.id)"
                    >
                      处置
                    </span>
                    <span class="btn mg-l" v-else @click="goToEvent(item.id)">事件回溯</span>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="listData.length === 0 && !loading" class="empty">暂无数据</div>
          </el-scrollbar>

          <!-- 分页 -->
          <el-pagination
            background
            class="pagination"
            v-model:currentPage="params.pageNo"
            :teleported="false"
            :page-size="params.pageSize"
            layout="total, prev, pager, next"
            :total="params.total"
            :pager-count="3"
            @change="pageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { useAppStoreWithOut } from '@/store/modules/app'
import { getEventList } from '@/api/event'
import { debounce } from 'lodash-es'
import { EVENT_TYPES, EVENT_STATUS } from '@/config/dict'
import { Icon } from '@/components/Icon'
import { useTrafficStoreOut } from '@/store/modules/traffic'
import { ScrollbarInstance } from 'element-plus'
import { useRouter } from 'vue-router'

const appStore = useAppStoreWithOut()

const appStyle = computed(() => {
  return {
    height: appStore.fixHeight - 122 + 'px'
  }
})

const trafficStore = useTrafficStoreOut()

const alarmTime = computed({
  get() {
    return [params.eventStartTimeSearchStart, params.eventStartTimeSearchEnd]
  },
  set(e) {
    if (e) {
      params.eventStartTimeSearchStart = e[0]
      params.eventStartTimeSearchEnd = e[1]
    } else {
      params.eventStartTimeSearchStart = ''
      params.eventStartTimeSearchEnd = ''
    }
  }
})

const params = reactive({
  keyWord2: '',
  eventStartTimeSearchStart: '', // 开始时间
  eventStartTimeSearchEnd: '', // 结束时间
  pageNo: 1,
  pageSize: 10,
  total: 0
})

const drawerShow = ref(false) // 实时事件弹窗打开开关
const listData = ref<any[]>([])
const loading = ref(false)
const scrollbarRef = ref<ScrollbarInstance>()
const router = useRouter()

const emit = defineEmits(['handle-event-alert'])

const STATUS_MAP = Object.fromEntries(
  EVENT_STATUS.map((item) => {
    return [item.key, item.name]
  })
)

const EVENT_MAP = Object.fromEntries(
  EVENT_TYPES.map((item) => {
    return [item.key, item.name]
  })
)

// 状态计算
const typeCompute = (row) => {
  const { eventCarPlate, eventType } = row

  if (+eventType === 6) {
    return {
      classStr: 'type-1',
      nameStr: EVENT_MAP[eventType]
    }
  }

  if (eventCarPlate.length > 1) {
    return {
      classStr: 'type-2',
      nameStr: EVENT_MAP[eventType] + '(多车)'
    }
  }

  return {
    classStr: 'type-3',
    nameStr: EVENT_MAP[eventType] + '(单车)'
  }
}

// 车牌
const carPlateStr = (eventCarPlate) => {
  return eventCarPlate?.join('、')
}

// 搜索
const search = debounce(() => {
  params.pageNo = 1
  getList()
}, 100)

// 重置
const reset = () => {
  params.keyWord2 = ''
  params.eventStartTimeSearchStart = ''
  params.eventStartTimeSearchEnd = ''
  search()
}

// 分页
const pageChange = (e: number) => {
  params.pageNo = e
  getList()
}

// 获取列表
const getList = async () => {
  loading.value = true
  const res = await getEventList(params)
  listData.value = res.list
  params.total = res.total
  loading.value = false
  scrollbarRef.value!.setScrollTop(0)
}

// 跳转事件详情
const goEventDetail = (id: string, isClose: boolean = false) => {
  emit('handle-event-alert', id)
  if (isClose) {
    closeNotification()
  }
}

// 事件回溯
const goToEvent = (id: string) => {
  router.push({
    path: 'detail',
    query: { id, from: 'home' }
  })
}

// 初始化列表
const initList = () => {
  params.pageSize = 10
  params.total = 0
  listData.value = []
  reset()
}

// 获取事件数量
const getEventsCount = async () => {
  const res = await getEventList({ pageNo: 1, pageSize: 1 })
  trafficStore.setEventCount(res.total)
}

// 实时事件数量
const eventsCount = computed(() => {
  return trafficStore.getEventCount > 99 ? '99+' : trafficStore.getEventCount
})

// 打开实时事件抽屉弹窗
const openRealTimeEvents = () => {
  drawerShow.value = !drawerShow.value
  if (drawerShow.value) {
    initList()
  }
}

// 关闭实时事件抽屉弹窗
const closeRealTimeEvents = () => {
  drawerShow.value = false
}

const notificationRef = ref<any>(null)
// 右下角事件通知
const triggerEventNotify = (item) => {
  notificationRef.value = ElNotification({
    // title: 'Title',
    position: 'bottom-right',
    icon: h(Icon, { icon: 'ep:warn-triangle-filled', size: 25, color: '#FF5151' }),
    duration: 10000,
    appendTo: document.getElementsByClassName('home')[0] as HTMLElement,
    customClass: 'event-notify',
    message: h('div', { class: 'content' }, [
      h('div', { class: 'title' }, [
        h('span', null, `【${typeCompute(item).nameStr}】`),
        h('span', { class: 'time' }, item.eventStartTime.slice(5, -3))
      ]),
      h(
        'div',
        { class: 'text ellipsis' },
        carPlateStr(item.eventCarPlate) + ' ' + item.eventSituation
      ),
      h('div', { class: 'foot' }, [
        h('div', { class: `status-${item.eventStatus}` }, STATUS_MAP[item.eventStatus]),
        h('div', { class: 'btn-block' }, [
          h('span', { class: 'btn', onClick: () => goToEvent(item.id) }, '事件详情'),
          h('span', { class: 'btn-red', onClick: () => goEventDetail(item.id, true) }, '处置')
        ])
      ])
    ])
  })
  trafficStore.setEventNotify(null)
}

// 关闭通知
const closeNotification = () => {
  if (notificationRef.value) {
    notificationRef.value.close()
    notificationRef.value = null
  }
}

// 触发事件通知
watch(
  () => trafficStore.getEventNotify,
  (e) => {
    if (e) {
      triggerEventNotify(e)
    }
  },
  { immediate: true, deep: true }
)

onBeforeMount(() => {
  getEventsCount()
})

defineExpose({
  initList,
  search
})
</script>
<style lang="scss" scoped>
.full-block {
  top: 0 !important;
  left: 0;
  z-index: 7 !important;
  width: 100%;
  height: 100%;
}
.realTime-block {
  position: fixed;
  right: 0;
  top: 122px;
  z-index: 5;
  font-family: PingFang SC;
  font-size: 18px;
  font-weight: 600;
  line-height: 22px;
  text-align: center;
  letter-spacing: 0px;
  color: #ffffff;
  display: flex;

  .mask {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }

  .realTime-content {
    position: absolute;
    right: 0;
    top: 122px;
  }

  .realTime-btn-block {
    margin-top: 16px;
    width: 36px;
    height: 140px;
    border-radius: 6px 0px 0px 6px;
    background: #0f81c9;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    padding: 12px 7px;
    box-sizing: border-box;
    cursor: pointer;

    .num-block {
      width: 32px;
      height: 20px;
      border-radius: 13px;
      background: #ff5151;
      font-family: DIN Alternate;
      font-size: 14px;
      line-height: 14px;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 1px 0px;
    }
  }

  .list-block {
    width: 0;
    overflow: hidden;
    visibility: hidden;
    transition: all 0.5s;
    &.action {
      visibility: visible;
      width: 400px;
    }

    .realTimeEvents {
      width: 400px;
      //   height: 958px;
      background: rgba(4, 27, 79, 0.75);
      padding: 12px 16px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;

      .search-block {
        .inp-block {
          margin-bottom: 12px;
          display: flex;
          align-items: center;
          .i-name {
            width: 70px;
            font-family: PingFang SC;
            font-size: 14px;
            font-weight: normal;
            text-align: left;
            line-height: 22px;
            letter-spacing: 0em;
            color: rgba(240, 245, 255, 0.95);
          }
          .i-content {
            flex: 1;

            :deep(.el-input__wrapper) {
              background-color: transparent;
              box-shadow: none;
              border: none;
            }

            .x-inp {
              border-radius: 4px;
              background-color: rgba(23, 42, 69, 0.6);
              box-sizing: border-box;
              border: 1px solid #2d5479;
            }
          }
        }

        .btns {
          display: flex;
          justify-content: flex-end;
          align-items: center;
          font-size: 16px;
          font-weight: normal;
          line-height: 24px;
          letter-spacing: 0px;
          color: rgba(255, 255, 255, 0.85);
          margin-bottom: 10px;
          .search-btn,
          .reset-btn {
            cursor: pointer;
            width: 54px;
            height: 28px;
            border-radius: 2px;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 4px 8px;
            box-sizing: border-box;
            border: 1px solid rgba(255, 255, 255, 0.4);
          }
          .search-btn {
            background: #1270ff;
            margin-left: 8px;
          }
        }
      }

      .scrollbar-block {
        flex: 1;
        .list-item {
          height: 136px;
          display: flex;
          justify-content: space-between;
          padding: 12px 16px;
          font-size: 16px;
          font-weight: normal;
          line-height: 24px;
          letter-spacing: 0px;
          text-align: left;
          color: #ffffff;
          background: #1b4f8f;
          box-sizing: border-box;
          border-radius: 8px;
          margin-bottom: 16px;
          &:last-child {
            margin-bottom: 0;
          }

          .content {
            margin-left: 12px;
            flex: 1;
            .title {
              margin-left: -6px;
              font-size: 18px;
              font-weight: 600;
              .time {
                margin-left: 10px;
              }
            }

            .text {
              margin: 8px 0;
            }

            .foot {
              font-size: 14px;
              line-height: 22px;
              display: flex;
              justify-content: space-between;
              align-items: center;

              .status-0,
              .status-1,
              .status-2 {
                display: flex;
                align-items: center;
                &::before {
                  content: '';
                  width: 10px;
                  height: 10px;
                  border-radius: 10px;
                  margin-right: 4px;
                }
              }
              .status-0,
              .status-3 {
                color: #e6a23c;
                &::before {
                  background: #e6a23c;
                }
              }
              .status-1 {
                color: #70a9ff;
                &::before {
                  background: #70a9ff;
                }
              }
              .status-2 {
                color: #67c23a;
                &::before {
                  background: #67c23a;
                }
              }

              .btn-block {
                display: flex;
                align-items: center;
                .btn,
                .btn-red {
                  padding: 1px 8px;
                  box-sizing: border-box;
                  border: 1px solid rgba(255, 255, 255, 0.4);
                  border-radius: 2px;
                  cursor: pointer;
                }
                .btn-red {
                  background: #f56c6c;
                  border: 1px solid rgba(255, 108, 108, 0.4);
                  margin-left: 8px;
                }
                .mg-l {
                  margin-left: 8px;
                }
              }
            }
          }
        }
        .empty {
          text-align: center;
          color: #fff;
          font-size: 14px;
          line-height: 22px;
          margin-top: 20px;
        }
      }
      .pagination {
        margin-top: 10px;
        display: flex;
        justify-content: center;
        :deep(.btn-prev),
        :deep(.btn-next),
        :deep(.el-pager li),
        :deep(.el-pagination__total) {
          background-color: transparent;
          color: #fff;
        }
        :deep(.el-pager .is-active) {
          background-color: #409eff;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.realTimeEvents {
  .el-date-editor {
    width: 100%;
    height: 34px;
    background-color: rgba(23, 42, 69, 0.6) !important;
    border: 1px solid #2d5479 !important;
    border-radius: 4px !important;
    box-sizing: border-box;

    .el-range-input {
      background: transparent;
      color: #fff;
    }

    .el-range-separator {
      color: rgba(240, 245, 255, 0.95);
    }

    .el-range__close-icon {
      color: rgba(240, 245, 255, 0.95);
    }
  }
}
.event-notify {
  border-radius: 8px;
  background: #1b4f8f;
  box-sizing: border-box;
  border: 0px solid #5499cf;
  width: 368px;
  height: 136px;
  box-sizing: border-box;
  padding: 12px 16px;

  .el-notification__group {
    margin-left: 12px;
    margin-right: 0;
  }

  .el-notification__closeBtn {
    color: #fff;
  }

  .content {
    font-family: PingFang SC;
    font-size: 16px;
    font-weight: normal;
    line-height: 24px;
    letter-spacing: 0px;
    color: #ffffff;

    .title {
      margin-left: -6px;
      font-size: 18px;
      font-weight: 600;
      .time {
        margin-left: 10px;
      }
    }

    .text {
      margin: 8px 0;
    }

    .foot {
      font-size: 14px;
      line-height: 22px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .status-0,
      .status-1,
      .status-2 {
        display: flex;
        align-items: center;
        &::before {
          content: '';
          width: 10px;
          height: 10px;
          border-radius: 10px;
          margin-right: 4px;
        }
      }
      .status-0,
      .status-3 {
        color: #e6a23c;
        &::before {
          background: #e6a23c;
        }
      }
      .status-1 {
        color: #70a9ff;
        &::before {
          background: #70a9ff;
        }
      }
      .status-2 {
        color: #67c23a;
        &::before {
          background: #67c23a;
        }
      }

      .btn-block {
        display: flex;
        align-items: center;
        .btn,
        .btn-red {
          cursor: pointer;
          padding: 1px 8px;
          box-sizing: border-box;
          border: 1px solid rgba(255, 255, 255, 0.4);
          border-radius: 2px;
        }
        .btn-red {
          background: #f56c6c;
          border: 1px solid rgba(255, 108, 108, 0.4);
          margin-left: 8px;
        }
      }
    }
  }
}

.ellipsis {
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 显示的行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
