<template>
  <div v-if="files">
    <div class="has-text-right" v-if="!hideopt">
      <FileUpload v-bind="{type: 'file', position: position}" @files="getFiles"></FileUpload>
    </div>
  <div>
  <div class="mt-3 has-text-grey fs-15" v-if="files.length===0 && info!==false">
    Chưa có tài liệu được tải lên
  </div>
    <DataView v-bind="vbind" v-else-if="vbind"></DataView>
    </div>
    <Modal @close="showmodal=undefined" v-bind="showmodal" v-if="showmodal"></Modal>
  </div>
</template>
<script>
export default {
  props: ['row', 'pagename', 'api', 'hideopt', 'setting', 'info', 'position'],
  data() {
    return {
      showmodal: undefined,
      files: undefined,
      vbind: undefined
    }
  },
  async created() {
    this.files = await this.$getdata(this.api, {ref: this.row.id, file__type: 1})
    if(this.files.length>0) this.vbind = {api: this.api, setting: this.setting || 'media-fields', data: this.files}
  },
  methods: {
    open() {
      this.showmodal = {component: 'media/Imagebox', width: '70%', title: 'Chọn hình ảnh', height: '500px'}
    },
    async remove(v, i) {
      this.$delete(this.files, i)
      await this.$deleteapi(this.api, v.id)
    },
    async getFiles(files) {
      let arr = files.map(v=>{return {ref: this.row.id, file: v.id}})
      let found = this.$findapi(this.api)
      let rs = await this.$insertapi(this.api, arr, found.params.values)
      if(rs!=='error') {
        this.files = this.files.concat(rs)
        this.vbind = undefined
        setTimeout(()=>this.vbind = {api: this.api, setting: 'media-fields', data: this.files}, 100)
      }
    }
  }
}
</script>