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

defineEmits(["update:modelValue"]);

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

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

const imgUrl = useVModel(props, "modelValue");
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: () =>  {
      const url =  baseUrl + "/storage/" + data[0].url
      imgUrl.value = isEncoded(url) ? url : encodeURI(url)
      console.log(imgUrl.value, data[0].url)
    }
  });
};
</script>

<template>
  <ElUpload
    class="avatar-uploader"
    :show-file-list="false"
    :before-upload="onBeforeReturnImageUpload"
    :http-request="handleRequeset"
    :accept="types.join(',')"
  >
    <img v-if="imgUrl" :src="imgUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon">
      <div style="font-size: 28px">+</div>
    </el-icon>
  </ElUpload>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 48px;
  height: 48px;
  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: 18px;
  color: #8c939d;
  width: 48px;
  height: 48px;
  text-align: center;
}
</style>
