<!--
 * @Description: 单个PDF文件上传组件
 * @Author: Rockery
 * @Date: 2021-12-20 09:16:41
 * @LastEditors: Rockery
 * @LastEditTime: 2022-01-17 14:50:52
 * @FilePath: \party_construct_web\src\components\RocPdfFileUpload\index.vue
 * @Copyright: Copyright (c) 2016~2021 Rockery(1113269755@qq.com)
-->

<template>
  <div class="rocpdffileupload">
    <div class="rocpdffileupload-attachment" v-loading="removeLoading">
      <el-upload
        ref="rocPdfFileUploadRef"
        :disabled="disabled"
        :limit="1"
        accept=".pdf"
        :auto-upload="true"
        :show-file-list="true"
        :action="actionUrl"
        :headers="headers"
        :before-upload="handleRocPdfFileUploadBeforeUpload"
        :on-success="handleRocPdfFileUploadOnsuccess"
        :on-change="handleRocPdfFileUploadOnchange"
        :on-remove="handleRocPdfFileUploadOnRemove"
        :on-exceed="handleRocPdfFileUploadOnExceed"
        :class="{'is-disabled':disabled}"
        class="rocpdffileupload-attachment-fileupload"
      >
        <div class="rocpdffileupload-attachment-fileupload-content">
          <i class="el-icon-plus" />
          上传文件，格式：PDF
        </div>
      </el-upload>
      <div
        v-if="isUploadSuccess"
        class="fl rocpdffileupload-attachment-addr"
        @click="handleRocPdfFileUploadUrlClick"
      >
        <div>文件上传成功地址：</div>
        <!-- <a :href="successUrl" target="_blank">{{ successUrl }}</a> -->
        <div>{{ successResp.name }}</div>
      </div>
      <el-button
        v-if="isSelect && !isUploadSuccess"
        type="primary"
        size="small"
        @click="submitRocPdfFileUploadClick"
      >上传文件</el-button>
      <el-button v-if="isSelect" type="info" size="small" @click="removeRocPdfFileUploadClick">移除文件</el-button>
    </div>

    <roc-vue-pdf-dialog
      v-if="pdfDialogVisible"
      :visible.sync="pdfDialogVisible"
      :pdfUrl="successResp.successUrl"
    ></roc-vue-pdf-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth';

