<template>
  <div class="has-text-left">
    <p class="py-1 border-bottom" v-for="v in vfiles">
      <span class="icon-text">
        <span class="mr-5">{{ v.name }}</span>
        <SvgIcon v-bind="{name: 'check2.svg', type: 'primary', size: 22}" v-if="v.status==='success'"></SvgIcon>
        <SvgIcon v-bind="{name: 'error.svg', type: 'danger', size: 22}" v-else-if="v.status==='error'"></SvgIcon>
      </span>
      <span class="icon-text has-text-danger ml-6" v-if="v.error">
        <SvgIcon v-bind="{name: 'error.svg', type: 'danger', size: 22}"></SvgIcon>
        <span class="ml-1">{{ v.text }}</span>
      </span>
      <button class="button is-small is-primary is-loading px-0 ml-4" v-if="v.status==='uploading'">Loading</button>
    </p>
  </div>
</template>
<script>
export default {
  props: ['files'],
  data() {
    return {
      vfiles: this.$copy(this.files),
      data: []
    }
  },
  created() {
    let found = this.$find(this.vfiles, {error: true})
    if(!found) this.upload()
  },
  methods: {
    async doUpload(v, i) {
      let file = this.files[i]
      let rs = await this.$insertapi('upload', file.form, undefined, false)
      v.status = rs==='error'? 'error' : 'success'
      this.vfiles[i] = v
      let obj = rs.rows[0]
      obj.source = file
      this.data.push(obj)
      this.checkDone()
    },
    async upload() {
      this.vfiles.map((v,i)=>{
        v.status = 'uploading'
        this.vfiles[i] = v
        this.doUpload(v, i)
      })
    },
    checkDone() {
      let found = this.vfiles.find(v=>!v.status || v.status==='uploading')
      if(!found) {
        this.$emit('files', this.data)
        this.$emit('modalevent', {name: 'files', data: this.data})
      }
    },
  }
}
</script>