<template>
  <div
    class="upload"
    :style="{
      width: width,
      height: height,
      cursor: disabled ? 'not-allowed' : '',
    }"
    v-loading="imgLoading"
  >
    <input
      type="file"
      accept="image/png, image/jpeg, image/jpg"
      :disabled="disabled"
      :id="id"
      v-show="false"
      :ref="id"
      @change="upload"
    />
    <div
      class="upload-btn"
      :style="{ width: width, height: height }"
      v-loading="imgLoading"
      v-if="!url"
      @click="handleUpload"
    >
      <i class="el-icon-plus"></i>
    </div>
    <img
      class="img"
      :style="{ width: width, height: height }"
      @click="handleUpload"
      v-else
      :src="url"
      alt=""
    />
  </div>
</template>

<script>
import { requestUploadImg, finishUploadImg } from "@/api/common";
import OSS from "ali-oss";
export default {
  props: {
    imgUrl: {
      type: String,
      default: "",
    },
    id: {
      //同一个页面使用多个上传组件时必填
      type: String,
      default: "file",
    },
    width: {
      type: String,
      default: "100px",
    },
    height: {
      type: String,
      default: "100px",
    },
    type: {
      type: String,
      default: "", //用于同页面多个上传，方便区分字段，this.query.img 传img
    },
    uploadType: {
      type: String,
      default: "GOODS_INFO", //OTHER,SHOP_INFO,YIN_LIAN_AUTH
    },
    disabled: {
      type: Boolean,
      default: false, //OTHER,SHOP_INFO,YIN_LIAN_AUTH
    },
  },
  data() {
    return {
      imgLoading: false,
      config: null,
      url: this.imgUrl,
    };
  },
  // computed: {
  //    url: {
  //     get: function () {
  //       return this.imgUrl
  //     },
  //     set: function (v) {
  //       this.imgUrl = v
  //     }
  //   }
  // },
  watch: {
    imgUrl(val) {
      this.url = val;
    },
  },
  methods: {
    async upload(val) {
      //oss上传
      this.imgLoading = true;
      let files = val.target.files[0];
      if (this.type) {
        //银联认证上传图片
      }

      this.getOssConfig(files.name)
        .then((res) => {
          const client = new OSS({
            // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
            region: res.endPoint.split(".")[0],
            // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            accessKeyId: res.token.accessKeyId,
            accessKeySecret: res.token.accessKeySecret,
            // 填写Bucket名称。
            bucket: res.bucket,
            stsToken: res.token.securityToken,
          });

          client
            .multipartUpload(res.paths[0].join("/"), files)
            .then((r) => {
              // 上传完成
              finishUploadImg([{ path: res.paths[0] }]).then((msg) => {
                if (msg.state == "Success") {
                  let url =
                    "http://" +
                    res.bucket +
                    "." +
                    res.endPoint +
                    "/" +
                    res.paths[0].join("/");
                  this.imgLoading = false;
                  this.url = url;
                  this.$refs[this.id].value = "";
                  this.$emit("uploadEnd", { url, type: this.type });
                }
              });
            })
            .catch((err) => {
              console.log(err); //上传失败之后
            });
        })
        .catch(() => {
          this.$refs[this.id].value = "";
          this.imgLoading = false;
        });
    },

    handleUpload() {
      document.getElementById(this.id).click();
    },
    getOssConfig(fineName) {
      return new Promise((resolve, reject) => {
        requestUploadImg({
          fineName: fineName,
          operate: this.uploadType,
        }).then((res) => {
          if (res.state == "Success") {
            resolve(res.content);
          } else {
            reject();
          }
        });
      });
    },
  },
  created() {},
};
</script>

<style lang="scss" scoped>
.upload {
  .upload-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(176, 176, 177, 0.2);
    border-radius: 4px;
    cursor: pointer;
  }
  .el-icon-plus {
    font-size: 20px;
    font-weight: 600;
    color: #666;
  }
  .img {
    // width: 100px;
    // height: 100px;
    border-radius: 4px;
    object-fit: contain;
  }
}
</style>