<template>
  <div class="preview-info">
    <a-button
      type="primary"
      style="margin-right: 15px"
      size="mini"
      @click="emits('handleBack')"
    >
      <template #icon>
        <icon-arrow-left />
      </template>
    </a-button>
    <Breadcrumb :items="['menu.previewList.basic', 'menu.previewInfo.basic']" />
    <a-card class="general-card" :body-style="{ height: '100%', padding: '0' }">
      <a-space direction="vertical" fill>
        <div class="preview-info-main">
          <div class="video-box-qj">
            <div class="video-box-wrapper">
              <div v-if="!workerObj.qj" class="video-box-tip"
                ><span>{{ $t('previewList.wxh') }}</span></div
              >
              <a-spin v-if="qjLoading" dot />
              <canvas
                id="video-canvas-qj"
                v-doubleClick="cropFullInfo"
                :style="{
                  width: '100%',
                  // transform: `rotateZ(${cropFullInfo.Rotate}deg)`,
                }"
              ></canvas>
            </div>
          </div>
          <div class="video-right-content">
            <div class="video-right-content-tools">
              <!-- 截图 录像 -->
              <a-tooltip
                v-for="tool in tools"
                :key="tool.type"
                :content="tool.title"
              >
                <a-button @click="toolsClick(tool)">
                  <template #icon>
                    <Icon
                      :icon="tool.icon"
                      :color="tool.color"
                      :class="[tool.iconClass]"
                      width="24"
                      height="24"
                    />
                  </template>
                </a-button>
              </a-tooltip>
              <!-- 喊话 -->
              <a-popover
                title=""
                trigger="click"
                position="top"
                :content-style="{ padding: '0 15px' }"
              >
                <a-button>
                  <template #icon>
                    <Icon icon="ri:speak-line" width="22" height="22" />
                  </template>
                </a-button>
                <template #content>
                  <Speech :data="data" />
                </template>
              </a-popover>
              <!-- 对讲 -->
              <a-tooltip :content="$t('previewList.dj')">
                <a-button
                  :disabled="intercomDisabled === 'loading'"
                  @click="intercomClick"
                >
                  <template #icon>
                    <Icon
                      v-if="intercomDisabled === 'close'"
                      icon="material-symbols:record-voice-over-outline"
                      width="22"
                      height="22"
                    />
                    <Icon
                      v-else-if="intercomDisabled === 'loading'"
                      icon="eos-icons:three-dots-loading"
                      width="22"
                      height="22"
                    />
                    <Icon
                      v-else
                      class="fade-open"
                      icon="icon-park-outline:voice"
                      width="22"
                      height="22"
                      color="red"
                    />
                  </template>
                </a-button>
              </a-tooltip>
              <!-- 分屏 -->
              <a-dropdown @select="handleRadioChange">
                <a-tooltip :content="$t('previewList.fp')">
                  <a-button>
                    <template #icon>
                      <Icon icon="carbon:split-screen" width="20" height="20" />
                    </template>
                  </a-button>
                </a-tooltip>

                <template #content>
                  <a-doption
                    v-for="item in btnList"
                    :key="item.label"
                    :value="item.value"
                  >
                    <template #default>{{ item.label }}</template>
                  </a-doption>
                </template>
              </a-dropdown>
            </div>
            <div class="split-screen-main">
              <div class="split-screen-box">
                <a-grid
                  class="grid-demo-grid"
                  :cols="gridCount"
                  :col-gap="2"
                  :row-gap="2"
                >
                  <a-grid-item
                    v-for="(item, i) in radioActive"
                    :key="item + '' + i"
                    @click="handleScreen(i)"
                  >
                    <div
                      class="video-box"
                      :class="[
                        'demo-item',
                        screenActive === i ? 'screen-active' : '',
                      ]"
                      @mouseleave="handleMouseLeave(i)"
                      @mouseenter="handleMouseEnter(i)"
                      @dblclick="handleDoubleClick(i)"
                    >
                      <a-spin v-if="activeObj[i]?.loading" dot />
                      <div v-if="!activeObj[i]?.workerObj" class="video-box-tip"
                        ><span>{{ t('previewList.wxh') }}</span></div
                      >
                      <div v-if="activeObj[i]?.isCloseBtn" class="video-tools">
                        <!-- 截图 录像 -->
                        <a-tooltip
                          v-for="tool in activeObj[i]?.tools"
                          :key="tool.type"
                          :content="tool.title"
                        >
                          <a-button
                            type="text"
                            size="mini"
                            @click="partToolsClick(tool, activeObj[i])"
                          >
                            <template #icon>
                              <Icon
                                :icon="tool.icon"
                                :color="tool.color"
                                :class="[tool.iconClass]"
                                width="24"
                                height="24"
                              />
                            </template>
                          </a-button>
                        </a-tooltip>
                        <!-- 关闭 -->
                        <a-tooltip :content="$t('previewList.close')">
                          <a-button
                            v-if="i != 0"
                            type="text"
                            size="mini"
                            @click="handleClose(i)"
                          >
                            <template #icon>
                              <Icon
                                icon="mdi:shutdown"
                                width="24"
                                height="24"
                              />
                            </template>
                          </a-button>
                        </a-tooltip>
                        <!-- 对讲 -->
                        <!-- <a-tooltip :content="$t('previewList.close')">
                          <a-button
                            v-if="activeObj[i].isCloseBtn"
                            type="text"
                            size="mini"
                            @click="handleClose(i)"
                          >
                            <Icon
                              icon="material-symbols:record-voice-over-outline"
                              width="24"
                              height="24"
                            />
                          </a-button>
                        </a-tooltip> -->
                      </div>
                      <canvas
                        v-if="activeObj[i]?.isReset"
                        :id="'video-canvas-part' + i"
                        :style="{
                          width: '100%',
                          height: '100%',
                          // transform: `rotateZ(${cropFullInfo.Rotate}deg)`,
                        }"
                      ></canvas>
                    </div>
                  </a-grid-item>
                </a-grid>
              </div>
            </div>
            <div class="alarm-box">
              <a-table
                :columns="alarmColumns"
                :data="alarmData"
                :scroll="{ y: '100%' }"
                :pagination="false"
                :bordered="{ cell: true }"
                :loading="alarmLoading"
                size="small"
                style="height: 100%"
              >
                <template #columns>
                  <a-table-column
                    :title="t('previewList.bjlx')"
                    data-index="type"
                  >
                  </a-table-column>
                  <a-table-column
                    :title="t('previewList.bjsj')"
                    data-index="timeN"
                    :width="180"
                  >
                  </a-table-column>
                  <!-- <a-table-column
                    :title="t('previewList.status')"
                    data-index="status"
                    :width="150"
                    :body-cell-style="
                      (record) => ({
                        background: record.status ? '' : '#7e2d2d',
                      })
                    "
                  >
                    <template #cell="{ record }">
                      <span>{{
                        record.status
                          ? t('previewList.ycl')
                          : t('previewList.wcl')
                      }}</span>
                    </template>
                  </a-table-column> -->
                  <!-- <a-table-column
                    :title="t('previewList.dqstatus')"
                    data-index="isRead"
                    :width="150"
                    :body-cell-style="
                      (record) => ({
                        background: record.isRead ? '' : '#2d4f7e',
                      })
                    "
                  >
                    <template #cell="{ record }">
                      <span>{{
                        record.isRead
                          ? t('previewList.yd')
                          : t('previewList.wd')
                      }}</span>
                    </template>
                  </a-table-column> -->
                  <a-table-column :title="t('previewList.cz')" :width="150">
                    <template #cell="{ record }">
                      <a-button
                        type="text"
                        size="mini"
                        :loading="record.loading"
                        @click="showView(record)"
                        >{{ t('previewList.ck') }}</a-button
                      >
                    </template>
                    <template #title>
                      <span>{{ t('previewList.cz') }}</span>
                      <a-tooltip :content="$t('previewList.ckqb')">
                        <a-button
                          type="text"
                          size="mini"
                          style="position: absolute; right: 8px"
                          @click="modalRef.open()"
                        >
                          <template #icon>
                            <Icon icon="gg:view-list" width="22" height="22" />
                          </template>
                        </a-button>
                      </a-tooltip>
                      <!-- <a-tooltip :content="$t('previewList.tip1')">
                        <a-button
                          type="text"
                          size="mini"
                          style="position: absolute; right: 8px"
                          @click="
                            () =>
                              alarmData.forEach((item) => (item.isRead = true))
                          "
                        >
                          <template #icon>
                            <a-badge
                              dot
                              color="#FFB400"
                              :count="alarmData.filter((v) => !v.isRead).length"
                            >
                              <Icon
                                icon="ant-design:clear-outlined"
                                width="20"
                                height="20"
                              />
                            </a-badge>
                          </template>
                        </a-button>
                      </a-tooltip> -->
                    </template>
                  </a-table-column>
                </template>
              </a-table>
            </div>
          </div>
        </div>
      </a-space>
    </a-card>
    <PubModal
      ref="modalRef"
      :title="$t('previewList.bjlb')"
      :fullscreen="true"
      :closable="true"
    >
      <AlarmAll :guid="data.id" :is-show-cl="isShowCl" />
    </PubModal>
    <ViewDrawer
      ref="viewDrawerRef"
      v-model:view-data="viewData"
      :guid="data.id"
      :is-show-cl="false"
    />
  </div>
