<template>
  <div v-if="type == 'image'">
    <el-upload class="avatar-uploader" :http-request="(event: any) => upload(event)" :show-file-list="false">
      <img v-if="imageSrc" :src="imageSrc" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </div>
  <div v-if="type == 'file'">
    <div>
      <el-upload class="upload-demo" :http-request="(event: any) => upload(event)" :show-file-list="false">
        <div>
          <el-button size="small" type="primary">点击上传</el-button>
        </div>
      </el-upload>
    </div>
    <div>
      <div
          v-for="(item, index) in fileData"
          :key="index"
          style="width: 185px; display: flex; justify-content: space-between; align-items: center; cursor: pointer"
      >
        <div @click="goUrl(item.url)">
          <SvgIcon name="byte-notes" :size="14" /><span style="margin-left: 6px">{{ item.name }}</span>
        </div>
        <div @click="del(item.id)"><SvgIcon name="byte-delete" :size="14" /></div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent } from 'vue';
import { uploadFile, getFileUrl, delFile } from '@/utils/util';
import { ElMessage } from 'element-plus';

export default defineComponent({
  name: 'upload',
  props: {
    // 上传类型:image file
    type: {
      type: String,
      default: 'image',
    },
    imageSrc: {
      type: String,
      default: '',
    },
    fileData: {
      type: Array,
      default: () => [],
    },
  },
  emits: ['handleUpload', 'handleDelete'],
  setup(props, { emit }) {
    const upload = (e: any) => {
      const file = e.file;
      const type = file.type.split('/')[1];
      const name = new Date().getTime() + '.' + type;
      uploadFile(file, name).then((res: any) => {
        if (res) {
          emit('handleUpload', { res: res, name: name });
        }
      });
    };

    const del = (fileId: string) => {
      delFile(fileId).then((res) => {
        if (res) {
          ElMessage.success('文件已删除');
          emit('handleDelete', fileId);
        }
      });
    };

    const goUrl = (goUrl: string) => {
      window.open(goUrl);
    };
    return {
      upload,
      del,
    };
  },
});
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
}
</style>
