<script setup lang="ts">
import {
  downloadVideoFile,
  setOnOffVal,
  stopVideo,
  videoLogin,
  videoScreenCapture,
} from '@/services/video-service';
import { traduction } from '@/utils/language';
import { computed, onMounted, onUnmounted, PropType, reactive, ref, toRefs } from 'vue';
import { IPlayInfo, IVideoShotGroup } from '../models/video.datatype';
import { taskService, getFileSize } from '../util/video.util';
import { IconDownload, IconRefresh, IconPlay } from '@computing/opendesign-icons';
import useStore from '@/stores';
import Dialog from '../../../../components/Dialog/Dialog.vue';
import { showElMessage } from '@/utils/utils';
import { showFailedMessage } from '@/utils/composition';

const emits = defineEmits(['change-act-id']);
const store = useStore();

const props = defineProps({
  enabled: {
    type: Boolean,
    required: true,
    default: false,
  },
  group: {
    type: Array as any,
    required: true,
    default: () => [],
  },
  activatedSystemId: {
    type: Number,
    required: true,
    default: 1,
  },
  tabPlayerGroup: {
    type: Array as any,
    required: true,
    default: () => [],
  },
  systemIds: {
    type: String,
    required: true,
    default: '',
  },
});
const { enabled, group, activatedSystemId, tabPlayerGroup } = toRefs(props);
let originEnabled = enabled.value;
const shotEnabled = ref(enabled.value);
const playerGroup = ref(group.value);
let openInfo = reactive({}) as IVideoShotGroup;
const dialogRef = ref();
const activeSystemId = ref(activatedSystemId.value);
const tabPlayerGroupData = ref(tabPlayerGroup.value);
const activeName = ref('host1');
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const dialogConfig = reactive({
  id: 'videoConfirm',
  content: traduction('VIDEO_DEL_VIDEO_USER'),
  title: traduction('ALARM_OK'),
});
function changeHost() {
  dialogConfig.id = 'changeImg';
  dialogConfig.content = traduction('COMMON_ASK_OK');
  dialogRef.value.show();
}
function changeSwitch() {
  dialogConfig.id = 'videoEnableId';
  dialogConfig.content = traduction('COMMON_ASK_OK');
  dialogRef.value.show();
}

function sendChangeSwitch() {
  if (originEnabled !== shotEnabled.value) {
    const param = { VideoRecordingEnabled: shotEnabled.value };
    setOnOffVal(param).then(
      (res: any) => {
        store.state.event.setEventState({
          type: 'alertMessage',
          value: { type: 'success', message: traduction('COMMON_SUCCESS') },
        });
        originEnabled = shotEnabled.value;

        if (res.data && res.data !== '') {
          shotEnabled.value = res.data.VideoRecordingEnabled;
          originEnabled = res.data.VideoRecordingEnabled;
          const group1 = res.data.VideoRecords.slice(0, 3);
          const group2 = res.data.VideoRecords.slice(3, 6);
          if (activeName.value === 'host1') {
            group1.forEach((record: any, index: number) => {
              tabPlayerGroupData.value[0].playerGroup[index + 1].value =
                record !== null ? getFileSize(record.VideoSizeByte) : '0';
              if (tabPlayerGroupData.value[0].playerGroup[index + 1].value !== '0') {
                tabPlayerGroupData.value[0].playerGroup[index + 1].detail = record.CreateTime;
              }
            });
          } else {
            group2.forEach((record: any, index: number) => {
              tabPlayerGroupData.value[1].playerGroup[index + 1].value =
                record !== null ? getFileSize(record.VideoSizeByte) : '0';
              if (tabPlayerGroupData.value[1].playerGroup[index + 1].value !== '0') {
                tabPlayerGroupData.value[1].playerGroup[index + 1].detail = record.CreateTime;
              }
            });
          }
        }
      },
      error => {
        const errorCode = error?.data?.error?.[0]?.code;
        if (errorCode) {
          store.state.commit('setEventState', {
            type: 'alertMessage',
            value: {
              type: 'error',
              message: traduction(errorCode + '.errorMessage') || traduction('COMMON_FAILED'),
            },
          });
        } else {
          showFailedMessage();
        }
      },
    );
  }
}
function widnowDown(ev: any) {
  const target: HTMLElement = ev.target;
  const className = target.getAttribute('class');
  if (className && className.indexOf('circle') === -1 && className.indexOf('play-menu') === -1) {
    for (const key of playerGroup.value) {
      key.active = false;
    }
  }
}

