<template>
  <el-row class="el-upload-self">
    <el-upload
      ref="upload"
      :multiple="multiple"
      class="avatar-uploader"
      :action="action"
      :headers="headers"
      :list-type="listType"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
      :before-remove="beforeRemove"
      :file-list="fileList"
      :show-file-list="showFileList"
      :accept="accept"
      :limit="limit"
      :drag="drag"
      :disabled="disabled"
    >
      <!-- :http-request="handleUpload" -->
      <template v-if="drag">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
      </template>
      <template v-else-if="listType === 'picture-card'">
        <i class="el-icon-plus"></i>
      </template>

      <template v-else>
        <!-- <el-button size="middle" :type="btnType">点击上传</el-button> -->
        <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar" /> -->
        <i class="el-icon-plus avatar-uploader-icon"></i>
      </template>
      <div slot="tip" class="el-upload__tip">{{ tip }}</div>
    </el-upload>

    <el-image
      ref="image"
      style="display: none"
      :src="imgUrl"
      :preview-src-list="previewList"
    ></el-image>
  </el-row>
</template>

<script>
import { getAccessToken } from "@/utils/accessToken"
import { delFile } from "@/api/file"
export default {
  name: "ElUploadSelf",
  props: {
    accept: { type: String, default: "image/*" },
    disabled: {
      type: Boolean,
      default: false,
    },
    prop: {},
    uploadQuery: {
      type: Object,
      default: () => {
        return {}
      },
    }, //后端上传文件路径（参数）
    listType: String,
    tip: String,
    multiple: Boolean,
    limit: {
      type: Number,
      default: 9,
    },
    fileSize: Number,
    loadText: String,
    showFileList: {
      type: Boolean,
      default: true,
    },
    drag: {
      type: Boolean,
      default: false,
    },
    btnType: {
      type: String,
      default: "primary",
    },
    value: Array, //上传文件数组 绑定数组
  },
  data() {
    return {
      imgUrl: "",
      title: "",
      httpPrefix:
        process.env.NODE_ENV === "development"
          ? "/api"
          : process.env.VUE_APP_BASE_API,
      fileList: [],
      uploadPrefix: process.env.VUE_APP_UPLOAD_API,
    }
  },
  computed: {
    headers() {
      return {
        Authorization: `Bearer ${getAccessToken()}`,
      }
    },
    action() {
      return (
        this.httpPrefix +
        `/disease-data/file/upload?formId=${this.uploadQuery.formId}&patientId=${this.uploadQuery.patientId}&prefix=${this.uploadQuery.prefix}`
      )
    },
    // 预览list
    previewList() {
      if (!this.value) return []
      return this.value.map((_) => {
        return (
          _.url ||
          this.uploadPrefix + `${_.bucket_name}/${_.prefix}-${_.uuid_name}`
        )
      })
    },
  },
  watch: {
    value: {
      handler(newValue, oldValue) {
        // console.log(this.value)
        if (newValue === oldValue) return
        this.fileList = newValue.map((_) => {
          return {
            name: _.file_name,
            url:
              this.uploadPrefix + `${_.bucket_name}/${_.prefix}-${_.uuid_name}`,
          }
        })
      },
      immediate: true,
    },
  },
  methods: {
    // 自定义上传方法
    // handleUpload(param) {
    //   let formData = new FormData()
    //   fd.append("file", param.file) //传文件
    //   fd.append("formld", this.formld) //传formld
    //   // ajax.axiosPost(
    //   //   url, //接口地址
    //   //   fd, //formdata对象参数
    //   //   (res) => {
    //   //     console.log(res)
    //   //   }
    //   // )
    // },
    // 上传前回调
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        const size = this.fileSize
        if (size && file.size > size) {
          this.$message.error("大小超出限制" + this.tip)
          reject()
        }
        resolve()
      })
    },

    // 超出限制
    handleExceed(files, fileList) {
      this.$message.error(`最多可上传${this.limit}个文件！`)
    },

    // 上传成功
    handleSuccess(res, file, fileList) {
      const { data } = res
      if (data) {
        this.value.push({ ...data })
        this.$emit("validUpload", this.prop)
      } else {
        this.$message.warning(res.msg)
        this.$refs.upload.clearFiles()
      }
    },

    // 移除提醒
    beforeRemove(file, fileList) {
      // console.log(file, fileList)
      return this.$confirm(
        `确定移除 ${file.file_name || file.name || "该照片"}？`
      )
    },

    // 移除
    handleRemove({ uuid_name }, fileList) {
      const i = this.value.findIndex((_) => uuid_name == _.uuidName)
      if (i > -1) this.value.splice(i, 1)
      console.log("删了", this.value)
    },

    // 查看/下载
    handlePreview(file) {
      const name = file.fileName || file.name
      this.title = name
      let responseUrl
      if (file.response) {
        const _ = file.response.data
        responseUrl =
          this.uploadPrefix + `${_.bucket_name}/${_.prefix}-${_.uuid_name}`
      }
      try {
        if (name.match(/\.(PNG|png|jpg|JPG|jpeg|JPEG)/)) {
          this.imgUrl = file.url || responseUrl
          this.$refs.image.clickHandler()
        } else {
          const elink = document.createElement("a")
          elink.download = name
          elink.style.display = "none"
          elink.href = file.url || responseUrl
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        }
      } catch {
        const elink = document.createElement("a")
        elink.download = name
        elink.style.display = "none"
        elink.href = file.url || responseUrl
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      }
    },
  },
}
</script>
<style lang="scss">
.el-upload-self {
  .el-upload {
    position: relative;
  }
}
</style>

<style lang="scss" scoped>
.el-upload-self {
  font-size: 14px;
}
.avatar-uploader {
  display: flex;
  align-items: center;
}
::v-deep .avatar-uploader .el-upload {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .el-upload-list {
  display: flex;
  align-items: center;
  transform: translateY(4px);
}
::v-deep .el-upload--picture-card {
  width: 88px;
  height: 88px;
  line-height: 88px;
}
::v-deep .el-upload-list__item {
  width: 88px;
  height: 88px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 88px;
  height: 88px;
  line-height: 88px;
  text-align: center;
}
.avatar {
  width: 88px;
  height: 88px;
  display: block;
}
</style>
