<script lang="ts" setup>
import { ref } from "vue";
import { type UploadUserFile, type UploadProps, ElMessage } from "element-plus";
import { useUserStore } from "/@/store/modules/user";
import { useResponseHandle } from "/@/hooks";
import { httpImageUpload, baseUrl } from "/@/api/other";

const emit = defineEmits(["change"]);

const types = ["image/png", "image/jpg", "image/bmp", "image/jpeg"];

const fileList = ref<UploadUserFile[]>([]);
const imgs = ref<Array<string>>([]);
const userStore = useUserStore();
const responseHandle = useResponseHandle();

const onBeforeReturnImageUpload: UploadProps["beforeUpload"] = ({
  type,
  size
}) => {
  if (!types.includes(type)) {
    ElMessage.error("请上传jpg.png.bmp.jpeg类型图片");
    return false;
  }

  if (size / 1024 / 1024 > 1) {
    ElMessage.error("图片大小超过1M");
    return false;
  }
};

const handleRequeset: UploadProps["httpRequest"] = async ({ file }) => {
  const _formData = new FormData();
  _formData.append("img", file);
  _formData.append("token", userStore.token);
  const { message, code, data } = await httpImageUpload(_formData);

  responseHandle({
    message,
    code,
    handler: () => {
      imgs.value.push(baseUrl + "/" + data[0].url);
      emit("change", imgs.value.join(","));
    }
  });
};

const handleRemove: UploadProps["beforeRemove"] = uploadFile => {
  const delIndex = fileList.value.findIndex(
    ({ uid }) => uid === uploadFile.uid
  );
  imgs.value.splice(delIndex, 1);
  emit("change", imgs.value.join(","));
  return true;
};
</script>

<template>
  <el-upload
    v-model:file-list="fileList"
    :before-upload="onBeforeReturnImageUpload"
    :http-request="handleRequeset"
    :before-remove="handleRemove"
    list-type="picture"
  >
    <el-button type="primary">上传图片</el-button>
    <template #tip>
      <div class="el-upload__tip">请上传jpg.png.bmp.jpeg类型图片</div>
    </template>
  </el-upload>
</template>
