<!--
 * @Author: lixg lixg@dongwu-inc.com
 * @Date: 2023-02-22 10:53:52
 * @LastEditors: lixg lixg@dongwu-inc.com
 * @LastEditTime: 2023-02-22 10:54:01
 * @FilePath: /stu_h5/src/components/img/UploadPostImg.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!-- 上传评论图片 -->
<template>
  <el-upload
    :file-list="files"
    :action="FILE_UPLOAD_IMG"
    method="POST"
    :show-file-list="false"
    :on-change="handleChange"
    :limit="max"
    ref="imageRef"
    :on-exceed="exceed"
  >
    <template #trigger>
      <div>
        <slot></slot>
      </div>
    </template>
  </el-upload>
</template>
<script setup>
import { FILE_UPLOAD_IMG } from "@/api/api";
import { defineProps, ref, watch } from "vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  value: [],
  max: {
    type: Number,
    default: 10,
  },
});

const emit = defineEmits();

const files = ref([]);
const imageRef = ref();

watch(props.value, () => {
  props.value.length || (files.value = props.value);
});

function exceed() {
  ElMessage.error(`只能上传${props.max}个附件`);
}

function handleChange(e) {
  if (e.response && e.response.code === 200) {
    e.url = e.response.data;
    // console.log(e)
    emit("fileUploadValue", e);
  }

  const index = files.value.findIndex((f) => f.uid === e.uid);
  if (index === -1) {
    files.value.unshift(e);
  } else {
    files.value[index] = e;
  }
  emit("update:value", files.value);
}

function remove(i) {
  files.value.splice(i, 1);
  console.log(imageRef);
}

function clearFiles() {
  imageRef.value.clearFiles();
}

function reUpload(i) {
  console.log(i);
  if (
    files.value[i].status === "ready" ||
    files.value[i].status === "uploading"
  ) {
    imageRef.value.abort(files.value[i].raw);
    files.value[i].status = "abort";
  } else if (
    files.value[i].status === "fail" ||
    files.value[i].status === "abort"
  ) {
    imageRef.value.handleStart(files.value[i].raw);
    imageRef.value.submit();
  }
}

function abort(i) {
  imageRef.value.abort(files.value[i].raw);
}

defineExpose({ reUpload, remove, clearFiles });
</script>
