<template>
  <div>
    <Upload
      :action="uploadAction"
      :headers="uploadHeaders"
      :default-file-list="defaultList"
      :before-upload="beforeUpload"
      :on-success="onUploadSuccess"
      :on-preview="onUploadPreview"
      :on-remove="onUploadRemove"
      :disabled="readonly"
      :accept="accept"
    >
      <Button v-if="!readonly" :size="size" icon="ios-cloud-upload-outline">{{ $t('Front_Btn_Upload') }}</Button>
    </Upload>
    <Input type="text" :value="value" :size="size" v-show="false" />
  </div>
</template>
<script>
  import mixinPage from '../../mixins/page';

  export default {
    mixins: [mixinPage],
    props: {
      // 值
      value: {
        type: String
      },
      /**
       * 请求地址
       */
      url: {
        type: String
      },
      // 只读
      readonly: {
        type: Boolean,
        default: false
      },
      // 最大上传数量
      maxCount: {
        type: Number
      },
      /**
       * 大小
       * @values small, default, large
       */
      size: {
        type: String
      },
      /**
       * 允许的文件类型
       */
      accept: {
        type: String
      }
    },
    computed: {
      // 上传地址
      uploadAction() {
        return this.url == null ? this.uploadURL : this.url;
      },
      fileList() {
        let list = [];
        if (this.value && this.value !== '') {
          try {
            list = JSON.parse(this.value);
          } catch (e) {
            // console.log(e);
          }
        }

        return list;
      },
      defaultList() {
        return this.fileList.map(item => {
          return {
            ...item,
            url: this.getAttachmentUrl(item.file, item.name)
          };
        });
      }
    },
    methods: {
      // 上传之前
      beforeUpload() {
        if (this.maxCount != null) {
          let list = this.fileList;
          if (list.length >= this.maxCount) {
            this.error('Front_Msg_Max_Quantity|' + this.maxCount);
            return false;
          }
        }
      },
      // 上传成功
      onUploadSuccess(res, file) {
        let list = this.fileList;

        list.push({
          file: file.response.data[0],
          name: file.name,
          user: this.info.id
        });

        this.$emit('input', JSON.stringify(list));
      },
      // 上传预览
      onUploadPreview(file) {
        window.location.href = this.getAttachmentUrl(file.file, file.name);
      },
      // 移除上传文件
      onUploadRemove(file) {
        let list = this.fileList;

        let index = list.findIndex(item => {
          return item.file === file.file;
        });

        list.splice(index, 1);

        if (list.length === 0) {
          this.$emit('input', null);
        } else {
          this.$emit('input', JSON.stringify(list));
        }
      }
    }
  };
</script>
