import { defineComponent } from 'vue'
import { Uploader, Button } from 'vant'
import request from '@/helpers/request'

export default defineComponent({
  name: 'Upload',
  props: {
    accept: {
      type: String
    },
    formatFile: {
      type: Function,
      default: (file: any) => file
    },
    'onUpdate:modelValue': {
      type: Function,
      default: (val: any) => {}
    }
  },
  data() {
    return {
      list: [],
      uploading: false
    }
  },
  methods: {
    async beforeRead(file: File): Promise<boolean> {
      console.log('beforeRead', file)
      return true
    },
    async upload(file: File) {
      this.uploading = true
      const form = new FormData()
      form.append('file', file)
      try {
        const res = await request.post('/api-teacher/uploadFile', {
          data: form
        })
        this.$emit('update:modelValue', res.data.url)
      } catch (error) {}
      this.uploading = false
    }
  },
  render() {
    return (
      <Uploader
        accept={this.accept}
        maxCount={1}
        modelValue={this.list}
        beforeDelete={this.beforeRead}
        onUpdate:modelValue={async val => {
          if (val[0]) {
            await this.upload(val[0].file)
            this.formatFile(val[0].file)
          }
          this.list = val
        }}
        onDelete={() => {
          this.list = []
          this.$emit('update:modelValue', null)
        }}
      >
        <Button loading={this.uploading}>上传文件</Button>
      </Uploader>
    )
  }
})
