<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 {};
    },
  },
});
const { data } = toRefs(props);
const screenShotTime = ref('');
const picDisable = ref(false);
const src = ref('');
const dialogRef = ref();
const imageUrl = '/tmp/web/manualscreen.jpeg';
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 (data.value['Time3'] !== '' && data.value['Time3'] !== null) {
    getImg(imageUrl);
  } else {
  }
}

// 虚拟控制台手动截屏
function getImg(url: string) {
  let xmlhttp: XMLHttpRequest = new XMLHttpRequest();
  xmlhttp.open('GET', url);
  xmlhttp.responseType = 'blob';
  xmlhttp.onload = () => {
    if (xmlhttp.status === 200) {
      src.value = imageUrl;
      picDisable.value = false;
      screenShotTime.value = data.value['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') {
          src.value = imageUrl + '?a=' + Date.now();
          screenShotTime.value = taskData.ScreenshotCreateTime;
          store.state.event.setEventState({
            type: 'alertMessage',
            value: { type: 'success', message: traduction('COMMON_SUCCESS') },
          });
          picDisable.value = false;
          videoScreenCapture().then(rsp => {
            screenShotTime.value = rsp.ScreenshotCreateTime?.Time3 || '';
          });
        } 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() {
  deletescreenshot({}).then(
    res => {
      store.state.event.setEventState({
        type: 'alertMessage',
        value: { type: 'success', message: traduction('COMMON_SUCCESS') },
      });
      src.value = '';
    },
    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="src !== ''" id="deleteCapId" class="del-button" @click="deleteFN()">
        <el-icon id="picDelete" :size="16"><IconDelete></IconDelete></el-icon>
      </div>
    </div>
    <div class="captrue-img-area">
      <el-image
        v-if="src !== ''"
        id="captId"
        class="small-img"
        :src="src"
        :preview-src-list="[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="src !== ''" id="capTime" class="time">{{ 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;
  }

  .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 {
    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;
      #picDelete {
        color: var(--o-color-primary-secondary);
      }
    }

    #picDelete {
      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>
