<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";
import { getToken } from "/@/utils/auth";

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

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

defineProps<{
  multiple?: boolean;
}>();

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

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

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();
  const token = getToken();
  _formData.append("img", file);
  _formData.append("token", 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 handleExceed: UploadProps["onExceed"] = () => {
  ElMessage.error("回执图片不能超过十张");
};

const handlePictureCardPreview: UploadProps["onPreview"] = uploadFile => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

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

<template>
  <el-upload
    v-model:file-list="fileList"
    :before-upload="onBeforeReturnImageUpload"
    :http-request="handleRequeset"
    :before-remove="handleRemove"
    :on-preview="handlePictureCardPreview"
    :on-exceed="handleExceed"
    :limit="10"
    list-type="picture-card"
    :multiple="multiple"
  >
    <div class="add-icon">+</div>
    <template #tip>
      <div class="el-upload__tip">请上传jpg.png.bmp.jpeg类型图片</div>
    </template>
  </el-upload>

  <el-dialog v-model="dialogVisible" :close-on-click-modal="false">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<style scoped>
.add-icon {
  font-size: 38px;
}
</style>
