import { getToken } from '@/utils/auth'
import { Upload } from 'element-ui'
import './upload.scss'
import { removeFile } from '@/api/file'
export default {
  props: {
    accept: {
      type: String,
      default: ''
    },
    action: {
      type: String,
      default: process.env.VUE_APP_BASE_API + '/file/upload'
    },
    limit: [Number],
    showFileList: {
      type: Boolean,
      default: () => true
    },
    fileList: {
      type: Array,
      default: () => []
    },
    beforeUpload: {
      type: Function,
      default: () => {}
    },
    listType: {
      type: String,
      default: 'text'
    },
    drag: {
      type: Boolean,
      default: false
    },
    uploadData: {
      type: Object,
      default: () => ({})
    },
    localCLassName: [String],
    httpRequest: Function
  },
  data() {
    return {
      token: { Authorization: 'Bearer ' + getToken() },
      previewUrl: '',
      dialogVisible: false
    }
  },
  computed: {
    localFileList: {
      get() {
        return this.fileList
      },
      set(val) {
        this.$emit('update:fileList', val)
      }
    }
  },
  methods: {
    validatePicture(file) {
      const filename = file.name
      const suffix = filename.substr(filename.lastIndexOf('.') + 1)
      const isLt2M = file.size / 1024 / 1024 < 2
      const tupianArr = ['jpeg', 'jpg', 'png', 'gif']
      const isSupport = tupianArr.includes(suffix)
      if (!isSupport) {
        this.$message.error('上传文件不是图片格式!')
        return isSupport
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    localBeforeUpload(file) {
      if (this.beforeUpload && typeof this.beforeUpload === 'function') {
        this.beforeUpload(file)
      } else {
        this.validatePicture(file)
      }
    },
    handleFilePreview(file) {
      this.dialogVisible = true
      this.previewUrl = file.url
    },
    handleFileRemove(file, fileList) {
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.localFileList[i].uid === file.uid) {
          this.localFileList.splice(i, 1)
        }
      }
      // 从文件服务中删除文件
      if (file.id) {
        removeFile([{ fileUrl: file.fileUrl }]).then()
      }
    },
    handleFileChanged(file, fileList) {
      // 检查是否有重复文件，有的话删除新选择的文件
      if (fileList.findIndex(f => f.name === file.name) !== fileList.findLastIndex(f => f.name === file.name)) {
        this.$message.error(file.name + ' 文件已存在')
        fileList.pop()
      }
    },
    handleSuccess(res, file, fileList) {
      this.$emit('on-success', res, fileList, file)
    },
    handleExceed() {
      this.$emit('on-exceed')
    },
    handleError(err, file, fileList) {
      this.$emit('on-error', err, file, fileList)
    },
    onClick() {
      this.$refs.upload.$children[0].$refs.input.click()
    },
    upload() {
      this.$refs.upload.submit()
    },
    handleClose() {
      this.dialogVisible = false
    }
  },
  render() {
    const { token, dialogVisible, previewUrl } = this.$data
    const { listType, localCLassName } = this.$props
    return (
      <div>
        <el-dialog visible={dialogVisible} append-to-body={true} onClose={this.handleClose}>
          <img width='100%' src={previewUrl} alt='' />
        </el-dialog>
        <div class='upload'>
          <Upload
            ref={'upload'}
            {...{ props: Object.assign({}, { ...this.$attrs }, { ...this.$props }), scopedSlots: { ...this.$scopedSlots }}}
            class={{ 'upload-picture': listType !== 'text', localCLassName }}
            headers={token}
            beforeUpload={this.localBeforeUpload}
            on-change={this.handleFileChanged}
          >
            {Object.keys(this.$slots).map(name => (<template slot={name}>{this.$slots[name]}</template>))}
          </Upload>
        </div>
      </div>
    )
  }
}
