<script setup lang="ts">
import { computed } from "vue";
import { useVModel } from "@vueuse/core";
import { type UploadProps, ElMessage } from "element-plus";
import { useRenderIcon } from "../../ReIcon/src/hooks";
import { httpImgUpload } from "/@/api/components/upload";
import { useResponseHandle } from "/@/hooks/useAsync";
import { getToken } from "/@/utils/auth";
import { loadEnv } from "@build/index";
const emit = defineEmits(["change", "update:url"]);

const props = withDefaults(
  defineProps<{
    descs?: string[];
    types?: string[];
    size?: number;
    url?: string;
    disabled?: boolean;
  }>(),
  {
    size: 1
  }
);
const { VITE_PROXY_DOMAIN_REAL } = loadEnv();
const imageUrl = useVModel(props, "url");

const baseUrl = `${VITE_PROXY_DOMAIN_REAL}storage/`;

const token = getToken();

const imageTypes = computed(() => {
  const { types } = props;
  return types.map(type => "image/" + type);
});

const responseHandle = useResponseHandle();

const onBeforeImageUpload: UploadProps["beforeUpload"] = ({ type, size }) => {
  if (!imageTypes.value.includes(type)) {
    ElMessage.warning(`请上传${props.types.join(".")}类型的图片`);
    return false;
  }

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

const handleRequest: UploadProps["httpRequest"] = async ({ file }) => {
  const _formData = new FormData();
  _formData.append("image", file);
  _formData.append("token", token);

  const { message, code, data } = await httpImgUpload(_formData);

  const url = baseUrl + data[0].url;

  responseHandle({
    message,
    code,
    handler: () => {
      imageUrl.value = url;
      emit("change", url);
    }
  });
};
</script>

<template>
  <ElUpload
    class="avatar-uploader"
    :http-request="handleRequest"
    :before-upload="onBeforeImageUpload"
    :show-file-list="false"
    :disabled="disabled"
  >
    <div class="flex justify-between">
      <img class="avatar" v-if="imageUrl" :src="imageUrl" />
      <div v-else>
        <ElButton class="avatar-uploader-icon" :icon="useRenderIcon('plus')" />
      </div>

      <div class="ml-2 text-[#8c939d]">
        <p v-for="(desc, index) in descs" :key="index">{{ desc }}</p>

        <p>
          格式 :
          <span v-for="(type, index) in types" :key="index"
            >{{ type }} <i v-if="index !== types.length - 1">,</i>
          </span>
        </p>
      </div>
    </div>
  </ElUpload>
</template>

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

.avatar-uploader-icon {
  font-size: 31px;
  height: 55px !important;
}
</style>
