<template>
  <input
    type="file"
    ref="inputRef"
    class="hidden"
    accept=".jpg,.jpeg,.png,.gif,.bmp"
    @change="handleFileChange"
  />
  <div v-loading="loading">
    <label class="cursor-pointer" @click="($refs.inputRef as any).click">
      <img
        v-show="!url"
        src="@/assets/img/uploadFileImg.png"
        style="width: 196px"
      />
      <img v-show="url" :src="url" style="width: 196px" />
    </label>
    <div class="tip mt-5">
      <slot></slot>上传 温馨提醒：允许上传
      .jpg、.jpeg、.png、.gif、.bmp的图像文件，且文件不能大于2M。
    </div>
  </div>
</template>

<script setup lang="ts">
import { copyrightUploadFile } from "@/service/copyrightService";
import { syMessage } from "cqk-sy-ui";
import { ref, watch } from "vue";
const props = defineProps<{
  modelValue: {
    url?: string;
    file?: File;
  } | null;
}>();
const emit = defineEmits(["update:modelValue"]);
const loading = ref(false);
const url = ref("");
watch(
  () => props.modelValue,
  (newV) => {
    URL.revokeObjectURL(url.value);
    url.value = getImageUrl(props.modelValue) || "";
  }
);

function getImageUrl(dta: any) {
  if (!dta) return "";
  return (dta.file && URL.createObjectURL(dta.file!)) || dta.url || "";
}

const checkType = (fileName: string) => {
  return !!fileName.match(/\.((jpg)|(jpeg)|(png)|(gif)|(bmp))$/);
};
const checkSize = (size: number) => {
  return !(size > 2 * 1024 * 1024);
};

const handleFileChange = async (e: Event) => {
  const target = e.target as HTMLInputElement;
  const file = target.files && target.files[0];

  if (!file) return;

  loading.value = true;

  const typeValid = checkType(file.name);
  const sizeValid = checkSize(file.size);
  if (!typeValid)
    syMessage.warning("只许上传.jpg、.jpeg、.png、.gif、.bmp的图像文件");
  if (!sizeValid) syMessage.warning("文件不能大于2M");
  if (typeValid && sizeValid) {
    const ret = await copyrightUploadFile(file);
    if (ret && ret.code === 200) {
      emit("update:modelValue", {
        file,
        ...ret.data,
      });
    }
    target.value = "";
  }
  loading.value = false;
};
</script>

<style lang="scss" scoped>
.tip {
  font-size: 12px;
  font-weight: 400;
  color: var(--sy-gray);
  line-height: 26px;
}
</style>
