<template>
  <el-dialog class="show-file" :visible="dialogVisibleShowFile" width="1100px" @close="dialogShowFileClose">
    <div slot="title">{{ $t('Key322') }}【{{ fileName }}】</div>
    <div v-loading="loading">
      <iframe
        v-if="fileUrl.length > 0"
        id="iframe"
        :src="`${$store.state.app.config.doc_preview_service_address}/onlinePreview?url=${fileUrl}`"
        width="100%"
        height="540px"
      />
    </div>

    <div slot="footer">
      <el-button @click="dialogShowFileClose">
        {{ $t('Key246') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { GetFileStoreInfo } from '@/api/app';
import { encode } from 'js-base64';

export default {
  name: 'ShowFile',
  props: {
    fileName: {
      default: '',
      type: String
    },
    fileId: {
      default: '',
      type: String
    }
  },
  data() {
    return {
      loading: false,
      dialogVisibleShowFile: false,
      fileUrl: ''
    };
  },
  watch: {
    fileId(newVal) {
      if (newVal.length > 0) {
        this.getFileStoreInfo();
      }
    },
    dialogVisibleShowFile(newVal) {
      if (!newVal) {
        this.fileUrl = '';
      }
    }
  },
  methods: {
    getFileStoreInfo() {
      GetFileStoreInfo({ file_id: this.fileId }).then(({ file_url_https }) => {
        this.loading = true;
        this.fileUrl = encodeURIComponent(encode(file_url_https));
        this.$nextTick(() => {
          document.getElementById('iframe').onload = () => {
            this.loading = false;
          };
        });
      });
    },

    showDialog() {
      this.dialogVisibleShowFile = true;
    },

    dialogShowFileClose() {
      this.dialogVisibleShowFile = false;
      this.$emit('dialogShowFileClose');
    }
  }
};
</script>

<style lang="scss">
@import '~@/styles/mixin';

.show-file {
  @include dialog;

  .el-dialog__header {
    font-weight: bold;
  }

  %image-parent,
  .image-parent {
    display: flex;
    justify-content: center;
  }

  .audio-file {
    @extend %image-parent;
  }

  .video-file {
    @extend %image-parent;

    video {
      width: 100%;
    }
  }

  .text-file {
    height: 60vh;

    .el-textarea,
    textarea {
      height: 100%;
    }
  }
}
</style>
