<script setup lang="ts">
import { onUnmounted, reactive, ref, toRefs } from 'vue';
import { IconDelete, IconAlertCircle } from '@computing/opendesign-icons';
import Dialog from '../../../../components/Dialog/Dialog.vue';
import { traduction } from '@/utils/language';
import {
  capturescreenshot,
  deletescreenshot,
  queryTask,
  videoScreenCapture,
} from '@/services/video-service';
import useStore from '@/stores';

const store = useStore();

const props = defineProps({
  data: {
    type: Object,
    required: true,
    default: () => {
      return {};
    },
  },
  systemIds: {
    type: Array as any,
    required: true,
    default: () => [],
  },
  activatedSystemId: {
    type: Number,
    required: true,
    default: 1,
  },
  tabScreenShot: {
    type: Array as any,
    required: true,
    default: () => [],
  },
});
const { data, tabScreenShot, activatedSystemId } = toRefs(props);
const activeSystemId = ref(activatedSystemId.value);
const picDisable = ref(false);
const dialogRef = ref();
const imageUrl1 = '/tmp/web/manualscreen.jpeg';
const imageUrl2 = '/tmp/web/system2_manualscreen.jpeg';
const activeName = ref('host1');
const tabScreenShotData: any = ref(tabScreenShot.value);
let timeout = null as any;
const dialogConfig = reactive({
  id: 'capScreen',
  content: traduction('COMMON_ASK_OK'),
  title: traduction('ALARM_OK'),
  okButton: { id: 'capScreen_ok_btn' },
  cancelButton: { id: 'capScreen_cancel_btn' },
});
initData();
function initData() {
  if (tabScreenShotData.value[0].data['Time3'] !== '' && tabScreenShotData.value[0].data['Time3'] !== undefined && tabScreenShotData.value[0].data['Time3'] !== null) {
    getImg1(imageUrl1);
  } else {
  }
  if (tabScreenShotData.value[1].data['Time3'] !== '' && tabScreenShotData.value[1].data['Time3'] !== undefined && tabScreenShotData.value[1].data['Time3'] !== null) {
    getImg2(imageUrl2);
  } else {
  }
}

// 虚拟控制台手动截屏
function getImg1(url: string) {
  let xmlhttp: XMLHttpRequest = new XMLHttpRequest();
  xmlhttp.open('GET', url);
  xmlhttp.responseType = 'blob';
  xmlhttp.onload = () => {
    if (xmlhttp.status === 200) {
      tabScreenShotData.value[0].src = imageUrl1;
      picDisable.value = false;
      tabScreenShotData.value[0].screenShotTime = tabScreenShot.value[0].data['Time3'];
    }
  };
  xmlhttp.send();
}
function getImg2(url: string) {
  let xmlhttp: XMLHttpRequest = new XMLHttpRequest();
  xmlhttp.open('GET', url);
  xmlhttp.responseType = 'blob';
  xmlhttp.onload = () => {
    if (xmlhttp.status === 200) {
      tabScreenShotData.value[1].src = imageUrl2;
      picDisable.value = false;
      tabScreenShotData.value[1].screenShotTime = tabScreenShot.value[1].data['Time3'];
    }
  };
  xmlhttp.send();
}

function capFN() {
  dialogConfig.id = 'capScreen';
  dialogConfig.okButton = { id: 'capScreen_ok_btn' };
  dialogConfig.cancelButton = { id: 'capScreen_cancel_btn' };
  dialogRef.value.show();
}

function dialogClose(reason: boolean) {
  dialogRef.value.hide();
  if (reason) {
    if (dialogConfig.id === 'capScreen') {
      captrueScreenFn();
    } else {
      deleteCapt();
    }
  }
}
// 手动屏幕截屏针对的是当前激活的主机
function captrueScreenFn() {
  capturescreenshot({}).then((res: any) => {
    if (res.data !== undefined && res.data !== null) {
      taskFn(res.data.url);
    }
  });
}

