<template>
  <div>
    <Upload
      ref="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 || '').trim()
          ? accept
              .split(',')
              .map(item => '.' + item.replaceAll('.', ''))
              .join(',')
          : null
      "
      :format="!!(accept || '').trim() ? accept.split(',').map(item => item.replaceAll('.', '')) : []"
      :multiple="true"
      :type="draggable ? 'drag' : 'select'"
      :max-size="maxSize == null ? null : maxSize * 1024"
    >
      <Button v-if="!draggable && !readonly" :size="size" icon="ios-cloud-upload-outline">{{ $t('Front_Btn_Upload') }}</Button>
      <div v-if="draggable && !readonly" style="padding: 20px 0">
        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
        <p>{{ $t('Front_Label_Drag_Upload') }}</p>
      </div>
    </Upload>
    <Input type="text" :model-value="modelValue" :size="size" v-show="false" />
  </div>
</template>
<script>
  import mixinPage from '../../mixins/page';

  export default {
    mixins: [mixinPage],
    data() {
      return {
        fileList: [],
        defaultList: []
      };
    },
    props: {
      // 值
      modelValue: {
        type: String
      },
      /**
       * 请求地址
       */
      url: {
        type: String
      },
      // 只读
      readonly: {
        type: Boolean,
        default: false
      },
      // 最大上传数量
      maxCount: {
        type: Number
      },
      // 最大上传文件大小(M)
      maxSize: {
        type: Number
      },
      /**
       * 大小
       * @values small, default, large
       */
      size: {
        type: String
      },
      /**
       * 允许的文件类型
       */
      accept: {
        type: String
      },
      /**
       * 允许拖拽上传
       */
      draggable: {
        type: Boolean,
        default: false
      }
    },
    computed: {
      // 上传地址
      uploadAction() {
        return this.url == null ? this.uploadURL : this.url;
      }
    },
    methods: {
      // 设置初始值
      setData(value) {
        let list = [];
        if (value && value !== '') {
          try {
            list = JSON.parse(value).map(item => {
              return {
                ...item,
                url: this.getAttachmentUrl(item.file, item.name)
              };
            });
          } catch (e) {
            // console.log(e);
          }
        }

        //this.$emit('update:modelValue', value);
        this.fileList = list;
        this.defaultList = list;
      },
      // 上传之前
      beforeUpload(file) {
        if (this.maxSize != null) {
          if (file.size > this.maxSize * 1024 * 1024) {
            this.error('Front_Msg_Max_Quantity|' + this.maxSize);
            return false;
          }
        }

        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) {
        if (res.code != 0) {
          this.error(res.message);
          this.$refs.upload.fileList = this.$refs.upload.fileList.filter(item => item.uid != file.uid);
          return false;
        }

        let list = this.fileList;

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

        this.$emit('update:modelValue', JSON.stringify(list));
      },
      // 上传预览
      onUploadPreview(file) {
        if (file.file) {
          window.location.href = this.getAttachmentUrl(file.file, file.name);
        } else {
          window.location.href = this.getAttachmentUrl(file.response.data[0], 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('update:modelValue', null);
        } else {
          this.$emit('update:modelValue', JSON.stringify(list));
        }
      }
    }
  };
</script>
