<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.milestoneStr }}</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-if="eventHisResp.cameraIndexCode"
                v-bind="{
                  frameW: 220,
                  frameH: 148,
                  vcode: eventHisResp.cameraIndexCode,
                  pileNumber: ''
                }"
              />
            </div>
          </div>
          <div class="video-item">
            <span>报警回放视频</span>
            <div class="video">
              <video
                v-if="eventHisResp.videoPath"
                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
                ref="imageSomeRef"
                :images="eventHisResp.eventImagesPath"
                @current-change="handleChange"
              />
              <div class="img-indicator">
                <span>({{ activeIndex }} / {{ eventHisResp.eventImagesPath.length }})</span>
                <div class="img-btn">
                  <span @click="prevImg">上一张</span>
                  <span @click="nextImg">下一张</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 关联车辆 -->
      <div class="content-block" v-if="!alertInfo.nonVehicleFlag">
        <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"
        v-if="!disabled || (disabled && ![0, 3].includes(alertInfo.eventStatus))"
      >
        <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"
              :maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>

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

    <template #footer>
      <div class="footer" v-if="!disabled && [0, 3].includes(alertInfo.eventStatus)">
        <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 ImageSome from './components/ImageSome.vue'
import CarCard from './components/CarCard.vue'
import { EVENT_TYPES } from '@/config/dict'
import { useRouter } from 'vue-router'
import { useUserStoreWithOut } from '@/store/modules/user'
import { ElLoading } from 'element-plus'

const userStore = useUserStoreWithOut()

const isShow = ref<boolean>(false)
const alertInfo = ref<any>({})
const eventHisResp = ref<any>({})
const handleType = ref<number>(1)
const disabled = ref<boolean>(false)
const activeIndex = ref<number>(1)
const imageSomeRef = ref<InstanceType<typeof ImageSome> | null>(null)

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

const loading = ref<boolean>(false)

const router = useRouter()

const emits = defineEmits(['update'])

const carList = computed(() => {
  const { carInfoList, direction, milestone } = alertInfo.value
  if (!carInfoList) return []
  return carInfoList.map((t) => {
    return {
      carId: t.carId,
      carImageUrl: t.carImageUrl,
      direction: direction,
      inTunnelTime: t.inTunnelTimeStr,
      retainedMinutesTime: t.retainedMinutesTime,
      speed: t.speed?.toFixed(2) || 0,
      carMilestone: milestone,
      type: t.vehicleType,
      carPlate: t.carPlate,
      isFocusMark: t.isFocusMark,
      isDangerous: t.isDangerous,
      isDriveTunnel: t.isDriveTunnel
    }
  })
})

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, nonVehicleFlag } = row

  if (nonVehicleFlag) {
    return {
      classStr: 'type-3',
      nameStr: EVENT_MAP[eventType]
    }
  }

  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 handleChange = (index: number) => {
  activeIndex.value = index + 1
}

const prevImg = () => {
  if (activeIndex.value > 1) {
    imageSomeRef.value?.prevImg()
  }
}

const nextImg = () => {
  if (activeIndex.value < eventHisResp.value.eventImagesPath.length) {
    imageSomeRef.value?.nextImg()
  }
}

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

const open = async (info) => {
  disabled.value = info.disabled || false
  params.id = info.id
  params.dispelCause = ''
  params.processingOperationsName = userStore.getUser.nickname
  handleType.value = 1
  alertInfo.value = {}
  eventHisResp.value.eventImagesPath = []

  const loading = ElLoading.service({
    lock: true,
    text: '加载中。。。',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  await getDetail()

  loading.close()
  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) {
    if (!params.dispelCause) return ElMessage.warning('请先填写原因！')

    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, eventImagesPath: eventHisRespVO.eventImagesPath || [] }
}

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: 24px;
      margin-right: 48px;
      padding: 0 6px;
    }
  }

  .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;
            position: relative;

            .img-indicator {
              position: absolute;
              bottom: -24px;
              left: 0;
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: space-between;
              font-size: 14px;
              color: #fff;
              .img-btn {
                display: flex;
                align-items: center;
                justify-content: center;
                color: #00ddff;
                span {
                  margin-left: 16px;
                  cursor: pointer;
                }
              }
            }
          }
        }
      }

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

  .footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 8px;
    color: #fff;
    font-size: 16px;
    .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;
    }
  }

  .ellipsis {
    display: -webkit-box;
    -webkit-line-clamp: 2; /* 显示的行数 */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</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);
    }
    .el-input__count {
      background: transparent;
    }
  }
}
</style>