function taskFn(url: string) {
  picDisable.value = true;
  queryTask(url).then(
    (res: any) => {
      const taskData = res.data;
      if (taskData !== undefined) {
        if (taskData.state === 'Completed') {
          if (activeSystemId.value !== 2) {
            tabScreenShotData.value[0].src = imageUrl1 + '?a=' + Date.now();
            tabScreenShotData.value[0].screenShotTime = taskData.ScreenshotCreateTime;
          } else {
            tabScreenShotData.value[1].src = imageUrl2 + '?a=' + Date.now();
            tabScreenShotData.value[1].screenShotTime = taskData.ScreenshotCreateTime;
          }
          store.state.event.setEventState({
            type: 'alertMessage',
            value: { type: 'success', message: traduction('COMMON_SUCCESS') },
          });
          picDisable.value = false;
          videoScreenCapture().then(rsp => {
            if (activeSystemId.value !== 2) {
              tabScreenShotData.value[0].screenShotTime = rsp.Screenshots?.[0]?.CreateTime?.Manual || '';
            } else {
              tabScreenShotData.value[1].screenShotTime = rsp.Screenshots?.[1]?.CreateTime?.Manual || '';
            }
          });
        } else {
          timeout = setTimeout(() => {
            taskFn(url);
          }, 3000);
        }
      }
    },
    error => {
      picDisable.value = false;
      store.state.event.setEventState({
        type: 'alertMessage',
        value: { type: 'error', message: traduction(traduction('COMMON_FAILED')) },
      });
    },
  );
}

// 删除截屏
function deleteFN() {
  dialogConfig.id = 'delScreen';
  dialogConfig.okButton = { id: 'delScreen_ok_btn' };
  dialogConfig.cancelButton = { id: 'delScreen_cancel_btn' };
  dialogRef.value.show();
}

function deleteCapt() {
  const param = {
    SystemId: activeName.value === 'host1' ? 1 : 2,
  };
  deletescreenshot(param).then(
    res => {
      store.state.event.setEventState({
        type: 'alertMessage',
        value: { type: 'success', message: traduction('COMMON_SUCCESS') },
      });
      if (activeName.value === 'host1') {
        tabScreenShotData.value[0].src = '';
      } else {
        tabScreenShotData.value[1].src = '';
      }
    },
    error => {
      const code = error?.data?.error[0]?.code;
      if (code === 'SystemLockdownForbid') {
        const errorMessage = code + '.errorMessage';
        store.state.event.setEventState({
          type: 'alertMessage',
          value: { type: 'error', message: traduction(traduction(errorMessage)) }
        });
        return;
      }
      store.state.event.setEventState({
        type: 'alertMessage',
        value: { type: 'error', message: traduction(traduction('COMMON_FAILED')) },
      });
    },
  );
}

onUnmounted(() => {
  if (timeout !== null) {
    clearTimeout(timeout);
  }
});
</script>

