<template>
  <div>
    <el-upload
      v-if="isUpload"
      ref="my-upload"
      action="#"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleChange"
      :drag="!$slots.default"
      multiple
      :accept="calcFileType"
    >
      <div style="width: 100%">
        <slot v-if="$slots.default" />
        <div class="upload-demo" style="width: 400px" v-else>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            {{ $t("将文件拖到此处，或") + " " }}<em>{{ $t("点击上传") }}</em>
          </div>
        </div>
      </div>
    </el-upload>
    <div
      class="progress_panel"
      v-for="file in filelist"
      :key="file.uid || file.attachmentid"
    >
      <img
        v-if="file.type === 'doc' || file.type === 'docx'"
        width="30"
        src="../../../assets/file_icons/word.png"
        alt=""
      />
      <img
        v-else-if="file.type === 'pdf'"
        width="30"
        src="../../../assets/file_icons/PDF.png"
        alt=""
      />
      <img
        v-else-if="file.type === 'mp4' || file.type === 'avi'"
        width="30"
        src="../../../assets/file_icons/video.png"
        alt=""
      />
      <img
        v-else-if="file.type === 'xls' || file.type === 'xlsx'"
        width="30"
        src="../../../assets/file_icons/excel.png"
        alt=""
      />
      <img
        v-else-if="file.type === 'ppt' || file.type === 'pptx'"
        width="30"
        src="../../../assets/file_icons/PPT.png"
        alt=""
      />
      <span
        v-else-if="
          ['jpg', 'png', 'jpeg', 'bmp', 'gif', 'webp', 'svg', 'tiff'].includes(
            file.type
          )
        "
      >
        <el-image
          v-if="file.url"
          style="width: 30px; height: 30px"
          :src="file.url"
          fit="fit"
        ></el-image>
        <img
          v-else
          width="30"
          src="../../../assets/file_icons/image.png"
          alt=""
        />
      </span>
      <img
        v-else
        width="30"
        src="../../../assets/file_icons/unknow.png"
        alt=""
      />
      <div>
        <div style="display: flex; margin-bottom: 6px; width: 90%">
          <p>{{ file.name || file.document || $t("未命名文件") }}</p>
          <span
            v-if="file.attachmentid"
            style="color: #67c23a; margin-left: 4px"
            >●</span
          >
        </div>
        <el-progress
          :percentage="file.progress"
          :show-text="false"
        ></el-progress>
      </div>
      <el-popconfirm
        :title="$t('是否确定删除') + '?'"
        @confirm="deleteFile(file)"
        v-if="isDelete && file.attachmentid"
      >
        <el-button slot="reference" type="text" class="icon iconfont"
          >&#xe688;</el-button
        >
      </el-popconfirm>
    </div>
  </div>
</template>

