<template>
  <div class="upload-file">
    <el-upload
      multiple
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :headers="headers"
      class="h5-upload-box"
      ref="fileUpload"
      v-if="uploadType==0"
    >
      <!-- 上传提示
      <div class="tips" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize"> 大小不超过 <b>{{ fileSize }}MB</b></template>
        <template v-if="fileType"> 格式为 <b>{{ fileType.join("/") }}</b></template>
        的文件
      </div>-->
      <!-- 上传按钮 -->
      <el-button class="add-upload" icon="el-icon-plus" v-if="showUploadBtn">选取文件</el-button>
    </el-upload>
    <div class="h5-upload-box" v-if="uploadType>0 && showUploadBtn" @click="appUpload">
      <div class="el-upload el-upload--text">
        <el-button class="add-upload" icon="el-icon-plus">选取文件</el-button>
      </div>
    </div>


    <!-- 文件列表 -->
    <transition-group class="h5-upload-list upload-file-list el-upload-list el-upload-list--text"
                      name="el-fade-in-linear" tag="ul">
      <li v-for="(file, index) in fileList" :key="index" class="el-upload-list__item ele-upload-list__item-content">
        <!-- <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
        </el-link> -->
        <img
          :src="getShowUrl(file)"
          class="el-upload-list__item-thumbnail"
          @click="baseFilePreview(fileList,index)"
        />
        <span class="el-icon-document" @click="filePreview(file)"> {{ getAttachmentName(file) }} </span>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger"><i class="el-icon-close"></i></el-link>
        </div>
      </li>
    </transition-group>

    <!-- 附件预览 -->
    <!--    <full-screen-dialog  ref="fileDialog" v-model="fileDialogVisible"></full-screen-dialog>-->
    <div class="pop-box" v-if="showPreviewDialog">
      <div>
        <div class="header-box">
          <i class="back el-icon-close" @click="showPreviewDialog=false"></i>文件预览
        </div>
        <el-form label-position="top" class="form-box">
          <div class="flex">
            <div class="tit"><span>{{ prevewFileName }}</span></div>
            <iframe style="width: 100%;flex:1" :src="prevewFileUrl"></iframe>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import {getToken} from "../../../utils/auth";
import Vue from "vue";
import ElImageViewer from '../../../components/VabUpload/image-viewer'

