<template>
  <div class="dsk-photo-input-container">
    <el-badge :value="0" class="item" type="primary">
      <div class="dsk-photo-input-inner" @click.stop="uploadFile">
        <i class="el-icon-plus"></i>
        <span>上传图片</span>
      </div>
    </el-badge>
    <el-upload :on-change="handleChange" action="#" :accept="allowTypes.join(',')" :auto-upload="false" :show-file-list="false" :limit="limit"
      ref="elUploadDskUploadIns" class="el-upload-dsk-upload-ins"></el-upload>
  </div>
</template>
<script>
import { uploadFileToOssApi } from "@/api/consultingOrgManagement";
export default {
  name: "dskPhotoInput",
  props: {
    limit: {
      type: [String, Number],
      default: 1
    }
  },
  data() {
    return {
      allowTypes: [".jpg", ".png", ".svg", ".gif", ".jpeg"],
      comFileList: []
    };
  },
  //可访问data属性
  created() {

  },
  //计算集
  computed: {

  },
  //方法集
  methods: {
    async handleChange(file, fileList) {
      try {
        /** 
       * @type {string}
      */
        let fileName = file.name;
        let fileType = "";
        const index = fileName.lastIndexOf(".");
        if (index) fileType = fileName.slice(index);

        if (!this.allowTypes.includes(fileType.toLowerCase())) {
          return this.$message.warning(`只支持上传${this.allowTypes.join(" , ")}类型图片`);
        }
        // 验证通过进行上传
        const result = this.uploadHandle(file.raw, fileType);
      } catch (error) {

      }
    },
    uploadFile() {
      this.$refs["elUploadDskUploadIns"].$el.querySelector(".el-upload__input").click();
    },
    async uploadHandle(file, fileType) {
      try {
        const formData = new FormData();
        formData.append("file", file);
        const result = await uploadFileToOssApi(formData);
        if (result.code == 200 && result.data) {
          this.comFileList.push({
            url: result.data.url,
            type: fileType,
            fileName: ""
          });
        }
      } catch (error) {

      }
    }
  },
}
</script>
<style lang="scss" scoped>
.dsk-photo-input-container {
  width: 100%;
  height: 32px;

  .dsk-photo-input-inner {
    width: 106px;
    height: 32px;
    background: #ffffff;
    border: 1px solid #dcdfe6;

    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0px 16px;
    box-sizing: border-box;
    color: rgba(35, 35, 35, 0.8);
    font-size: 14px;
    font-weight: 400;
    cursor: pointer;

    &:hover {
      color: #0081ff;
      border-color: #0081ff;
    }
  }

  ::v-deep .el-upload-dsk-upload-ins {
    width: 0px;
    height: 0px;
    opacity: 0;
    position: relative;
    z-index: -999;
  }
}
</style>
