<template>
  <el-dialog v-model="isShow" width="740" class="event-alert-dialog" :align-center="true">
    <template #header>
      <div class="header">
        事件告警
        <span class="btn" @click="goToEvent">详情</span>
      </div>
    </template>

    <div class="container">
      <!-- 告警内容 -->
      <div class="content-block">
        <div class="title"> 告警内容 </div>
        <div class="info">
          <span>事件类型：{{ typeCompute(alertInfo).nameStr }}</span>
          <span>事件时间：{{ alertInfo.eventStartTime }}</span>
          <span>事件地点：{{ alertInfo.milestone }}</span>
        </div>
      </div>

      <!-- 报警视频图片 -->
      <div class="content-block">
        <div class="title"> 报警视频图片 </div>
        <div class="video-block">
          <div class="video-item">
            <span>实时视频</span>
            <div class="video">
              <VideoPlayer
                v-bind="{
                  frameW: 220,
                  frameH: 148,
                  vcode: eventHisResp.cameraIndexCode,
                  pileNumber: ''
                }"
              />
            </div>
          </div>
          <div class="video-item">
            <span>报警回放视频</span>
            <div class="video">
              <video
                ref="videoRef"
                :src="eventHisResp.videoPath"
                :controls="true"
                autoPlay
                width="100%"
                height="100%"
              >
              </video>
            </div>
          </div>
          <div class="video-item">
            <span>报警图片</span>
            <div class="video">
              <ImageSome :images="eventHisResp.eventImagesPath" />
            </div>
          </div>
        </div>
      </div>

      <!-- 关联车辆 -->
      <div class="content-block">
        <div class="title"> 关联车辆（{{ carList.length }}） </div>
        <el-scrollbar>
          <div class="car-block">
            <CarCard v-for="car in carList" :key="car.id" :carInfo="car" />
          </div>
        </el-scrollbar>
      </div>

      <!-- 事件处置 -->
      <div class="content-block">
        <div class="title"> 事件处置 </div>

        <el-form :label-width="100" v-if="[0, 3].includes(alertInfo.eventStatus)">
          <el-form-item required label="处置方式：">
            <el-radio-group v-model="handleType">
              <el-radio :value="1">上报事件</el-radio>
              <el-radio :value="2">消除事件</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="handleType === 2" required label="原因：">
            <el-input
              v-model="params.dispelCause"
              placeholder="请输入"
              :rows="5"
              resize="none"
              type="textarea"
            />
          </el-form-item>
        </el-form>

        <div class="info mg-b" v-else>
          <span>处置记录：{{ alertInfo.processingTime }}</span>
          <span>处置人：{{ alertInfo.processingOperationsName }}</span>
          <span>处置方式：{{ formatHandleType(alertInfo) }}</span>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="footer">
        <div class="cancel-btn" @click="isShow = false">取消</div>
        <div class="confirm-btn" v-loading="loading" @click="onSubmit">确定</div>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { cancelEvent, postEvent } from '@/api/event'
import { getEventDetail } from '@/api/home'
import VideoPlayer from '@/views/components/VideoPlayer/index.vue'
import ImageSome from '@/components/ImageSome/index.vue'
import CarCard from './components/CarCard.vue'
import { EVENT_TYPES } from '@/config/dict'
import { useRouter } from 'vue-router'
import { useUserStoreWithOut } from '@/store/modules/user'

const userStore = useUserStoreWithOut()

const carList = ref<any[]>([
  {
    carId: 'MEGCAM-90G-LS22033162-2016040732-92486',
    direction: 1,
    inTunnelTime: '2023-04-07 10:00:00',
    retainedMinutesTime: 10,
    speed: 60,
    carMilestone: 1000,
    type: 1,
    carPlate: '粤B12345',
    isFocusMark: true,
    isDangerous: false
  },
  {
    carId: 'MEGCAM-90G-LS22033162-2016040732-92486',
    direction: 1,
    inTunnelTime: '2023-04-07 10:00:00',
    retainedMinutesTime: 10,
    speed: 60,
    carMilestone: 1000,
    type: 1,
    carPlate: '粤B12345',
    isFocusMark: true,
    isDangerous: false
  },
  {
    carId: 'MEGCAM-90G-LS22033162-2016040732-92486',
    direction: 1,
    inTunnelTime: '2023-04-07 10:00:00',
    retainedMinutesTime: 0,
    speed: 60,
    carMilestone: 1000,
    type: 1,
    carPlate: '粤B12345',
    isFocusMark: true,
    isDangerous: false
  }
])
const isShow = ref<boolean>(false)
const alertInfo = ref<any>({})
const eventHisResp = ref<any>({})
const handleType = ref<number>(1)

