<template>
  <div v-if="files" class="is-fullwidth">
    <div class="has-text-right mb-4" v-if="!hideopt">
      <FileUpload :type="['image', 'pdf']" @files="getFiles"></FileUpload>
    </div>
    <div v-if="files.length > 0" class="is-flex is-gap-2 is-flex-wrap-wrap">
      <ChipImage
        v-for="(file, i) in files"
        style="width: 160px"
        @remove="remove(file, i)"
        v-bind="{
          row,
          show,
          pagename,
          api,
          file,
          image: `${$getpath()}download/?name=${file.file__file}&type=file`,
        }"
      />
    </div>
    <div class="mt-3 has-text-grey" v-if="files.length === 0">
      {{ this.isVietnamese ? "Chưa có hình ảnh được tải lên" : "No images uploaded" }}
    </div>
    <Modal @close="showmodal = undefined" v-bind="showmodal" v-if="showmodal"></Modal>
  </div>
</template>
<script>
import { useStore } from "@/stores/index";

export default {
  setup() {
    const store = useStore();
    return { store };
  },
  props: ["row", "pagename", "api", "hideopt", "vapi", "show"],
  data() {
    return {
      showmodal: undefined,
      files: undefined,
    };
  },
  computed: {
    lang() {
      return this.store.lang;
    },
    isVietnamese() {
      return this.store.lang === "vi";
    },
  },
  async created() {
    this.files = await this.$getdata(this.api, { ref: this.row.id }); //file__type: 2
  },
  methods: {
    async remove(v, i) {
      // this.$delete(this.files, i);
      this.files.splice(i, 1);
      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") return;
      this.files = this.files.concat(rs);
      if (this.pagename) {
        let vapi = this.vapi ? this.vapi : this.api.replace("file", "");
        let ele = await this.$getdata(vapi, { id: this.row.id }, undefined, true);
        this.$updatepage(this.pagename, ele);
      }
    },
  },
};
</script>