export default {
  name: 'Rocpdffileupload',
  components: {
    'roc-vue-pdf-dialog': () => import('@/components/RocVuePdfDialog')
  },
  props: {
    // 值
    value: {
      type: String,
      default: ''
    },
    // PDF文件上传地址
    uploadUrl: {
      type: String,
      default: `${process.env.VUE_APP_FILE_UPLOAD_API}`
    },
    // 请求头对象
    uploadHeaders: {
      type: Object,
      default: () => {
        return {
          Authorization: 'Bearer ' + getToken()
        };
      }
    },
    // 上传文件标题
    uploadFileTitle: {
      type: String,
      default: ''
    },
    // 是否禁用
    isDisabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 是否选择PDF文件
      isSelect: false,
      // 是否上传PDF文件成功
      isUploadSuccess: false,
      // PDF文件上传成功数据对象
      successUrl: '',
      // PDF文件上传成功数据对象
      successResp: {},
      pdfDialogVisible: false,
      removeLoading: false,
      setTimeoutTimer: null
    };
  },
  computed: {
    // PDF文件上传地址
    actionUrl() {
      return this.uploadUrl;
    },
    // 请求头对象
    headers() {
      return this.uploadHeaders;
    },
    // 上传文件标题
    fileTitle() {
      if (this.uploadFileTitle) {
        return `文件【${this.uploadFileTitle}】`;
      }

      return '文件';
    },
    // 是否禁用
    disabled() {
      return this.isDisabled;
    }
  },
  destroyed() {
    this.setTimeoutTimer && clearTimeout(this.setTimeoutTimer);
  },
  methods: {
    /**
     * PDF文件上传预处理
     */
    handleRocPdfFileUploadBeforeUpload(file) {
      if (file.type.indexOf('application/pdf') === -1) {
        this.$refs.rocPdfFileUploadRef.clearFiles();
        this.msgError(`${this.fileTitle}格式错误，请上传类型格式为PDF的文件！`);
        return;
      }
    },
    /**
     * PDF文件上传成功处理
     */
    handleRocPdfFileUploadOnsuccess(response, file, fileList) {
      // 校验封面图片是否上传成功
      if (response.code !== 200) {
        this.$refs.rocPdfFileUploadRef?.clearFiles?.();
        this.isSelect = false;
        this.isUploadSuccess = false;
        this.msgError(`上传PDF${this.fileTitle}失败，请重新选择PDF文件上传！`);
        return;
      }

      let successUrl = `${window.origin}${process.env.VUE_APP_FILE_VIEW_API}${response?.data?.url}`;

      // 绑定封面图片数据
      this.successUrl = successUrl;

      // PDF文件上传成功数据对象
      this.successResp = {
        ...response?.data,
        successUrl: successUrl
      };

      this.$emit('input', response?.data?.url);
      this.isUploadSuccess = true;
      this.$alert(`PDF${this.fileTitle}上传成功！`, '上传结果', { dangerouslyUseHTMLString: true, type: 'success' });
    },
    /**
     * PDF文件状态改变
     */
    handleRocPdfFileUploadOnchange(file, fileList) {
      if (file.status === 'ready') {
        if (((file.raw || {}).type || '').indexOf('application/pdf') === -1) {
          this.$refs.rocPdfFileUploadRef.clearFiles();
          this.isSelect = false;
          this.msgError(`${this.fileTitle}格式错误，请上传类型格式为PDF的文件！`);
          return;
        }
        this.isSelect = true;
        this.isUploadSuccess = false;
        // this.$emit('input', 'ROCPDFUPLOADSELECT');
      } else if (file.status === 'success') {
        this.isUploadSuccess = true;
      } else {
        this.isUploadSuccess = false;
        this.isSelect = false;
        // this.$emit('input', 'ROCPDFUPLOADSELECT');
      }
    },
    /**
     * PDF文件列表移除文件时的钩子
     */
    handleRocPdfFileUploadOnRemove(file, fileList) {
      this.removeLoading = true;
      this.setTimeoutTimer = setTimeout(() => {
        this.successResp = {};
        this.successUrl = '';
        this.isUploadSuccess = false;
        this.isSelect = false;
        this.$emit('input', '');
        this.setTimeoutTimer && clearTimeout(this.setTimeoutTimer);
        this.removeLoading = false;
      }, 900);
    },
    /**
     * PDF文件超出个数限制时的钩子
     */
    handleRocPdfFileUploadOnExceed(files, fileList) {
      this.msgWarning(`只允许上传单个PDF${this.fileTitle}`);
    },
    /**
     * 提交上传相关材料PDF文件
     */
    submitRocPdfFileUploadClick() {
      if (!this.isSelect) { return; }
      this.$confirm(`确定上传PDF${this.fileTitle}操作吗？`, '提示', {
        confirmButtonText: '确定 ',
        cancelButtonText: '取消 ',
        type: 'info'
      }).then(() => {
        this.$refs.rocPdfFileUploadRef?.submit?.();
      }).catch(() => {
        this.msgInfo('您已取消上传操作！');
      });
    },
    /**
     * 移除选择相关材料PDF文件
     */
    removeRocPdfFileUploadClick() {
      this.removeLoading = true;
      this.$refs.rocPdfFileUploadRef.clearFiles();
      this.setTimeoutTimer = setTimeout(() => {
        this.isSelect = false;
        this.isUploadSuccess = false;
        this.successResp = {};
        this.successUrl = '';
        this.$emit('input', '');
        this.setTimeoutTimer && clearTimeout(this.setTimeoutTimer);
        this.removeLoading = false;
      }, 1000);
    },
    /**
     * PDF文件地址单击事件
     */
    handleRocPdfFileUploadUrlClick() {
      this.pdfDialogVisible = true;
    }
  }
}
</script>

<style lang="scss">
.rocpdffileupload {
  .rocpdffileupload-attachment {
    &-fileupload {
      .el-upload {
        position: relative;
        overflow: hidden;
        width: 100%;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;

        &:hover {
          border-color: #409eff;
        }
      }

      .el-upload-list.el-upload-list--text {
        .el-upload-list__item:first-child {
          margin-top: 0;
        }
      }

      &-content {
        width: 100%;
        height: 32px;
        font-size: 14px;
        font-weight: 400;
        color: #8c939d;
        text-align: center;
      }

      &.is-disabled {
        .el-upload {
          position: relative;
          overflow: hidden;
          width: 100%;
          background-color: #f5f7fa;
          border: 1px dashed #dfe4ed;
          border-radius: 6px;
          cursor: not-allowed;

          &:hover {
            border-color: #dfe4ed;
          }

          .rocpdffileupload-attachment-fileupload-content {
            color: #c0c4cc;
          }
        }
      }
    }

    &-addr {
      width: 100%;
      padding: 5px 0;

      div {
        &:first-child,
        &:last-child {
          margin-left: 4px;
          width: 100%;
          height: 20px;
          vertical-align: middle;
          font-size: 14px;
          font-weight: 400;
          color: #606266;
          line-height: 20px;
        }

        &:last-child {
          height: 25px;
          line-height: 25px;
          cursor: pointer;
          opacity: 0.8;

          &:hover {
            color: #409eff;
            text-decoration: underline;
          }
        }
      }
    }
  }
}
</style>