</template>

<script setup lang="ts">
  import useWorker from '@/assets/js/video-lib/omnimatrix-video-player';
  import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
  import { IntercomFn } from '@/utils/Intercom';
  import { useI18n } from 'vue-i18n';
  import { Icon } from '@iconify/vue';
  import { getCropFullInfo } from '@/api/system';
  import { useAppStore } from '@/store';
  import dayjs from 'dayjs';
  import { Message } from '@arco-design/web-vue';
  import useWheel from '@/assets/js/useWheel';
  import Speech from '../components/speech.vue';
  import AlarmAll from '../components/alarm-all.vue';
  import PubModal from '../components/pub-modal.vue';
  import ViewDrawer from '../components/view-drawer.vue';

  const { t } = useI18n();
  interface IBtn {
    label: string;
    value: number;
  }
  interface AlarmData {
    [key: string]: number | string | boolean;
  }
  const app = useAppStore();

  const viewData = ref<AlarmData>({});
  const isShowCl = ref(false);
  const modalRef = ref();
  const workerObj: any = ref({ qj: null });
  const cropFullInfo = ref<{
    H: number;
    Rotate: number;
    W: number;
    X: number;
    Y: number;
  }>({ H: 0, Rotate: 0, W: 0, X: 0, Y: 0 });
  const emits = defineEmits(['handleBack']);
  const props = defineProps<{
    data: any;
  }>();
  const qjLoading = ref(false);
  const radioActive = ref<number>(2);
  const screenActive = ref<number>(1);

  const btnList = computed<IBtn[]>(() => [
    {
      label: t('previewList.dp'),
      value: 1,
    },
    {
      label: t('previewList.efp'),
      value: 2,
    },
    {
      label: t('previewList.sfp'),
      value: 4,
    },
    {
      label: t('previewList.jfp'),
      value: 9,
    },
    // {
    //   label: t('previewList.slfp'),
    //   value: 16,
    // },
  ]);
  const tools = ref([
    {
      icon: 'ri:screenshot-2-line',
      title: t('previewList.jt'),
      type: 'jt',
      color: '#fff',
      iconClass: '',
    },
    {
      icon: 'bx:video-recording',
      title: t('previewList.lx'),
      type: 'lx',
      color: '#fff',
      iconClass: '',
    },
  ]);
  const state = ref(false);
  const toolsClick = (tool: any) => {
    if (!workerObj.value.qj) return;
    switch (tool.type) {
      case 'lx':
        state.value = !state.value;
        tool.icon = state.value ? 'fad:armrecording' : 'bx:video-recording';
        tool.color = state.value ? 'red' : '#fff';
        tool.iconClass = state.value ? 'fade-open' : '';
        workerObj.value.qj.WebSocketWork.postMessage({
          type: 'lx',
          lx: state.value,
        });
        break;
      case 'jt':
        workerObj.value.qj.worker.postMessage({ type: 'jt' });
        break;
      default:
        break;
    }
  };
  const partToolsClick = (tool: any, ao: any) => {
    if (!ao.workerObj) return;
    switch (tool.type) {
      case 'lx':
        state.value = !state.value;
        tool.icon = state.value ? 'fad:armrecording' : 'bx:video-recording';
        tool.color = state.value ? 'red' : '#8ac5ff';
        tool.iconClass = state.value ? '.fade-open' : '';
        ao.workerObj.WebSocketWork.postMessage({
          type: 'lx',
          lx: state.value,
        });
        break;
      case 'jt':
        ao.workerObj.worker.postMessage({ type: 'jt' });
        break;
      default:
        break;
    }
  };
  const gridCount = computed<number>(() => {
    let result = 4;
    switch (radioActive.value) {
      case 2:
        result = 2;
        break;
      case 4:
        result = 2;
        break;
      case 9:
        result = 3;
        break;
      // case 16:
      //   result = 4;
      //   break;
      default:
        result = 1;
        break;
    }
    return result;
  });
  const activeObj = ref<
    {
      loading: boolean;
      isSignal: boolean;
      [key: string]: any;
    }[]
  >([
    {
      loading: false,
      isSignal: false,
      workerObj: null,
      isCloseBtn: false,
      isReset: false,
      tools: ref(tools.value.map((v) => ({ ...v, color: '#8ac5ff' }))),
    },
  ]);
  const alarmColumns = [
    {
      title: t('previewList.bjlx'),
      dataIndex: 'type',
    },
    {
      title: t('previewList.status'),
      dataIndex: 'status',
      width: 150,
    },
  ];
  const alarmLoading = ref(false);
  const alarmData = ref<{ [key: string]: number | string | boolean }[]>([
    // {
    //   type: '行人闯入',
    //   status: 0,
    //   isRead: false,
    // },
  ]);
  const handleClose = async (v: number): Promise<void> => {
    if (activeObj?.value[v]?.workerObj) {
      return new Promise((resolve) => {
        activeObj.value[v].isReset = false;
        activeObj.value[v].loading = false;
        activeObj.value[v].workerObj.close();
        setTimeout(() => {
          activeObj.value[v].isSignal = false;
          activeObj.value[v].workerObj = null;
          resolve();
        }, 50);
      });
    }
    return undefined;
  };
  const handleRadioChange = (
    v: string | number | Record<string, any> | undefined
  ) => {
    radioActive.value = typeof v === 'number' ? v : 2;
    if (typeof v === 'number') {
      screenActive.value = 1;
      // eslint-disable-next-line no-plusplus
      for (let i = 1; i < v; i++) {
        handleClose(i);
      }
    }
  };
  const handleScreen = (i: number) => {
    if (!i) return;
    screenActive.value = i;
  };
  const handleMouseEnter = (v: number) => {
    activeObj.value[v].isCloseBtn = true;
  };
  const handleMouseLeave = (v: number) => {
    activeObj.value[v].isCloseBtn = false;
  };

  let parent: any = null;
  const handleDoubleClick = (i: number) => {
    const el = document.querySelectorAll('.video-box')[i];
    const fullscreenDom: HTMLElement | null = document.querySelector(
      '#video-box-fullscreen>div'
    );
    if (fullscreenDom) {
      parent?.appendChild(fullscreenDom);
      const box = document.querySelector('#video-box-fullscreen');
      if (box) {
        document.body.removeChild(box);
      }
    } else {
      parent = el?.parentElement;
      const div: HTMLElement = document.createElement('div');
      div.id = 'video-box-fullscreen';
      div.style.position = 'fixed';
      div.style.top = '0';
      div.style.left = '0';
      div.style.width = '100%';
      div.style.height = '100%';
      div.style.zIndex = '999';
      div.appendChild(el);

      document.body.appendChild(div);
    }
    // toggle();
  };

  const intercomDisabled = ref<'open' | 'loading' | 'close'>('close');
  const intercomClick = () => {
    // (app.ip as string).split('//')[1]
    IntercomFn(intercomDisabled, props.data.id);
  };
  const viewDrawerRef = ref();
  const showView = (record: any) => {
    record.isRead = true;
    const alarmLog = [record];
    // AlgorithmName: '人员计数D';
    // CameraDeviceId: 21;
    // classId: 1;
    // h: 386;
    // isRead: true;
    // src: 'originPicture/20241218/20241218192906_180909_30_21_src.jpg?serverUUID=3f16a3b113234807b81f6f8d0f268232';
    // status: 0;
    // time: 1734521346;
    // timeN: '2024-12-18 19:29:06';
    // type: '人员计数D';
    // w: 680;
    // x: 1454;
    // y: 19;
    record.loading = true;
    const img = document.createElement('img');
    img.src = `${app.ip}/rpc/rabbitMQ/KunPengYun/Files/${record.src}&GUID=${props.data.id}`;
    img.onload = () => {
      const [w, h] = [img.width, img.height];
      const newAlarmData = alarmLog.map((item: any, i: number) => {
        return {
          ...item,
          Name: item.AlgorithmName,
          type: item.AlgorithmName,
          status: 0,
          isRead: false,
          img: img.src,
          tImg: img.src,
          imgJson: {
            imageHeight: h,
            imageWidth: w,
            resultData: {
              objectList: [
                {
                  rect: {
                    ...alarmLog[i],
                    width: alarmLog[i].w,
                    height: alarmLog[i].h,
                  },
                },
              ],
            },
          },
        };
      });
      const [firstAlarmData] = newAlarmData;
      viewData.value = firstAlarmData;
      viewDrawerRef.value.open();
      record.loading = false;
    };
  };
  watch(
    radioActive,
    (newV) => {
      activeObj.value = [activeObj.value[0]];
      // eslint-disable-next-line no-plusplus
      for (let i = 1; i < newV; i++) {
        activeObj.value.push({
          loading: false,
          isSignal: false,
          workerObj: null,
          isCloseBtn: false,
          isReset: false,
          tools: ref(tools.value.map((v) => ({ ...v, color: '#8ac5ff' }))),
        });
      }
    },
    { immediate: true }
  );
  watch(
    () => app.partObj,
    (newV: any) => {
      handleClose(screenActive.value).then(() => {
        ((active: number) => {
          let ao: any;
          let partVideoUrl;
          let className;
          if (newV.PartCenterX) {
            ao = activeObj.value[active];
            ao.loading = true;
            ao.isReset = true;
            partVideoUrl = `${app.ip}/VideoShow/Preview/Part/Main?GUID=${props.data.id}&X=${newV.PartCenterX}&Y=${newV.PartCenterY}`;
            className = `#video-canvas-part${active}`;
          } else {
            [ao] = activeObj.value;
            ao.loading = true;
            ao.isReset = true;
            partVideoUrl = `${app.ip}/VideoShow/Preview/Part/Main?GUID=${props.data.id}&X=0&Y=0`;
            className = `#video-canvas-part${0}`;
          }
          nextTick(() => {
            ao.workerObj = useWorker(partVideoUrl, className, null, () => {
              ao.loading = false;
              ao.isSignal = false;
              if (newV.PartCenterX) {
                useWheel(
                  document.querySelectorAll('.video-box')[active],
                  className
                );
              } else {
                useWheel(document.querySelectorAll('.video-box')[0], className);
              }
            });
          });
        })(screenActive.value);
      });
    },
    { deep: true, immediate: true }
  );

  let eventSource: EventSource;
  const alarmSSE = () => {
    if (!props.data.id) return;
    alarmLoading.value = true;
    eventSource = new EventSource(`${app.ip}/rpc/AiSSE?Topic=${props.data.id}`);
    eventSource.addEventListener(
      'open',
      () => {
        alarmData.value = [];
        alarmLoading.value = false;
      },
      false
    );
    eventSource.addEventListener(
      'message',
      (e) => {
        const data = JSON.parse(e.data);
        alarmData.value.unshift({
          type: data.AlgorithmName,
          status: 0,
          isRead: false,
          loading: false,
          timeN: dayjs(+`${data.time}`.padEnd(13, '0')).format(
            'YYYY-MM-DD HH:mm:ss'
          ),
          ...data,
        });
      },
      false
    );
    eventSource.addEventListener(
      'error',
      () => {
        Message.warning({
          content: t('previewList.tip2'),
          duration: 5 * 1000,
        });
      },
      false
    );
  };
  onMounted(() => {
    alarmSSE();
    getCropFullInfo({ GUID: props.data.id }).then((res) => {
      cropFullInfo.value = res.data;
      const videoUrl = `${app.ip}/VideoShow/Preview/Full/Main?GUID=${props.data.id}`;
      qjLoading.value = true;
      workerObj.value.qj = useWorker(videoUrl, `#video-canvas-qj`, null, () => {
        qjLoading.value = false;
      });
    });
  });
  onUnmounted(() => {
    handleClose(0);
    app.partObj = Object.assign(app.partObj as any, {
      PartCenterX: '',
      PartCenterY: '',
    });
    workerObj.value.qj?.close();
    workerObj.value.qj = null;
    eventSource?.close();
  });
