<template>
  <!--  <div class="file-input" @click="handleClick()">-->
  <!--    <slot></slot>-->
  <!--    <input -->
  <!--      class="input"-->
  <!--      type="file" -->
  <!--      name="upload" -->
  <!--      ref="inputRef" -->
  <!--      :accept="accept" -->
  <!--      @change="$event => handleChange($event)"-->
  <!--    >-->
  <!--  </div>-->
  <el-upload
      ref="upload"
      :multiple="false"
      class="avatar-uploader"
      action="apis10/upload/bucketFile"
      :headers="headers"
      :show-file-list="false"
      accept=".jpg,.png"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
      :on-success="successFile"
      :data="uploadParams"
  >
    <template #trigger>
      <el-button type="primary">
        <!--        <i-ep-Picture/>&nbsp;&nbsp;-->
        <el-icon>
          <UploadFilled/>
        </el-icon>
      </el-button>
    </template>
  </el-upload>
</template>

<script lang="ts" setup>
import {ref} from 'vue'
import {ElMessage, genFileId, UploadInstance, UploadProps, UploadRawFile} from "element-plus";
import {UploadFilled} from "@element-plus/icons-vue";
import {getToken} from "@/utils/js-cookie";

//el-upload
const upload = ref<UploadInstance>();
const headers = ref({
  "X-ERP-User-From": 10,
  "X-ERP-DataSource-Id": getToken("dataBaseAlias"),
  "X-ERP-Supplier-Code": getToken("shardingKey"),
  "X-Token": getToken("token"),
});
const uploadParams = reactive({
  srcfilename: "",
  chunks: 1,
  bucketName: "webImage",
});
const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

function beforeUpload(file) {
  console.log(file);
  uploadParams.srcfilename = file.name;
  return new Promise((resolve, reject) => {
    if (file.size > 307200) {
      ElMessage.warning(
          "图片大小不能大于300KB,请您注意图片的长和宽,网页图片的分辨率为72"
      );
      reject();
    } else {
      resolve(file);
    }
  });
}

function successFile(res, file, fileList) {
  // console.log(res);
  // formData.posterLocationImage = res.fileLink
  // formData.fontThumbUrl = res.url;

  if (res) emit('change', res)
  ElMessage.success("上传成功");
}


defineProps({
  accept: {
    type: String,
    default: 'image/*',
  },
})

const emit = defineEmits<{
  (event: 'change', payload: FileList): void
}>()

const inputRef = ref<HTMLInputElement>()

const handleClick = () => {
  if (!inputRef.value) return
  inputRef.value.value = ''
  inputRef.value.click()
}
const handleChange = (e: Event) => {
  const files = (e.target as HTMLInputElement).files
  if (files) emit('change', files)
}
</script>

<style lang="scss" scoped>
.input {
  display: none;
}
</style>