<template>
  <a-upload :show-upload-list="false" :custom-request="onFileChange">
    <div class="cover-upload">
      <img v-if="cover" :src="cover" alt="" />
      <div class="cover-edit-wrap">
        <template v-if="uploading">
          <LoadingOutlined />
        </template>
        <template v-else>
          <div class="add">
            <PlusOutlined />
          </div>
        </template>
      </div>
    </div>
  </a-upload>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";
import { message } from "ant-design-vue";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons-vue";

import { onUpload } from "@/api";

const ImageUpload = defineComponent({
  name: "ImageUpload",
  components: {
    LoadingOutlined,
    PlusOutlined
  },
  props: {
    type: {
      type: String,
      default: () => ""
    },
    name: {
      type: String,
      required: true,
      default: () => ""
    },
    value: {
      type: String,
      default: () => ""
    }
  },
  emits: ["change"],
  setup(props, { emit }) {
    const state = reactive({
      uploading: false,
      cover: props.value ?? ""
    });

    const onFileChange = async (file: { file: File }) => {
      try {
        state.uploading = true;
        let tempFile = file.file;
        const { data } = await onUpload(tempFile, props.type ?? "");
        state.cover = data.url;
        emit("change", { url: state.cover, type: props.name });
      } catch (error) {
        message.error(error.msg ?? "系统错误");
      } finally {
        state.uploading = false;
      }
    };

    return { ...toRefs(state), onFileChange };
  }
});

export default ImageUpload;
</script>

<style lang="scss" scoped>
.cover-upload {
  font-size: 0;
  position: relative;
  border-radius: 6px;
  width: 128px;
  height: 128px;
  overflow: hidden;

  img {
    width: 128px;
    height: 128px;
  }

  .cover-edit-wrap {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    background: rgba($color: #000, $alpha: 0.3);
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 18px;
    color: #fff;
    cursor: pointer;
    transition: opacity 0.3s;
    opacity: 1;

    // &:hover {
    //   opacity: 1;
    // }
  }
}
</style>
