<!--单图上传组件/按钮-->
<template>
  <div :class="fitWidth ? 'upload-container-fit' : 'upload-container'">
    <el-upload name="avatar"
               action="#"
               :http-request="myUpload"
               :multiple="false"
               :show-file-list="false"
               :before-upload="beforeUpload"
               :on-success="handleUploadSuccess"
               :on-error="handleUploadError"
               :drag="drag"
               with-credentials
               :class="uploadClass">
      <!-- <div v-if="!drag && !preview">
        <el-button v-if="imageUrl"
                   size="small"
                   type="success">已上传，可点击修改</el-button>
        <el-button size="small"
                   type="primary"
                   v-else><i class="el-icon-upload el-icon--left"></i>点击上传</el-button>
      </div> -->
      <div v-if="drag && !preview">
        <i class="el-icon-upload"
           v-if="!imageUrl" />
        <div class="el-upload__text"
             v-if="!imageUrl">
          <em>点击上传</em>
        </div>
        <div v-if="drag && imageUrl"
             class="el-upload-list el-upload-list--picture-card">
          <div class="el-upload-list__item is-success">
            <img :src="imageUrl"
                 alt=""
                 class="el-upload-list__item-thumbnail" />
            <label class="el-upload-list__item-status-label">
              <i class="el-icon-upload-success el-icon-check"></i>
            </label>
            <i class="el-icon-close"></i>
            <i class="el-icon-close-tip">按 delete 键可删除</i>
            <span class="el-upload-list__item-actions">
              <!-- <span class="el-upload-list__item-preview">
                <i class="el-icon-zoom-in"
                   @click.stop="handlePreview"></i>
              </span> -->
              <span class="el-upload-list__item-delete">
                <i class="el-icon-delete"
                   @click.stop="removeImage"></i>
              </span>
            </span>
          </div>
        </div>
        <!-- <img width="100%"
             height="auto"
             v-else
             :src="imageUrl"
             alt="" /> -->
      </div>

    </el-upload>
    <!-- <el-dialog :visible.sync="dialogVisible"
               :append-to-body="true"
               :modal-append-to-body="false"
               :width="dialogWidth"
               class="preview-dialog">
      <img width="100%"
           :src="imageUrl"
           alt="" />
    </el-dialog> -->
    <!-- <div v-if="!drag && imageUrl"
         class="el-upload-list el-upload-list--text">
      <div class="el-upload-list__item is-success">
        <a class="el-upload-list__item-name"
           @click="handlePreview">
          <i class="el-icon-picture"></i>点此处预览</a>
        <label class="el-upload-list__item-status-label">
          <i class="el-icon-upload-success el-icon-circle-check"
             v-if="!preview"></i>
        </label>
        <i class="el-icon-close"
           v-if="!preview"
           @click="removeImage"></i>
      </div>
    </div> -->
    <div class="el-upload__tip"
         slot="tip"
         v-if="!preview && isShowTip">
      <span v-if="limitWidth > 0 && limitHeight > 0">
        注：图片规格{{limitWidth}}*{{limitHeight}},
      </span>
      <span>
        格式限{{limitTypeString}},大小不超过{{limitKbString}}
      </span>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import util from "@/libs/util";
