<template>
  <div class="ant-upload-preview">
    <div style="width: 100%">
      <el-upload
      ref="upload"
        class="avatar-uploader"
        :class="[disabled ? 'uploadDisabled' : null]"
        :disabled="disabled"
        :accept="accept"
        :show-file-list="false"
        :action="ossUploadUrl"
        :data="dataObj"
        :before-upload="beforeUpload"
        :http-request="handleChange"
      >
        <i
          v-if="isDelete && imageUrl"
          class="el-icon-error"
          @click.stop="onDelete"
          style="
            position: absolute;
            right: -14px;
            font-size: 24px;
            top: -14px;
            color: #787878;
            background: #fff;
          "
        ></i>
        <img v-if="imageUrl" :src="imageUrl" class="avatar" :style="showBox" />
        <span v-else>
          <i
            v-if="loading"
            class="el-icon-loading avatar-uploader-icon"
            :style="showBox"
          ></i>
          <i
            v-else
            class="el-icon-plus avatar-uploader-icon"
            :style="showBox"
          ></i>
          <span class="upload-desc">添加上传图片</span>
        </span>
      </el-upload>
    </div>
    <!-- modal -->
    <cropper-modal
      ref="CropperModal"
      @cropper-no="handleCropperClose"
      @cropper-ok="handleCropperSuccess"
    ></cropper-modal>
  </div>