onMounted(() => {
  window.addEventListener('mousedown', widnowDown, false);
});

onUnmounted(() => {
  window.removeEventListener('mousedown', widnowDown);
});

function downloadVideo(item: any) {
  if (item.down) {
    return;
  }
  item.down = true;
  const queryParams = {
    // 支持导出到本地或远端
    VideoType: '',
    SystemId: activeName.value === 'host1' ? 1 : 2,
  };

  switch (item.downloadId) {
    case 'cpuErrorId':
      queryParams.VideoType = 'CaterrorVideo';
      break;
    case 'downOffId':
      queryParams.VideoType = 'PoweroffVideo';
      break;
    case 'restDownId':
      queryParams.VideoType = 'OsresetVideo';
      break;
    default:
      queryParams.VideoType = '';
      break;
  }
  downloadFN(queryParams, item);
}

// 下载录像文件到/tmp/web
function downloadFN(params: any, item: any) {
  downloadVideoFile(params).then(
    (res: any) => {
      taskService(res.data.url, item, activeName.value, props.systemIds);
    },
    error => {
      const errorCode = error.data.error[0].code;
      if (errorCode !== 'TaskLimitExceeded') {
        showElMessage(
          'error',
          traduction(errorCode + '.errorMessage') || traduction('COMMON_FAILED'),
        );
      } else {
        showElMessage('error', traduction('COMMON_FAILED'));
      }
      item.down = false;
    },
  );
}

function dialogClose(reason: boolean) {
  dialogRef.value.hide();
  if (reason) {
    if (dialogConfig.id === 'videoEnableId') {
      sendChangeSwitch();
    } else if (dialogConfig.id === 'changeImg') {
      let params: any = {};
      if (activeSystemId.value === 1) {
        params.ActivatedSystemId = 2;
      } else {
        params.ActivatedSystemId = 1;
      }
      emits('change-act-id', params.ActivatedSystemId);
      setOnOffVal(params).then(
        (res: any) => {
          store.state.event.setEventState({
            type: 'alertMessage',
            value: { type: 'success', message: traduction('COMMON_SUCCESS') },
          });
          if (res.data && res.data !== '') {
            activeSystemId.value = res.data.ActivatedSystemId;
          }
        },
        error => {
          const errorCode = error?.data?.error?.[0]?.code;
          if (errorCode) {
            store.state.commit('setEventState', {
              type: 'alertMessage',
              value: {
                type: 'error',
                message: traduction(errorCode + '.errorMessage') || traduction('COMMON_FAILED'),
              },
            });
          } else {
            showFailedMessage();
          }
        },
      );
    } else {
      stopVideo({}).then(resStop => {
        playVideo(openInfo);
      });
    }
  } else {
    shotEnabled.value = originEnabled;
  }
}

function refreshVideo(playId: string) {
  videoScreenCapture().then(res => {
    const group1 = res.VideoRecords.slice(0, 3);
    const group2 = res.VideoRecords.slice(3, 6);
    if (activeName.value === 'host1') {
      tabPlayerGroupData.value[0].playerGroup.forEach((item: IVideoShotGroup, index: number) => {
        const record = group1[index - 1];
        if (item.playId === playId) {
          item.value = record !== null ? getFileSize(record.VideoSizeByte) : '0';
          if (item.value !== '0') {
            item.detail = record.CreateTime;
          }
        }
      });
    } else {
      tabPlayerGroupData.value[1].playerGroup.forEach((item: IVideoShotGroup, index: number) => {
        const record = group2[index - 1];
        if (item.playId === playId) {
          item.value = record !== null ? getFileSize(record.VideoSizeByte) : '0';
          if (item.value !== '0') {
            item.detail = record.CreateTime;
          }
        }
      });
    }
  });
}
function playVideo(info: IVideoShotGroup): void {
  videoLogin(info.videoType, activeName.value).then(
    response => {
      openVideoClient(response.data, info.playId);
    },
    error => {
      const errorCode = error.data.error[0].code;
      // 非本地播放器且有其他用户占用，则需要先踢出用户
      if (info.playId !== 'localId' && errorCode === 'SessionLimitExceeded') {
        dialogConfig.id = 'videoConfirm';
        dialogConfig.content = traduction('VIDEO_DEL_VIDEO_USER');
        dialogRef.value.show();
        openInfo = { ...info };
      } else {
        showElMessage(
          'error',
          traduction(errorCode + '.errorMessage') || traduction('COMMON_FAILED'),
        );
      }
    },
  );
}
function openVideoClient(data: IPlayInfo, playId: string) {
  localStorage.setItem('isValidVideoUser', 'true');
  localStorage.setItem('videoId', playId);
  localStorage.setItem('videoInfo', JSON.stringify(data));
  const host = activeName.value === 'host1' ? 1 : 2;
  const toURL = props.systemIds.length === 2 && playId !== 'localId' ? `#/videoPlayer/${playId}?systemIds=${host}` : `#/videoPlayer/${playId}`;
  const win = window.open(toURL, '_blank');
  if (win) {
    win.opener = null;
  }
  return;
}
</script>

