<template>
    <div class="para-upload para-item" :class="{'is-disabled':disabled1}">
    <span class="para-upload-name">
      <inputElement :value="fileName" class="upload-filename" :title="fileName" disabled></inputElement>
        <Icon type="close" class="el-icon-close" @click="clear" v-if="file"/>
      </span>
        <template v-if="!disabled1">
            <label :for="fileID" class="para-select-file">{{buttonText1}}</label>
            <input ref="inputFile" v-show="false" type="file" :id="fileID" @change="fileChange($event)"/>
        </template>
    </div>
</template>
<script>
  import {Input, Icon} from 'ant-design-vue';

  const language = {
    'zh_CN': '选择文件',
    'en_GB': 'Select file'
  };

  export default {
    name: 'paraUpload',
    components: {'inputElement': Input, Icon},
    props: [
      'value',
      'disabled',
      'buttonText',
      'text'
    ],
    data() {
      return {
        // lang,
        file: this.value instanceof File ? this.value : null,
        disabled1: this.disabled || false,
        fileName: typeof this.text === 'string' ? this.text : '',
        buttonText1: this.buttonText || language[this.language()], // 选择文件
        fileID: 'paraupload_' + String(new Date().getTime()) + parseInt(Math.random() * 100000, 10)
      };
    },
    created(){
      if (this.value instanceof File) {
        this.file = this.value;
        this.fileName = this.value.name || '';
      } else {
        this.file = null;
        this.fileName = '';
      }
      if (typeof this.value === 'string') this.fileName = this.value;
    },
    watch: {
      value(val, old) {
        if (val === old) return;
        if (val instanceof File) {
          this.file = val;
          this.fileName = val.name || '';
        } else {
          this.file = null;
          this.fileName = '';
        }
        if (typeof val === 'string') this.fileName = val;
      },
      disabled(val) {
        // eslint-disable-next-line no-console
        if (typeof val !== 'boolean') return console.warn('para-upload disabled is boolean');
        this.disabled1 = val;
      },
      buttonHide(val) {
        // eslint-disable-next-line no-console
        if (typeof val !== 'boolean') return console.warn('para-upload notAr is boolean');
        this.buttonHide1 = val;
      }
    },
    methods: {
      language() {
        return JSON.parse(window.localStorage[window.$project]).setting.language || 'zh_CN';
      },
      fileChange(e) {
        const input = e.currentTarget;
        if (!input || !input.files) return;
        const file = input.files[0];
        this.file = file;
        this.fileName = file.name;
        this.$emit('input', file);
        this.$emit('change', file);
      },
      clear() {
        this.$refs.inputFile.value = null;
        this.fileName = '';
        this.file = null;
        this.$emit('input', null);
        this.$emit('change', null);
      }
    },
    mounted() {
    }
  };
</script>
