<template>
  <div class="sis-upload">
    <div class="sis-upload-div">
      <input class="sis-input-file" type="file" :accept="accept" @change="handleFileChange"/>选择文件
    </div>
    <span class="sis-file-name">{{ (value === null || value.name === undefined) ? '' : value.name }}</span>
    <el-tag v-if="success" class="sis-file-name" type="success">上传成功</el-tag>
  </div>
</template>

<script type="text/ecmascript-6">
  /**
   * @author 白雨浓
   * @date 17-9-27 下午6:44
   *
   * 上传模块
   **/
  export default{
    name: 'SisUpload',
    props: {
      value: {},
      url: {
        type: String,
        required: true
      },
      group: {
        type: String,
        required: true
      },
      accept: {
        type: String
      },
      fileName: {
        type: String,
        default: ''
      },
      data: {
        type: Object
      }
    },
    data(){
      return {
        success: false
      }
    },
    mounted(){
      this.$eventBus.once('upload:' + this.group, () => {
        if (typeof this.value === 'object' && this.value.name !== undefined) {
          this.success = false;
          this.upload();
        }
      });
    },
    methods: {
      /** 文件改变处理 */
      handleFileChange(event){
        this.$emit('input', event.target.files[0])
      },
      upload(){
        const formData = new FormData();
        if (this.data !== undefined)
          for (const key in this.data)
            formData.append(key, this.data[key]);
        formData.append('file', this.value);

        this.$$ajax.post(this.url, formData, {headers: {'Content-Type': 'multipart/form-data'}})
          .then(res => {
            if (res.data.code < 1)
              throw res.data.msg;

            this.success = true;
            this.$emit('on-success', this.value);
          })
          .catch(err => this.$$msg.err(err));

        this.$emit('input', 'success')
      }
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  .sis-upload {
    position relative
    display inline-block
    height 30px
    line-height 30px
    vertical-align middle

    .sis-upload-div {
      display inline
      width 80px
      height 35px
      background #50bfff
      border 1px solid #50bfff;
      border-radius 5px
      padding 8px 12px
      overflow hidden
      color white
      text-decoration none
      text-indent 0
    }

    .sis-input-file {
      position absolute
      width 80px
      height 35px
      font-size 20px
      left 0
      top 0
      opacity 0
    }

    .sis-file-name {
      margin-left 10px
    }
  }
</style>