</template>
<script>
import CropperModal from "./CropperModal";
import { policy } from "@/api/appTenant";
import axios from "axios";
export default {
  name: "ImageCropper",
  components: {
    CropperModal,
  },
  props: {
    //图片裁切配置
    options: {
      type: Object,
      default: function () {
        return {
          autoCrop: true, //是否默认生成截图框
          enlarge: 1, //  图片放大倍数
          autoCropWidth: 200, //默认生成截图框宽度
          autoCropHeight: 200, //默认生成截图框高度
          fixedBox: false, //是否固定截图框大小 不允许改变
          previewsCircle: true, //预览图是否是原圆形
          title: "上传图片",
        };
      },
    },
    // 显示图片原始图片
    showSize: {
      type: Boolean,
      default: false,
    },
    // 上传图片的大小，单位M
    imgSize: {
      type: Number,
      default: 2,
    },
    isDelete: {
      type: Boolean,
      default: false,
    },
    // 图片地址
    imageUrl: {
      type: String,
      default: "",
    },
    // 默认图片格式
    accept: {
      type: String,
      default: ".png,.jpg,.jpeg,.gif",
    },
    acceptArray: {
      type: [Array, Object],
      default() {
        return ["image/jpeg", "image/png", "image/jpg", "image/gif"];
      },
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    bucket_name: {
      type: String,
      default: "daya",
    },
  },
  data() {
    return {
      loading: false,
      isStopRun: false,
      info: null,
      ossUploadUrl: "https://ks3-cn-beijing.ksyuncs.com/" + this.bucket_name,
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        KSSAccessKeyId: "",
        // dir: "",
        acl: "public-read",
        name: "",
      },
    };
  },
  computed: {
    showBox() {
      let styleList = {};
      if (this.showSize) {
        styleList = {
          width: this.options.autoCropWidth + "px",
          height: this.options.autoCropHeight + "px",
          lineHeight: this.options.autoCropHeight + "px",
        };
      }
      console.log(styleList);
      return styleList;
    },
  },
  methods: {
    onDelete() {
      // 删除图片
      this.$emit("update:imageUrl", "");
    },
    //从本地选择文件
    async handleChange(info) {
      // 缓存原始数据信息
      this.info = info;
      if (this.isStopRun) {
        return;
      }
      this.loading = true;
      // ---

      //----
      const { options } = this;
      this.getBase64(info.file, (imageUrl) => {
        const target = Object.assign({}, options, {
          img: imageUrl,
          name: info.file.name, // 上传文件名
        });
        this.$refs.CropperModal.edit(target);
      });
    },
    // 上传之前 格式与大小校验
    beforeUpload(file) {
      this.isStopRun = false;
      var fileType = file.type;
      if (fileType.indexOf("image") < 0) {
        this.$message.warning("请上传图片");
        this.isStopRun = true;
        return false;
      }
      const isJpgOrPng = this.acceptArray.includes(file.type);
      // file.type === 'image/jpeg' ||
      // file.type === 'image/png' ||
      // file.type === 'image/jpg'
      if (!isJpgOrPng) {
        this.$message.error("你上传图片格式不正确!");
        this.isStopRun = true;
      }
      const isLtSize = file.size < this.imgSize * 1024 * 1024;
      if (!isLtSize) {
        this.$message.error("图片大小不能超过" + this.imgSize + "MB!");
        this.isStopRun = true;
      }
      return isJpgOrPng && isLtSize;
    },

    async handleCropperSuccess(data) {
      // 开始上传数据
      let { action, headers, filename } = this.info;
      let fileName = this.info.file.name.replaceAll(" ", "_");
      const formData = new FormData();
      try {
        let key = new Date().getTime() + fileName;
        let obj = {
          filename: fileName,
          bucketName: this.bucket_name,
          postData: {
            filename: fileName,
            acl: "public-read",
            key: key,
            unknowValueField: [],
          },
        };
        const res = await policy(obj);
        this.dataObj = {
          policy: res.data.policy,
          signature: res.data.signature,
          key: key,
          KSSAccessKeyId: res.data.kssAccessKeyId,
          acl: "public-read",
          name: fileName,
        };
        for (let key in this.dataObj) {
          formData.append(key, this.dataObj[key]);
        }
        formData.append(filename, data, fileName);
        console.log(this.ossUploadUrl, "this.ossUploadUrl", action);
        axios
          .post(action, formData, {
            ...headers,
          })
          .then((res) => {

            let url = this.ossUploadUrl + "/" + this.dataObj.key;

            if (url) {

              // filelist.value = [
              //   {
              //     name: url,
              //     url: url,
              //   },
              // ];

              // resValues.value = url;


              let data = {
                data: {
                  url: url,
                },
              };
                  this.loading = false;
              this.$emit("crop-upload-success", data);
              CropperModal.value.closeVisible();
            } else {
              this.handleCropperClose();
              // ElMessage.error(res.msg || '上传失败')
            }
          })
          .catch((e) => {
            // console.log(e, '失败')
            this.handleCropperClose();
          });
        //putObject
      } catch (err) {
        this.handleCropperClose();
        this.$message.error("上传失败");
      }

      //将返回的数据回显
    },
    // 取消上传
    handleCropperClose() {
      this.loading = false;
      this.$emit("crop-upload-close");
    },
    getBase64(img, callback) {
      const reader = new FileReader();
      reader.addEventListener("load", () => callback(reader.result));
      reader.readAsDataURL(img);
    },
  },
};
</script>

<style lang="scss" scoped>
.ant-upload-preview {
  background-color: #fff;
  .avatar-uploader {
    .upload-desc {
      position: absolute;
      bottom: 0;
      left: 0;
      color: #ccc;
      font-size: 8px;
      right: 0;
    }
  }
}
::v-deep .avatar-uploader .el-upload--text {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  margin-right: 20px;
  cursor: pointer;
  position: relative;
  // overflow: hidden;
}
::v-deep .avatar-uploader.uploadDisabled {
  .el-upload--text {
    cursor: not-allowed;
    background-color: #f7f7f7;
  }
  .el-upload:hover {
    border-color: #d9d9d9;
  }
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 22px;
  color: #ccc;
  width: 108px;
  height: 108px;
  line-height: 108px;
  text-align: center;
}
::v-deep.avatar {
  width: 108px;
  height: 108px;
  display: block;
}
</style>