let typeList = [
  "doc", "docx", "xls", "xlsx", "ppt", "pptx", "csv",
  "wps", "dps", "et", "ett", "wpt",
  "vsd", "vsdx",
  "wmf", "emf",
  "psd", "eps",
  "pdf",
  "xmind",
  "obj", "3ds", "stl", "ply", "gltf", "glb", "off", "3dm", "fbx", "dae", "wrl", "3mf", "ifc", "brep", "step", "iges", "fcstd", "bim",
  "dwg", "dxf", "dwf", "iges", "igs", "dwt", "dng", "ifc", "dwfx", "stl", "cf2", "plt",
  "txt", "xml", "md", "java", "php", "py", "js", "css",
  "zip", "rar", "jar", "tar", "gzip", "7z",
  "mp3", "wav", "mp4", "flv",
  "avi", "rm", "mkv", "mpeg", "mpg", "rmvb", "wmv", "3gp", "swf",
  "drawio",
  "tif", "tiff", "jfif", "webp", "tga", "svg"
];
let imgType = [
  "jpg",
  "jpeg",
  "png",
  "gif",
  "bmp",
  "mpg"
];
let allFileType = [...typeList, ...imgType]
window.fileUpload = function (fileName, url, suffix, fileJson, param) {
  // let that = window.currentFileTarget;
  let uuid = param?.uuid;
  let that = uuid ? window.mobileFileRefMap[uuid] : window.currentFileTarget;
  that.number++;
  that.uploadList.push({name: fileName, ...fileJson});
  that.uploadedSuccessfully();
  return fileJson;
}
export default {
  components: {
  },
  name: "FileUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 10,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 50,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => allFileType,
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    dataType: String
  },
  data() {
    return {
      prevewFileUrl: null,
      prevewFileName: null,
      showPreviewDialog: false,

      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      loadingObj: null,
      uuid: null,
      uploadType: 0//普通上传,1安卓APP 2苹果APP
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          this.fileList = !this.dataType ? val : [val]
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
    showUploadBtn() {
      let res = true;
      if (this.dataType) {
        res = this.fileList.length == 0;
      }
      return res;
    }
  },
  created() {
    this.init();
  },
  methods: {
    appUpload() {
      let param = JSON.stringify({
        uuid: this.uuid,
      })
      if (this.uploadType == 1) {
        window.Android.gettwImage(param); //test安卓中定义好的方法,data字符串数据
      } else if (this.uploadType == 2) {
        window.webkit.messageHandlers.gettwImage.postMessage(param); //test安卓中定义好的方法,data字符串数据
      }
    },
    initUploadType() {
      /*js 判断是安卓系统还是苹果系统*/
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      var data = '';
      if (isAndroid) {
        /*安卓系统*/
        if (window?.Android?.gettwImage) {
          this.uploadType = 1;
        }
      }

      if (isiOS) {
        /*苹果系统*/
        if (window?.webkit?.messageHandlers?.gettwImage?.postMessage) {
          this.uploadType = 2;
        }
      }
    },
    init() {
      this.initUploadType();
      let uuid = this.getUUID();
      if (window.mobileFileRefMap) {
        window.mobileFileRefMap[uuid] = this;
      } else {
        let mobileFileRefMap = {};
        mobileFileRefMap[uuid] = this;
        window.mobileFileRefMap = mobileFileRefMap;
      }
      window.currentFileTarget = this;
      this.uuid = uuid;
    },
    getUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
      })
    },
    getShowUrl(attachment, field) {
      let showUrl = null;
      let typeStr = Object.prototype.toString.call(attachment);
      if (typeStr == '[object Object]') {
        let showField = field ? field : 'medium';
        let fullUrl = attachment.domain + (attachment[showField] ? attachment[showField] : attachment.url);
        showUrl = this.$commonFileUtil.getShowUrl(fullUrl)
      } else {
        showUrl = this.$commonFileUtil.getShowUrl(attachment)
      }
      return showUrl;
    },
    // 上传前校检格式和大小
    async handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name;
        let fileExt = this.$commonFileUtil.getFileSuffix(fileName);
        const isTypeOk = this.fileType.includes(fileExt);
        if (!isTypeOk) {
          this.$baseAlert(`文件格式不正确`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$baseAlert(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      // this.$modal.loading("正在上传文件，请稍候...");
      this.loadingObj = this.$baseLoading({
        target: document.body
      });
      this.number++;
      let mineUploadUrl = window.BASE_FILEURL;
      return await this.$http({
        url: mineUploadUrl,
        method: 'post',
        data: {
          isAuth: false
        },
        success: res => {
          this.uploadFileUrl = res.objx;
          // callback && callback()
        }
      });
      // return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$baseAlert(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$baseAlert("上传文件失败，请重试");
      // this.$modal.closeLoading()
      this.loadingObj && this.loadingObj.close();
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      console.log(res, 'res');
      if (res.type === 'success') {
        this.uploadList.push({name: file.name, ...res.objx});
        this.uploadedSuccessfully();
      } else {
        this.number--;
        // this.$modal.closeLoading();
        this.loadingObj && this.loadingObj.close();
        this.$baseAlert(res.content);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.syncUpdateValue();
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        if (!this.dataType) {
          this.fileList = this.fileList.concat(this.uploadList);
        } else {
          if (this.uploadList.length) {
            let file = this.uploadList[0];
            let fileUrl = file.domain + file[this.dataType];
            // this.fileList = [fileUrl]
            this.fileList.splice(0, this.fileList.length)
            this.fileList.push(fileUrl)
          }
        }

        this.uploadList = [];
        this.number = 0;
        // this.$emit("input", this.fileList);
        this.syncUpdateValue();

        // this.$modal.closeLoading();
        this.loadingObj && this.loadingObj.close();
      }
    },
    syncUpdateValue() {
      let fileList = this.fileList;
      let value;
      if (!this.dataType) {
        value = fileList;
      } else {
        value = fileList.length ? fileList[0] : null;
      }
      this.$emit("input", value);
    },
    // 附件查看
    filePreview(e) {
      if (e.response?.data.length) {
        this.$refs.fileDialog.openDialog(e.response.data[0].id);
      } else {
        this.$refs.fileDialog.openDialog(e.id);
      }
    },
    async openFilePreview() {

      var filePath;
      var opts;
      if (typeof arguments[0] === 'string') {
        filePath = arguments[0];
      } else {
        let attachment = arguments[0];
        filePath = attachment.domain + attachment.url;
      }
      let prevewFileName = this.getAttachmentName(arguments[0]);
      let fileSuffix = this.$commonFileUtil.getFileSuffix(filePath);
      if (!typeList.includes(fileSuffix)) {
        return;
      }

      await this.$http({
        url: USER_PREFIX + '/sf_common/getFilePreviewUrl',
        method: `post`,
        data: {
          url: filePath
        },
        isLoading: true,
        success: res => {
          if (res.objx) {
            // window.open(res.objx);
            this.prevewFileUrl = res.objx;
            this.prevewFileName = prevewFileName;
            this.showPreviewDialog = true;
          }
        }
      });
    },
    baseFilePreview(attachment, index) {
      let that = this;
      let openImagePreView = function (attachments, index) {
        let pictureIndex = -1;
        let pictureDtoList = [];
        index = index || 0;
        attachments.forEach((item, i) => {
          let typeStr = Object.prototype.toString.call(item);
          if (typeStr == '[object Object]') {
            if (that.$commonFileUtil.isPictureFile(item.url)) {
              if (i <= index) {
                pictureIndex++;
              }
              pictureDtoList.push(item.domain + item.url);
            }
          } else {
            if (that.$commonFileUtil.isPictureFile(item)) {
              if (i <= index) {
                pictureIndex++;
              }
              pictureDtoList.push(item);
            }
          }
        });

        let a = Vue.extend(ElImageViewer);
        let instance = new a({
          propsData: {
            onClose: () => {
              dom.remove();
            },
            initialIndex: pictureIndex,
            urlList: pictureDtoList
          }
        });
        let dom = instance.$mount().$el;
        document.body.append(dom);
      };
      let openPreview = function (attachment, index) {
        if (Array.isArray(attachment)) {
          let currentFile = attachment[index];
          let typeStr = Object.prototype.toString.call(currentFile);
          let url = typeStr == '[object Object]' ? (currentFile.domain + currentFile.url) : currentFile;
          if (that.$commonFileUtil.isPictureFile(url)) {
            openImagePreView(attachment, index);
          } else if (that.$commonFileUtil.isPreviewFile(url)) {
            that.openFilePreview(url)
          }
        } else {
          let typeStr = Object.prototype.toString.call(attachment);
          let url = typeStr == '[object Object]' ? (attachment.domain + attachment.url) : attachment;
          if (that.$commonFileUtil.isPictureFile(url)) {
            openImagePreView([url], 0);
          } else if (that.$commonFileUtil.isPreviewFile(url)) {
            that.openFilePreview(url)
          }
        }
      };
      openPreview(attachment, index);
    },
    getAttachmentName(attachment) {
      let name = null;
      let typeStr = Object.prototype.toString.call(attachment);
      if (typeStr == '[object Object]') {
        name = attachment.name;
      } else {
        let url = attachment;
        if (url) {
          var i = url.lastIndexOf("/");
          if (i >= 0) {
            name = url.substring(i + 1, url.length);
          }
        }
      }
      return name;
    },

  }
};
</script>