<script>
import { Message } from "element-ui";
export default {
  name: "upload",
  data() {
    return {
      filelist: [],
      loading: false,
      linksids: [],
    };
  },
  watch: {
    loading(newCount) {
      this.$emit("oploadIng", newCount);
    },
  },
  props: {
    classType: {
      type: Array,
      default: () => {
        return [];
      },
    },
    ownertable: {
      type: String,
      default: "temporary",
    },
    ownerid: {
      type: [String, Number],
      default: (Date.now() / 99 / 45).toFixed(0),
    },
    usetype: {
      type: String,
      default: "default",
    },
    isDelete: {
      type: Boolean,
      default: true,
    },
    isUpload: {
      type: Boolean,
      default: true,
    },
    oploadIng: {
      type: Function,
    },
  },
  computed: {
    calcFileType() {
      if (this.classType.length == 0) return "";
      let obj = {
        image: ".jpg,.png,.jpg,.jpeg,.bmp,.gif,.webp,.svg,.tiff",
        video: ".mp4,.ogg,.webm",
        document: ".txt,.doc,.docx,.xls,.xlsx,.ppt,.pptx",
        pdf: ".pdf",
      };
      return this.classType.map((v) => (obj[v] ? obj[v] : v)).join(",");
    },
  },
  methods: {
    handleChange(file, filelist) {
      this.$set(this.filelist, this.filelist.length, file);
      this.loading = true;
      let filename = file.raw.name,
        filetype = file.name.substr(file.raw.name.lastIndexOf(".") + 1);
      this.$api
        .requested({
          classname: "system.attachment.huawei.OBS",
          method: "getFileName",
          content: {
            filename,
            filetype,
            parentid: JSON.parse(sessionStorage.getItem("folderid"))
              .appfolderid,
          },
        })
        .then((res) => {
          console.log("获取上传地址", res);
          if (res.code == 0) return this.failUpload(res, file);
          this.upoladFileToServer(
            res.data.uploadurl,
            file,
            filetype,
            res.data.serialfilename
          );
        });
    },
    // 上传到华为云
    async upoladFileToServer(url, file, ext, obsfilename) {
      let that = this,
        item = this.filelist.find((v) => v.uid === file.uid);
        console.log("itemitem",item)
      let config = {
        headers:
          ext === "pdf"
            ? { "Content-Type": "application/pdf" }
            : { "Content-Type": "application/octet-stream" },
        onUploadProgress: function (progressEvent) {
          let percent = (progressEvent.loaded / progressEvent.total) * 100;
          that.$set(item, "type", ext);
          that.$set(item, "progress", percent);
        },
      };
      const res = await this.$upload.hw_upload(url, file.raw, config);
      if (res.code == 0) return this.failUpload(res, file);
      console.log("上传到华为云", res);
      this.createFileRecord(obsfilename, file);
    },
    // 上传成功以后生成附件记录
    async createFileRecord(obsfilename, file) {
      this.$api
        .requested({
          classname: "system.attachment.huawei.OBS",
          method: "uploadSuccess",
          content: {
            serialfilename: obsfilename,
            ownertable: this.ownertable,
            ownerid: this.ownerid,
            usetype: this.usetype,
          },
        })
        .then((res) => {
          console.log("res", res, file);
          if (res.code == 0) return this.failUpload(res, file);
          let data = JSON.parse(res.attinfos).data,
            index = this.filelist.findIndex((v) => v.uid == file.uid),
            attachmentid = res.data.attachmentids[0],
            item = data.find((v) => v.attachmentid == attachmentid);
          console.log(item);
          console.log("this.filelist",this.filelist)
          delete file.row;
          this.$set(
            this.filelist,
            index,
            Object.assign(this.filelist[index], item)
          );
          console.log("this.filelist",this.filelist)
          this.loading = this.filelist.some((v) => v.row);
          this.filelist = this.filelist;
        });
    },
    failUpload(res, file) {
      console.log("失败",res)
      Message.error(file.name + res.msg);
      this.filelist = this.filelist.filter((v) => v.uid !== file.uid);
      this.loading = this.filelist.some((v) => v.row);
    },
    deleteFile(e) {
      if (e.ownertable == "temporary") {
        this.$api
          .requested({
            classname: "system.attachment.Attachment",
            method: "deleteFileLink",
            content: {
              linksids: [e.linksid],
            },
          })
          .then((res) => {
            console.log("删除临时文件", res);
            this.filelist = this.filelist.filter((v) => v.uid !== e.uid);
            this.loading = this.filelist.some((v) => v.row);
          });
      } else {
        this.filelist = this.filelist.filter((v) => v.uid !== e.uid);
        this.loading = this.filelist.some((v) => v.row);
        this.linksids.push(e.linksid);
      }
    },
    rebinding(ownertable, ownerid, usetype = "default") {
      return new Promise((resolve, reject) => {
        if (this.filelist.length == 0) return resolve(true);
        this.$api
          .requested({
            classname: "system.attachment.Attachment",
            method: "createFileLink",
            content: {
              ownertable,
              ownerid,
              usetype,
              attachmentids: this.filelist.map((v) => v.attachmentid),
            },
          })
          .then((res) => {
            resolve(res.code == 1);
            console.log("改绑", res);
          });
      });
    },
    deleteAllTemporaryFiles(list = []) {
      return new Promise((resolve, reject) => {
        let linksids = list
          ? list
          : this.filelist
              .filter((v) => v.ownertable == "temporary")
              .map((v) => v.linksid);
        if (linksids.length == 0) return resolve(true);
        this.$api
          .requested({
            classname: "system.attachment.Attachment",
            method: "deleteFileLink",
            content: {
              linksids,
            },
          })
          .then((res) => {
            resolve(res.code == 1);
            this.filelist = this.filelist.filter(
              (v) => v.ownertable != "temporary"
            );
            console.log("删除所有临时文件", res);
          });
      });
    },
  },
};
</script>
<style>
.upload-demo > div {
  width: 100% !important;
}
.upload-demo .el-upload-dragger {
  width: 100% !important;
}
</style>
<style scoped>
.progress_panel {
  position: relative;
  display: flex;
  align-items: center;
  padding: 10px;
  margin: 10px 0;
  border-radius: 5px;
  transition: linear 0.2s all;
  overflow: hidden;
}
.progress_panel:hover {
  box-shadow: 0px 0px 5px #ccc;
}
.progress_panel > div {
  flex: 1;
  padding: 0 10px;
}
.progress_panel > div > p {
  line-height: 30px;
}
.upload .el-button {
  width: 100%;
}

.progress_panel .icon {
  position: absolute;
  color: #999;
  top: 0;
  right: 0;
  font-size: 14px;
  padding: 4px 8px;
  opacity: 0;
  user-select: none;
}

.progress_panel .icon:hover {
  color: #333;
}

.progress_panel:hover .icon {
  opacity: 1;
}
</style>

