<template>
  <div>
    <FileUpload
      :type="['file']"
      @files="getFiles"
    ></FileUpload>
    <DataView
      v-if="vbind"
      v-bind="vbind"
    ></DataView>
  </div>
</template>
<script>
export default {
  props: ["row", "pagename", "api", "setting"],
  data() {
    return {
      vbind: undefined,
      files: undefined,
      pagename1: this.$findpage(),
    };
  },
  async created() {
    this.pagedata = this.$getpage();
    this.files = await this.$getdata(this.api, {
      filter: {
        ref: this.row.id,
        file__type: 1,
      },
    });
    this.vbind = {
      pagename: this.pagename1,
      api: this.api,
      setting: this.setting,
      data: this.$copy(this.files),
    };
  },
  beforeDestroy() {
    this.$clearpage(this.pagename1);
  },
  computed: {
    pagedata: {
      get() {
        return this.$store.state[this.pagename1];
      },
      set(val) {
        this.$store.commit("updateStore", { name: this.pagename1, data: val });
      },
    },
  },
  methods: {
    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, { data: arr, values: found.params.values });
      if (rs === "error") return;
      this.files = this.files.concat(rs);
      this.$store.commit("updateState", {
        name: this.pagename1,
        key: "update",
        data: { data: this.$copy(this.files) },
      });
      if (this.pagename) {
        let vapi = this.api.replace("file", "");
        let ele = await this.$getdata(vapi, { filter: { id: this.row.id }, first: true });
        this.$updatepage(this.pagename, ele);
      }
    },
  },
};
</script>