<template>
  <div id="screenCaptureId">
    <div class="content-title">{{ traduction('VIDEO_HAND_CUT') }}</div>
    <div class="operate">
      <el-button id="capFnId" :type="'primary'" :disabled="picDisable" @click="capFN()">
        <el-icon class="camera"><img src="/src/assets/assets-bmc/default/camera.svg" /></el-icon>
        {{ $t('VIDEO_RECORDING_HAND_CUT') }}
      </el-button>
      <div v-if="tabScreenShotData[0].src !== '' && systemIds.length !== 2" id="deleteCapId" class="del-button" @click="deleteFN()">
        <el-icon id="picDelete" class="del-icon" :size="16"><IconDelete></IconDelete></el-icon>
      </div>
    </div>
    <el-tabs v-if="systemIds.length === 2" v-model="activeName" class="host-tabs">
      <el-tab-pane
        v-for="(tab, idx) in tabScreenShotData"
        :key="tab.name"
        :label="$t(tab.label)"
        :name="tab.name"
      >
        <div class="captrue-img-area">
          <div v-if="tab.src !== ''" :id="`deleteCapId-${idx}`" class="del-button" :class="{ 'host2': systemIds.length === 2 }" @click="deleteFN()">
            <el-icon :id="`picDelete-${idx}`" class="del-icon" :size="16"><IconDelete></IconDelete></el-icon>
          </div>
          <el-image
            v-if="tab.src !== ''"
            :id="`captId-${idx}`"
            class="small-img"
            :src="tab.src"
            :preview-src-list="[tab.src]"
            hide-on-click-modal="true"
            fit="cover"
          >
            <template #error>
              <div class="image-slot">
                <div class="center">
                  <el-icon :size="24"><IconAlertCircle /></el-icon>
                  <p>{{ traduction('LOAD_FAILED') }}</p>
                </div>
              </div>
            </template>
          </el-image>
          <img v-else :id="`captId-${idx}`" class="no-pic" src="/src/assets/assets-bmc/default/screenshots.png" />

          <span v-if="tab.src !== ''" :id="`capTime-${idx}`" class="time">{{ tab.screenShotTime }}</span>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div v-else class="captrue-img-area">
      <el-image
        v-if="tabScreenShotData[0].src !== ''"
        id="captId"
        class="small-img"
        :src="tabScreenShotData[0].src"
        :preview-src-list="[tabScreenShotData[0].src]"
        hide-on-click-modal="true"
        fit="cover"
      >
        <template #error>
          <div class="image-slot">
            <div class="center">
              <el-icon :size="24"><IconAlertCircle /></el-icon>
              <p>{{ traduction('LOAD_FAILED') }}</p>
            </div>
          </div>
        </template>
      </el-image>
      <img v-else id="captId" class="no-pic" src="/src/assets/assets-bmc/default/screenshots.png" />

      <span v-if="tabScreenShotData[0].src !== ''" id="capTime" class="time">{{ tabScreenShotData[0].screenShotTime }}</span>
    </div>
    <Dialog ref="dialogRef" :config="dialogConfig" @close="dialogClose"></Dialog>
  </div>
</template>

<style lang="scss" scoped>
#screenCaptureId {
  margin-top: 16px;
  margin-left: 16px;
  padding: 24px;
  background: var(--o-bg-color-base);
  border-radius: 4px;
  .content-title {
    font-size: 16px;
    line-height: 24px;
    margin-bottom: 8px;
    font-weight: 600;
  }
  .operate {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16px;
  }
  .host-tabs {
    margin-top: 16px;
  }

  .captrue-img-area {
    height: 350px;
    margin-top: 16px;
    width: 100%;
    background: var(--o-bg-color-light);
    border-radius: 4px;
    position: relative;

    .no-pic {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }

  .time {
    position: relative;
    bottom: 24px;
    left: 24px;
    color: #fffefe;
  }

  .del-button {
    &.host2 {
      position: absolute;
      top: 24px;
      right: 24px;
    }
    width: 32px;
    height: 32px;
    border: 1px solid var(--o-border-color-lighter);
    border-radius: 2px;
    text-align: center;
    z-index: 1;
    &:hover {
      border-color: var(--o-color-primary-secondary);
      cursor: pointer;
      .del-icon {
        color: var(--o-color-primary-secondary);
      }
    }

    .del-icon {
      margin-top: 8px;
      color: var(--o-text-color-tertiary);
    }
  }

  .small-img {
    width: 100%;
    height: 100%;
  }

  .camera {
    margin-right: 8px;
  }

  .image-slot {
    background: var(--o-border-color-base);
    border-radius: 1px;
    height: 100%;
    text-align: center;
    .el-icon {
      color: var(--o-color-placeholder);
      margin-top: calc(50% - 80px);
    }
    p {
      color: var(--o-text-color-tertiary);
    }
  }
}
</style>