<template>
  <el-alert v-if="systemIds.length === 2" class="video-tip" type="info" show-icon>
    <template #title>
      <span class="video-tip-active">
        {{ $t('VIDEO_TIP_ACTIVE', { num: activeSystemId }) }}
      </span>
      <span class="video-tip-change" @click="changeHost">
        {{ $t('SERVICE_VNC_TIP_CHANGE') }}
      </span>
    </template>
  </el-alert>
  <div id="videoShotViewId" class="content-content">
    <span id="screenVideo" v-t="'REMOTE_KINESCOPE'" class="content-title"></span>
    <div class="enable-switch">
      <span>{{ $t('VIDEO_RECORDING_FUNCTION') }}</span>
      <el-switch
        id="shotStatus"
        v-model="shotEnabled"
        :disabled="isSystemLock"
        @change="changeSwitch"
      ></el-switch>
    </div>
    <div class="local-div">
      <span class="local-player">{{ traduction('VIDEO_RECORDING_LOCAL') }}</span>
      <el-button id="playMenulocalId0" class="local-item" @click="playVideo(tabPlayerGroupData[0].playerGroup[0])">
        {{ traduction('HTML5_VIDEO_PLAYER') }}
      </el-button>
      <span class="local-detail">{{ traduction('VIDEO_DOWNLOAD_PLAYER') }}</span>
    </div>
    <el-tabs v-if="systemIds.length === 2" v-model="activeName" class="host-tabs">
      <el-tab-pane
        v-for="(tab, idx) in tabPlayerGroupData"
        :key="tab.name"
        :label="$t(tab.label)"
        :name="tab.name"
      >
        <div class="table-box">
          <div v-for="item in tab.playerGroup" :key="item.playId" class="bg-box"></div>
          <table class="video-table">
            <tr v-for="item in tab.playerGroup" :key="item.playId" class="item">
              <td>
                <div v-if="item.playId !== 'localId'" class="td-item no-bg-item">
                  <div
                    class="capture-video-div video-background"
                    :class="{ 'has-video': item.value !== '0' }"
                  >
                    <div :id="`${item.playId}-${idx}`" class="circle"></div>
                  </div>
                  <div class="file-title title-btn-time">
                    <div class="title-tiem-text">
                      <div class="p-first">
                        <span :id="`label-${item.playId}-${idx}`" class="video-title-text">
                          {{ item.label }}
                        </span>
                        <span v-if="item.value !== '0'" :id="`file-${item.playId}-${idx}`" class="file-size">
                          {{ item.value }}
                        </span>
                      </div>
                      <div :id="`detail-${item.downloadId}-${idx}`" class="video-sub-title">
                        {{ item.value === '0' ? '--' : item.detail }}
                      </div>
                    </div>
                    <div class="btn-box">
                      <div :id="`${item.playId}-${idx}`" class="video-dow video-button" @click="playVideo(item)">
                        <el-icon :size="16">
                          <IconPlay />
                        </el-icon>
                        <span class="btn-text">{{ traduction('VIDEO_OPEN') }}</span>
                      </div>
                      <div
                        v-if="item.value !== '0'"
                        :id="`${item.downloadId}-${idx}`"
                        :class="item.down ? 'video-dow video-button-disable' : 'video-dow video-button'"
                        @click="downloadVideo(item || { downloadId: '' })"
                      >
                        <el-icon :size="16">
                          <IconDownload />
                        </el-icon>
                        <span class="btn-text">{{ traduction('VIDEO_DOWNLOAD') }}</span>
                      </div>
                      <div
                        :id="item.refreshId"
                        class="video-refresh video-button"
                        @click="refreshVideo(item.playId || '')"
                      >
                        <el-icon :size="16">
                          <IconRefresh />
                        </el-icon>
                        <span class="btn-text">{{ traduction('VIDEO_REFRESH') }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          </table>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div v-else class="table-box">
      <div v-for="item in tabPlayerGroupData[0].playerGroup" :key="item.playId" class="bg-box"></div>
      <table class="video-table">
        <tr v-for="item in tabPlayerGroupData[0].playerGroup" :key="item.playId" class="item">
          <td>
            <div v-if="item.playId !== 'localId'" class="td-item no-bg-item">
              <div
                class="capture-video-div video-background"
                :class="{ 'has-video': item.value !== '0' }"
              >
                <div :id="item.playId" class="circle"></div>
              </div>
              <div class="file-title title-btn-time">
                <div class="title-tiem-text">
                  <div class="p-first">
                    <span :id="'label' + item.playId" class="video-title-text">
                      {{ item.label }}
                    </span>
                    <span v-if="item.value !== '0'" :id="'file' + item.playId" class="file-size">
                      {{ item.value }}
                    </span>
                  </div>
                  <div :id="'detail' + item.downloadId" class="video-sub-title">
                    {{ item.value === '0' ? '--' : item.detail }}
                  </div>
                </div>
                <div class="btn-box">
                  <div :id="item.playId" class="video-dow video-button" @click="playVideo(item)">
                    <el-icon :size="16">
                      <IconPlay />
                    </el-icon>
                    <span class="btn-text">{{ traduction('VIDEO_OPEN') }}</span>
                  </div>
                  <div
                    v-if="item.value !== '0'"
                    :id="item.downloadId"
                    :class="item.down ? 'video-dow video-button-disable' : 'video-dow video-button'"
                    @click="downloadVideo(item || { downloadId: '' })"
                  >
                    <el-icon :size="16">
                      <IconDownload />
                    </el-icon>
                    <span class="btn-text">{{ traduction('VIDEO_DOWNLOAD') }}</span>
                  </div>
                  <div
                    :id="item.refreshId"
                    class="video-refresh video-button"
                    @click="refreshVideo(item.playId || '')"
                  >
                    <el-icon :size="16">
                      <IconRefresh />
                    </el-icon>
                    <span class="btn-text">{{ traduction('VIDEO_REFRESH') }}</span>
                  </div>
                </div>
              </div>
            </div>
          </td>
        </tr>
      </table>
    </div>
    <Dialog ref="dialogRef" :config="dialogConfig" @close="dialogClose" />
  </div>
</template>

<style lang="scss" scoped>
.video-tip {
  font-size: 12px;
  color: #000000;
  font-weight: 400;
  line-height: 16px;
  margin-bottom: 8px;
  .video-tip-change {
    color: var(--o-color-primary) !important;
    cursor: pointer;
    &:hover {
      color: var(--o-color-primary-secondary);
    }
  }
}
#videoShotViewId {
  padding: 24px;
  background: var(--o-bg-color-base);
  border-radius: 4px;
  .content-title {
    font-size: 16px;
    line-height: 24px;
    font-weight: 600;
  }

  .enable-switch {
    margin: 16px 0 24px;
    span {
      margin-right: 24px;
      font-size: 12px;
      color: var(--o-text-color-secondary);
      letter-spacing: 0;
      line-height: 16px;
    }
  }

  .local-div {
    margin-top: 16px;
    .local-player {
      font-size: 12px;
      color: var(--o-text-color-secondary);
      letter-spacing: 0;
      line-height: 16px;
    }
    .local-item {
      margin-left: 24px;
      margin-right: 8px;
      font-size: 12px;
      color: var(--o-text-color-secondary);
      letter-spacing: 0;
      text-align: center;
      line-height: 16px;
    }
    .local-detail {
      font-size: 12px;
      color: var(--o-text-color-tertiary);
      letter-spacing: 0;
      line-height: 16px;
    }
  }

  .host-tabs {
    margin-top: 16px;
  }
  .table-box {
    position: relative;
    padding-top: 24px;

    .bg-box {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
      display: inline-block;
      width: 100%;
      height: calc(33% - 12.5px);
      background: var(--o-bg-color-light);
      border-radius: 4px;
    }

    .bg-box:nth-child(1) {
      top: 24px;
    }

    .bg-box:nth-child(2) {
      top: calc(33% + 19.5px);
    }

    .bg-box:nth-child(3) {
      top: calc(66% + 15px);
    }

    .bg-box:nth-child(4) {
      top: calc(75%);
      display: none;
    }

    .video-table {
      position: relative;
      z-index: 2;
      width: 100%;
      border: none;
      border-spacing: 0;

      .item {
        height: 76px;
        margin-bottom: 8px;
        &:last-child {
          margin-bottom: 0;
        }
      }

      .item:nth-child(1) {
        display: none;
      }
      tr {
        display: flex;
      }

      tr td {
        z-index: 2;
        box-sizing: content-box;
        border: none;
        padding: 0;
        width: 100%;

        .td-item {
          background: var(--o-bg-color-light);
          border-radius: 4px;
          display: flex;
          align-items: center;
          .file-title {
            width: calc(100% - 72px);
            margin: 16px 24px 16px 0;
            display: flex;
            align-items: center;

            .p-first {
              font-weight: 600;
              font-size: 16px;

              .file-size {
                color: var(--o-text-color-secondary);
              }
            }

            .video-sub-title {
              color: var(--o-text-color-secondary);
              margin-top: 8px;
              width: calc(100% - 68px);
            }
            .video-button {
              cursor: pointer;
              border: 1px solid var(--o-border-color-lighter);
              border-radius: 2px;
              height: 32px;
              margin-left: 8px;
              padding: 8px 16px;
              display: flex;
              .el-icon {
                color: var(--o-text-color-tertiary);
              }
              span {
                font-size: 12px;
                color: var(--o-text-color-secondary);
                letter-spacing: 0;
                text-align: center;
                line-height: 14px;
                margin-left: 6px;
              }
            }
            .video-button-disable {
              border: 1px solid var(--o-border-color-lighter);
              color: var(--o-color-placeholder);
              background-color: var(--o-bg-color-placeholder);;
              border-color: var(--o-border-color-lighter);
              border-radius: 2px;
              height: 32px;
              margin-left: 8px;
              padding: 8px 16px;
              display: flex;
              .el-icon {
                color: var(--o-text-color-tertiary);
              }
              span {
                font-size: 12px;
                color: var(--o-text-color-secondary);
                letter-spacing: 0;
                text-align: center;
                line-height: 14px;
                margin-left: 6px;
              }
            }
          }

          .file-title-btn {
            display: block;
            padding-bottom: 25px;
          }

          .title-btn-time {
            .title-tiem-text {
              flex: 1;
            }

            .btn-box {
              margin-left: 8px;
              display: flex;
              flex-wrap: wrap;
            }

            .video-sub-title {
              white-space: nowrap;
            }
          }

          .has-video {
            .circle {
              background: url('/src/assets/assets-bmc/default/video_y.svg') no-repeat !important;
            }
          }
          .capture-video-div {
            width: 40px;
            height: 40px;
            margin: 18px 8px 18px 24px;
            background: var(--o-bg-color-light);
            box-shadow: inset 0 -1px 0 0 var(--o-border-color-light);

            .circle {
              position: absolute;
              width: 40px;
              height: 40px;
              background: url('/src/assets/assets-bmc/default/video_n.svg') no-repeat;
            }
            .player-menu-options {
              background: var(--o-bg-color-base);
              box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.24);
              border-radius: 4px;
              z-index: 1001;
              min-width: 160px;
              position: absolute;
              left: calc(50% + 4px);
              top: calc(50% + 8px);
              width: 56px;
              padding: 4px 0;

              .player-menu-item {
                display: block;
                line-height: 16px;
                cursor: pointer;
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;
              }

              .player-menu-item:first-child {
                padding: 8px 24px 4px 24px;
              }

              .player-menu-item:last-child {
                padding: 4px 24px 8px 24px;
              }
              .player-menu-item:hover {
                background: var(--o-color-primary-secondary);
                color: var(--o-color-white);
              }
            }
          }
        }

        .no-bg-item {
          background-color: rgba(0, 0, 0, 0);
        }
      }
    }
  }
}
</style>