const params = reactive<any>({
  id: '',
  dispelCause: '',
  processingOperationsName: ''
})

const loading = ref<boolean>(false)

const router = useRouter()

const emits = defineEmits(['update'])

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

// 状态计算
const typeCompute = (row: any) => {
  if (!row || Object.keys(row).length === 0) return { classStr: '', nameStr: '' }

  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 formatHandleType = (row: any) => {
  if (!row || Object.keys(row).length === 0) return ''

  const { processingType, dispelCause } = row

  if (+processingType === 1) {
    return '上报事件'
  }

  if (+processingType === 2) {
    return `消除事件${dispelCause ? `（${dispelCause}）` : ''}`
  }

  return ''
}

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

const open = async (id: string) => {
  params.id = id
  params.dispelCause = ''
  params.processingOperationsName = userStore.getUser.nickname
  handleType.value = 1
  alertInfo.value = {}
  eventHisResp.value = {}
  await getDetail()
  isShow.value = true
}

const onSubmit = () => {
  if (loading.value) return

  if (![0, 3].includes(alertInfo.value.eventStatus)) {
    isShow.value = false
    emits('update')
    return
  }

  // 上报事件
  if (handleType.value === 1) {
    loading.value = true
    postEvent(params)
      .then(() => {
        isShow.value = false
        ElMessage.success('操作成功！')
        emits('update', true)
      })
      .finally(() => {
        loading.value = false
      })
  }

  // 消除事件
  if (handleType.value === 2) {
    loading.value = true
    cancelEvent(params)
      .then((res) => {
        if (res) {
          isShow.value = false
          ElMessage.success('操作成功！')
          emits('update', true)
        }
      })
      .finally(() => {
        loading.value = false
      })
  }
}

// 获取详情
const getDetail = async () => {
  const res = await getEventDetail({ id: params.id })
  const { eventDetailRespVO, eventHisRespVO } = res
  alertInfo.value = eventDetailRespVO
  eventHisResp.value = eventHisRespVO
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.event-alert-dialog {
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #fff;
    font-size: 20px;
    font-weight: 600;
    line-height: 24px;
    letter-spacing: 0em;
    .btn {
      cursor: pointer;
      width: 56px;
      height: 24px;
      border-radius: 4px;
      box-sizing: border-box;
      border: 1px solid #ffffff;
      font-size: 14px;
      font-weight: normal;
      text-align: center;
      line-height: 22px;
      margin-right: 48px;
    }
  }

  .container {
    padding: 0px 8px;
    box-sizing: border-box;
    font-family: PingFang SC;
    font-size: 16px;
    font-weight: normal;
    line-height: 24px;
    letter-spacing: 0em;
    color: #ffffff;

    .content-block {
      margin-top: 24px;
      .title {
        font-size: 18px;
        font-weight: 600;
        line-height: 28px;
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        &::before {
          content: '';
          display: inline-block;
          width: 4px;
          height: 20px;
          border-radius: 2px;
          background: #00ddff;
          margin-right: 8px;
        }
      }

      .info {
        display: flex;
        flex-wrap: wrap;
        span {
          width: 50%;
          margin-bottom: 8px;
          &:last-child {
            width: 100%;
            margin-bottom: 0px;
          }
        }
      }
      .mg-b {
        margin-bottom: 24px;
      }

      .video-block {
        display: flex;
        justify-content: space-between;
        .video-item {
          width: 220px;
          padding-bottom: 12px;
          .video {
            margin-top: 8px;
            height: 148px;
            background-color: black;
          }
        }
      }

      .car-block {
        display: flex;
        padding-bottom: 14px;
      }
    }
  }

  .footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 8px;
    color: #fff;
    .cancel-btn,
    .confirm-btn {
      cursor: pointer;
      width: 70px;
      height: 32px;
      border-radius: 2px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 4px 16px;
      box-sizing: border-box;
      border: 1px solid rgba(255, 255, 255, 0.4);
    }
    .confirm-btn {
      background: #1270ff;
      margin-left: 16px;
    }
  }
}
</style>

<style lang="scss">
.event-alert-dialog {
  padding: 16px 16px 10px 16px;
  background: #1b4f8f;
  min-height: 800px;
  box-sizing: border-box;
  --el-text-color-regular: white;

  .el-dialog__header {
    padding: 0;

    .el-dialog__headerbtn .el-dialog__close {
      color: #fff;
      font-size: 18px;
    }
  }

  .el-dialog__footer {
    padding-top: 0;
  }

  .el-textarea {
    .el-textarea__inner {
      border-radius: 0;
      background: transparent;
      box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.2);
    }
  }
}
</style>