import { uploadImg } from "@/libs/common/constant";
export default {
  name: "single-upload",
  props: {
    warnImageTypeTitle: {
      type: String,
      default: "",
    }, // 上传图片格式提示文本
    warnImageType: {
      type: Boolean,
      default: false,
    }, // 是否使用默认上传图片格式提示
    value: {
      type: String,
      default: "",
    },
    drag: {
      type: Boolean,
      default: false,
    },
    preview: {
      type: Boolean,
      default: false,
    },
    isShowTip: {
      type: Boolean,
      default: true,
    },
    fitWidth: {
      type: Boolean,
      default: false,
    },
    imgHidth: {
      type: Number,
    },
    imgWidth: {
      type: Number,
    },
    dialogWidth: {
      type: String,
      default: "35%",
    },
    preiview: {
      type: Boolean,
      default: false,
    },
    limitTypeList: {
      type: Array,
      default: () => ["image/jpg", "image/png", "image/jpeg"],
    },
    limitKb: {
      type: Number,
      default: 2048,
    },
    limitWidth: {
      type: Number,
      default: 0,
    },
    limitHeight: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      dialogVisible: false,
      currentSize: 0,
    };
  },
  computed: {
    uploadUrl() {
      // const url = process.env.VUE_APP_API + 'mainManage/upload/img/one'
      return uploadImg.url;
    },
    imageUrl() {
      // return this.value ? process.env.VUE_APP_BASE_API + this.value : ''
      return this.value;
    },
    uploadClass() {
      return this.drag ? "image-uploader" : "";
    },
    // 限制图片
    limitTypeString() {
      let string = "";
      this.limitTypeList.map((item) => {
        string += item.replace("image/", "") + "/";
      });
      return string.substring(0, string.length - 1);
    },
    limitKbString() {
      let string = "";
      if (this.limitKb / 1024 >= 1) {
        string = this.limitKb / 1024 + "M";
      } else {
        string = this.limitKb + "KB";
      }
      return string;
    },
  },
  methods: {
    myUpload(params) {
      // 构建FormData对象
      const data = new FormData();
      data.append("file", params.file);
      axios({
        headers: {
          "Content-Type": "multipart/form-data",
          token: util.cookies.get("token"),
        },
        method: "POST",
        // url: process.env.VUE_APP_API + 'provider/upload/img/one',
        url: uploadImg.url,
        data: data,
      })
        .then((res) => {
          console.log(res, "上传了吗");
          this.handleUploadSuccess(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    removeImage(e) {
      this.$confirm("确定移除已上传的图片？", "提示").then(() => {
        this.emitInput("");
      });
    },
    emitInput(val) {
      console.log(val, "val");
      this.$emit("input", val);
    },
    handleUploadSuccess(response) {
      this.emitInput(response.data.data.urlPath);
      this.$emit("getCurrentSize", this.currentSize);
    },
    handleUploadError(err) {
      this.$message.error(err.message);
    },
    handleUploadRemove() {
      this.emitInput("");
    },
    beforeUpload(file) {
      const typeList = this.limitTypeList;
      const isTypeValid = typeList.includes(file.type);
      const isLtKb = file.size / 1024 < this.limitKb;
      const limitWidth = this.limitWidth;
      const limitHeight = this.limitHeight;
      this.currentSize = file.size / 1024;
      if (!isTypeValid) {
        if (this.warnImageType) {
          this.$message.error(this.warnImageTypeTitle);
        } else {
          const limitTypeList = this.limitTypeList;
          const imageFormat = [];
          // for (const i in limitTypeList) {
          //   if (limitTypeList[i] === 'image/jpeg') {
          //     imageFormat.push('jpeg')
          //   } else {
          //     imageFormat.push(limitTypeList[i].substring(6))
          //   }
          // }
          for (const i in limitTypeList) {
            imageFormat.push(limitTypeList[i].substring(6));
          }
          const formatWarn = imageFormat.join("/");
          this.$message.error(`图片格式只能是 ${formatWarn} `);
        }
        return false;
      }
      if (!isLtKb) {
        this.$message.error(`图片大小不能超过 ${this.limitKbString}!`);

        return false;
      }
      if (limitWidth === 0 && limitHeight === 0) {
        return true;
      }
      const isSize = new Promise(function (resolve, reject) {
        const _URL = window.URL || window.webkitURL;
        const img = new Image();
        img.onload = function () {
          const imgWidth = img.width;
          const imgHight = img.height;
          const valid =
            imgWidth === 0
              ? true
              : imgWidth >= parseInt(limitWidth) &&
                limitHeight === 0 &&
                imgWidth === imgHight
              ? true
              : imgHight >= parseInt(limitHeight) && imgWidth === imgHight;
          valid ? resolve() : reject(new Error());
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          if (limitWidth > 0 && limitHeight > 0) {
            // this.$message.error(
            //   `图片尺寸不符合${limitWidth}*${limitHeight}标准`
            // )
            this.$message.error(`图片规格大小不符合要求`);
          } else if (limitWidth > 0 && limitHeight === 0) {
            // this.$message.error(`图片宽度不符合${limitWidth}标准`)
            this.$message.error(`图片规格大小不符合要求`);
          } else if (limitWidth === 0 && limitHeight > 0) {
            // this.$message.error(`图片高度不符合${limitHeight}标准`)
            this.$message.error(`图片规格大小不符合要求`);
          }
          return Promise.reject(new Error());
        }
      );
      return isSize;
    },
    handlePreview() {
      this.dialogVisible = true;
    },
  },
};
</script>

<style lang="scss">
.upload-container {
  position: relative;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  .image-uploader {
    width: 150px;
    margin-right: 20px;
    .el-icon-upload {
      margin: 20px 0 16px;
      font-size: 60px;
    }
    .el-upload__text {
      line-height: 20px;
      font-size: 13px;
    }
  }
  .el-upload-list--text {
    margin: 6px 0 0 10px;
  }
  .image-uploader .el-upload-dragger {
    width: 150px;
    height: 150px;
  }
  .el-upload__tip {
    margin: 0 0 0 15px;
  }
  .el-upload-list__item:first-child {
    margin: 0;
  }
}
.upload-container-fit {
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  img {
    display: block;
  }
  .image-uploader {
    width: 100%;
    display: contents;
    // margin-right: 20px;
    .el-upload {
      width: 100%;
    }
    .el-icon-upload {
      margin: 0 0 16px;
      font-size: 60px;
    }
    .el-upload__text {
      line-height: 20px;
      font-size: 13px;
    }
  }
  .el-upload-list--text {
    margin: 6px 0 0 10px;
  }
  .image-uploader .el-upload-dragger {
    width: 100%;
    height: auto;
  }
  .el-upload__tip {
    margin: 0 0 0 15px;
  }
  .el-upload-list__item:first-child {
    margin: 0;
  }
}
.preview-dialog .el-dialog__header {
  padding: 0;
}
.preview-dialog .el-dialog__body {
  padding: 20px;
}
</style>
