<script lang="ts" setup>
import { type UploadProps, ElMessage } from "element-plus";
import { useUserStore } from "/@/store/modules/user";
import { useResponseHandle } from "/@/hooks";
import { httpImageUpload, baseUrl } from "/@/api/other";
import { useVModel } from "@vueuse/core";
import { useRenderIcon } from "../../ReIcon/src/hooks";
import { getToken } from "/@/utils/auth";

defineEmits(["update:modelValue"]);

const props = defineProps<{
  modelValue: string;
}>();

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

const imgUrl = useVModel(props, "modelValue");
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();
  const token = getToken();
  _formData.append("image", file);
  _formData.append("token", token);
  const { message, code, data } = await httpImageUpload(_formData);

  responseHandle({
    message,
    code,
    handler: () =>  {
      imgUrl.value = baseUrl + "/storage/" + data[0].url
      console.log(imgUrl.value, data[0].url)
    }
  });
};
</script>

<template>
  <el-upload
    class="avatar-uploader"
    :show-file-list="false"
    :before-upload="onBeforeReturnImageUpload"
    :http-request="handleRequeset"
  >
    <img v-if="imgUrl" :src="imgUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon">
      <div style="font-size: 36px">+</div>
    </el-icon>
  </el-upload>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