</script>

<style scoped lang="scss">
  .preview-info {
    height: 100%;
    .general-card {
      height: calc(100% - 60px);
      :deep(.arco-space) {
        height: 100%;
        .arco-space-item {
          height: 100%;
        }
        .arco-grid-item {
          aspect-ratio: 16 / 9;
        }
      }
    }

    .split-screen-main {
      display: flex;
      flex-flow: column;
      gap: 15px;
      .alarm-box {
        flex: 1;
        min-height: 100px;
      }
    }
    .split-screen-box {
      height: 0;
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      & > div {
        height: 100%;
        // aspect-ratio: 16/9;
        width: 100%;
      }
      .arco-grid-item {
        position: relative;
      }
    }
    &-main {
      display: flex;
      height: 100%;
      .video-box-qj {
        height: 100%;
        aspect-ratio: 2688 / 6080;
        position: relative;
        &-tip {
          height: 100%;
          width: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          color: #fff;
          position: absolute;
          top: 0;
          left: 0;
        }
        .video-box-wrapper {
          height: 100%;
          width: 100%;
          position: absolute;
          top: 0;
          left: 0;
          display: flex;
          justify-content: center;
          align-items: center;
          background-color: #000;
          .arco-spin {
            position: absolute;
          }
          .video-tools {
            position: absolute;
            right: 10px;
            top: 10px;
            z-index: 99;
          }
        }
      }
      .video-right-content {
        flex: 1;
        padding: 15px;
        display: flex;
        flex-flow: column;
        gap: 8px;
        &-tools {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          gap: 4px;
        }
      }
    }
    .screen-active {
      border: 1px solid red;
    }
    .alarm-box {
      flex: 1;
      min-height: 100px;
      :deep(.arco-table) {
        .arco-table-scroll-y > .arco-scrollbar {
          height: 100%;
        }
      }
    }
  }
  .video-box {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #000;
    overflow: hidden;
    box-sizing: content-box;
    border: 1px solid #000000;
    cursor: pointer;
    .arco-spin {
      position: absolute;
    }
    &-tip {
      height: 100%;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
      position: absolute;
      top: 0;
      left: 0;
    }
    .video-tools {
      position: absolute;
      right: 10px;
      top: 10px;
      z-index: 99;
      display: flex;
      gap: 8px;
    }
  }
</style>
