<template>
  <div class="select-upload" :style="{ width: width }">
    <span v-if="label" class="label-text">{{ label }}</span>
    <el-upload
      ref="upload"
      class="file-uploader"
      action="no"
      :accept="curTypeObj.accept"
      :multiple="multiple"
      :show-file-list="false"
      :auto-upload="false"
      :limit="limit"
      :on-change="onFileChange"
    >
      <el-button>{{ showText }}</el-button>
    </el-upload>
    <el-button size="small" class="upload-button" type="primary" @click="uploadFiles">上传</el-button>
  </div>
</template>

<script>
import { fileUpload } from '@/api/app';

export default {
  name: 'SelectUpload',
  props: {
    type: {
      type: String,
      required: true,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    label: {
      type: String,
      default: '',
    },
    width: {
      type: String,
      default: '100%',
    },
    limit: {
      type: Number,
      default: 999,
    },
  },
  data() {
    return {
      typeObj: {
        image: {
          label: '图片',
          accept: '.jpg,.png,.jpeg',
        },
        video: {
          label: '视频',
          accept: '.mp4',
        },
        audio: {
          label: '音频',
          accept: '.mp3,.acc,.wma',
        },
        lrc: {
          label: 'lrc',
          accept: '.lrc',
        },
      },
      fileList: [],
    };
  },
  computed: {
    curTypeObj() {
      return this.typeObj[this.type];
    },
    showText() {
      if (this.fileList.length > 0) {
        return this.fileList.map((file) => file.name).join('、');
      }
      return `选取${this.curTypeObj.label}文件`;
    },
  },
  methods: {
    onFileChange(file, fileList) {
      this.fileList = fileList;
    },
    uploadFiles() {
      const list = this.$refs.upload.uploadFiles;
      if (list.length === 0) {
        this.$message.error('请选择文件');
        return;
      }
      list.forEach((file) => {
        let form = new FormData();
        form.append(file.name, file.raw, file.name);
        fileUpload('Mid', form, { isGlobalprogress: true })
          .then(({ file_info_list }) => {
            this.fileList = [];
            this.$refs.upload.clearFiles();
            if (file_info_list.length > 0) {
              this.$emit('uploadSuccess', file_info_list);
            }
          })
          .catch(() => {
            this.$message.error('上传失败');
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.select-upload {
  display: flex;
  flex: 1;
  align-items: center;

  :deep + & {
    margin-top: 12px;
  }

  .label-text {
    padding-right: 16px;
  }

  .file-uploader {
    flex: 1;

    :deep .el-upload--text {
      width: 100%;
      border-radius: 2px 0 0 2px;
    }

    .el-button {
      width: 100%;
      color: #86909c;
      text-align: left;
      background-color: $fill-color;
    }
  }

  .upload-button {
    border-radius: 0 2px 2px 0;
  }
}
</style>
