<template>
  <div>
    <lay-upload :url="uploadUrl" :drag="true" :status="status" :headers="headers" :beforeUpload="handleBeforeUpload" @done="handleUploadDone" @error="handleUploadError" />
    <div>
      <div class="status_wp">
        <lay-space>
          <span>{{ fileName }}</span>
          <lay-icon v-if="status == 1" class="layui-anim layui-anim-rotate layui-anim-loop" type="layui-icon-loading" />
          <lay-icon v-if="status == 2" class="success" type="layui-icon-success" />
          <lay-icon v-if="status == 3" class="error" type="layui-icon-error" />
        </lay-space>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, getCurrentInstance } from "vue";

const { proxy }: any = getCurrentInstance();

const emit = defineEmits();

const props = defineProps({
  modelValue: String,
  status: Number,
  url: {
    type: String,
    default: `${import.meta.env.VITE_API_BASE_URL}/client/upload`,
  },
  beforeUpload: Function,
  uploadDone: Function,
});

watch(
  () => props.status,
  (value) => {
    updataStatus(value || 0);
  }
);

const status = ref(0);
const fileName = ref();
const uploadUrl = props.url;
const headers = {
  auth: "4L",
  Token: window.sessionStorage.getItem("_4L_TOKEN") || "",
};
const uploadValue = ref();

uploadValue.value = props.modelValue;

// 上传前处理方法
const handleBeforeUpload = (file: File) => {
  updataStatus(1);
  let isUpload = true;
  fileName.value = file.name;
  if (typeof props.beforeUpload === "function")
    isUpload = props.beforeUpload(file, (value: number) => {
      updataStatus(value);
    });
  return isUpload;
};

// 上传结束回调
const handleUploadDone = (e: any) => {
  let result = JSON.parse(e.data);
  if (JSON.parse(e.data).code != 200) {
    proxy.$message(`${result.msg}`, 2);
    return updataStatus(3);
  }
  emit("update:modelValue", JSON.parse(e.data).data);
  updataStatus(2);
};

// 上传失败回调
const handleUploadError = () => {
  uploadValue.value = undefined;
  updataStatus(3);
};
const updataStatus = (value: number) => {
  status.value = value;
};
</script>

<style lang="scss" scoped>
.status_wp {
  .success {
    color: var(--primary-color);
  }
  .error {
    color: var(--danger-color);
  }
}
</style>
