<template>
  <el-upload
    :style="`--width: ${props.size}px; --height: ${props.size}px`"
    class="upload"
    :class="{ hide: disabled }"
    accept="image/*"
    list-type="picture-card"
    v-model:file-list="fileList"
    :action="ACTION"
    :headers="HEADERS"
    name="files"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
    :limit="9"
    :before-upload="beforeUpload"
    :disabled="disabled"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>

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

<script lang="ts" setup>
import { ref, watch } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, UploadFiles, UploadProps } from "element-plus";
import { useCommonStore } from "@/store/common";

interface Tdata {
  code: number;
  data: {
    imeUrl: string;
  };
  msg: string;
}
const comm = useCommonStore();
const ACTION = import.meta.env.VITE_APP_URL + "/v1/api/upload/warning/img";
const HEADERS = {
  "Access-Token": comm.user.token,
};

const props = defineProps({
  size: {
    type: Number,
    default: 100,
  },
  modelValue: {
    type: Array,
    default: () => [],
  },
  disabled: {
    type: Boolean,
    default: () => false,
  },
  limit: {
    type: Number,
    default: () => 9,
  },
});

const emit = defineEmits(["update:modelValue"]);

const fileList = ref<any[]>([]);

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

watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && newVal.length) {
      fileList.value = newVal.map((item) => {
        return {
          name: item,
          response: { code: 200, msg: "成功", data: [item] },
          status: "success",
          url: item,
        };
      });
    }
  }
);

const beforeUpload = (rawFile: any) => {
  const isLtSize = rawFile.size / 1024 / 1024 < 5;
  if (!isLtSize) {
    ElMessage.error("上传图片大小不能超过 5MB!");
    return false;
  }
  return true;
};

const handleSuccess: UploadProps["onSuccess"] = (_: any, _1: any, uploadFiles: any) => {
  let list = uploadFiles.map((item) => item?.response?.data[0]);
  emit("update:modelValue", list);
};

const handleRemove = (_: any, uploadFiles: any) => {
  let list = uploadFiles.map((item) => item.response.data[0]);
  emit("update:modelValue", list);
};

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

<style scoped lang="less">
.upload :deep(.el-upload) {
  width: var(--width);
  height: var(--height);
}
.upload :deep(.el-upload-list__item) {
  width: var(--width);
  height: var(--height);
}
.upload :deep(.el-icon--close-tip) {
  display: none;
}
.hide :deep(.el-upload--picture-card) {
  display: none;
}
</style>
