<template>
  <w-dialog ref="dialogRef" :title="$t('re.resources.importSample.dialog.title')" width="900px" :can-maximize="false">
    <div class="px-2">
      <w-grid
        ref="gridRef"
        :height="300"
        :title="$t('re.resources.importSample.grid.title')"
        selection="multiple"
        :full-screen-button="false"
        :tree="true"
        dense-body
        :toolbar-configure="{ noIcon: false }"
        :toolbar-actions="[
          'refresh',
          'separator',
          'expand',
          'separator',
          {
            name: 'import',
            label: $t('re.resources.importSample.grid.toolbar.import'),
            icon: 'bi-database-up',
            enableIf: (arg) => {
              return arg.ticked;
            },
            click: (arg) => {
              if (arg.tickeds && arg.tickeds.length > 0) {
                const ids = Tools.extractProperties(arg.tickeds, 'id');
                console.log(ids);
                DialogManager.confirm($t('re.resources.importSample.grid.toolbar.import.tip'), () => {
                  axios.post(Environment.apiContextPath('/api/re/resource/createExample'), ids).then(() => {
                    close();
                    emit('afterImported');
                  });
                });
              }
            },
          },
        ]"
        :query-form-fields="[]"
        :auto-fetch-data="false"
        :fetch-data-url="Environment.apiContextPath('/api/re/resource/listResourceExampleContributionItems')"
        foreign-key="parentId"
        :columns="[
          {
            width: 200,
            name: 'name',
            label: $t('name'),
            format: (value, row) => {
              return $t(row.id);
            },
          },
          {
            width: '100%',
            name: 'description',
            label: $t('description'),
            format: (value, row) => {
              return $t(row.id + '.description');
            },
          },
        ]"
      ></w-grid>
    </div>
  </w-dialog>
</template>
<script setup lang="ts">
import { ref, nextTick } from 'vue';
import { axios, Environment, DialogManager, Tools } from 'platform-core';

const emit = defineEmits<{
  (e: 'afterImported', evt: Event): void;
}>();

const dialogRef = ref();
const gridRef = ref();

const open = () => {
  dialogRef.value.show();
  nextTick(() => {
    gridRef.value.refresh();
  });
};

const close = () => {
  dialogRef.value.hide();
};

defineExpose({
  open,
  close,
});
</script>
