<template>
  <div class="upload-wrapper">
    <h5 v-if="uploadTitle" class="upload-title">{{ uploadTitle }}</h5>
    <el-upload
      ref="upload"
      :limit="filleNumber"
      action="no"
      :accept="uploadType"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :http-request="upload"
      :on-exceed="handleExceed"
      :disabled="disabled"
    >
      <div class="upload-audio">
        <span>上传{{ fileTypeName }}</span>
      </div>
    </el-upload>
    <div v-show="file_list_show.length > 0" class="file-wrapper">
      <div v-for="(item, index) in file_list_show" :key="index" class="file-item">
        <div class="file-name" @click="handlePreview(item.file_url)">
          <SvgIcon icon-class="file-3-line" class-name="file-icon" /><span>{{ item.file_name }}</span>
        </div>
        <SvgIcon icon-class="delete" class-name="delete pointer" @click="deleteFile(item.file_id)" />
      </div>
    </div>
    <el-dialog
      v-if="resourceFlag"
      :visible.sync="resourceFlag"
      :show-close="true"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      width="1200px"
      class="file-dialog"
    >
      <iframe :src="resourceUrl" width="100%" height="600px"></iframe>
    </el-dialog>
  </div>
</template>

<script>
import { fileUpload, GetFileStoreInfo } from '@/api/app';
import { Base64 } from 'js-base64';
import { getConfig } from '@/utils/auth';
import { conversionSize } from '@/utils/common';

export default {
  name: 'UploadFiles',
  props: {
    fileIdList: {
      type: Array,
      default: () => [],
    },
    filleNumber: {
      type: Number,
      default: 1,
    },
    fileTypeName: {
      type: String,
      default: '文件',
    },
    uploadType: {
      type: String,
      default: '*',
    },
    uploadTitle: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    // 最大文件大小（单位 MB）
    maxSize: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      file_list_show: [],
      file_id: '',
      file_url: '',
      file_name: '',
      resourceUrl: '', // 资源预览地址
      resourceFlag: false,
      file_preview_url: '',
    };
  },
  watch: {
    fileIdList: {
      handler(val) {
        if (!val.length === 0) return;
        this.file_list_show = [];
        val.forEach((item) => {
          GetFileStoreInfo({ file_id: item }).then(({ file_id, file_url, file_name }) => {
            let obj = {
              file_id,
              file_url,
              file_name,
            };
            this.file_list_show.push(obj);
          });
        });
      },
      immediate: true,
    },
  },
  created() {
    this.file_preview_url = getConfig() ? getConfig().doc_preview_service_address : '';
  },
  methods: {
    beforeUpload(file) {
      let size = file.size / 1024 / 1024;
      if (this.maxSize !== 0 && size > this.maxSize) {
        this.$message.error(`文件大小不能超过${conversionSize(this.maxSize * 1024 * 1024)}`);
        return false;
      }
    },
    upload(file) {
      fileUpload('Mid', file, { isGlobalprogress: true }).then(({ file_info_list }) => {
        if (file_info_list.length > 0) {
          const { file_id, file_name, file_url } = file_info_list[0];
          this.file_id = file_id;
          this.file_url = file_url;
          this.file_name = file_name;
          this.$emit('upload', file_id);
        }
      });
    },
    deleteFile(id) {
      this.$confirm('是否删除当前文件？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$emit('deleteFile', id);
          this.$refs.upload.clearFiles();
        })
        .catch(() => {});
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.filleNumber ? this.filleNumber : 1} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`,
      );
    },
    // 预览文件
    handlePreview(url) {
      let path = `${this.file_preview_url}/onlinePreview?url=${Base64.encode(url)}`;
      this.resourceUrl = path;
      this.resourceFlag = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.upload-wrapper {
  .upload-title {
    margin: 0;
    margin-bottom: 8px; // 因为这个title可能没有 所以给了bottom
    font-size: 14px;
    font-weight: 400;
    line-height: 22px;
    color: #000;
  }

  .upload-audio {
    display: flex;
    column-gap: 12px;
    align-items: center;
    padding: 5px 16px;
    font-size: 14px;
    line-height: 22px;
    color: #fff;
    background: #165dff;
    border-radius: 2px;
  }

  .file-wrapper {
    .file-item {
      display: flex;
      align-items: center;
      margin-top: 8px;
    }

    .file-name {
      display: flex;
      align-items: center;
      width: 360px;
      padding: 7px 12px;
      margin-right: 12px;
      cursor: pointer;
      background: $main-background-color;
      border-radius: 2px;

      .file-icon {
        flex-shrink: 0;
        width: 16px;
        height: 16px;
        margin-right: 12px;
        color: #000;
      }

      > span {
        flex: 1;
      }
    }
  }
}
</style>
