<template>
  <w-dialog
    ref="dialogRef"
    :title="$t('system.shared.selectRole.dialog.title')"
    width="800px"
    height="500px"
    :can-maximize="false"
    :buttons="[
      {
        label: $t('confirm'),
        click: () => {
          const ids = Tools.extractProperties(gridRef.getSelectedRows(), 'id');
          emit('afterSelected', ids, dialogRef);
        },
      },
    ]"
  >
    <div class="px-2">
      <w-grid
        ref="gridRef"
        :title="$t('system.shared.selectRole.dialog.grid.title')"
        selection="multiple"
        :full-screen-button="false"
        :toolbar-configure="{ noIcon: false }"
        :toolbar-actions="['query', 'refresh']"
        :query-form-fields="[
          { name: 'code', label: $t('code'), type: 'text' },
          { name: 'name', label: $t('name'), type: 'text' },
          {
            name: 'enable',
            label: $t('enable'),
            type: 'select',
            options: Options.yesNo(),
            queryOperator: 'equals',
          },
          {
            name: 'dataComeFrom',
            label: $t('dataComeFrom'),
            type: 'select',
            options: Options.enum(DataComeFromEnum),
            queryOperator: 'equals',
          },
        ]"
        :auto-fetch-data="false"
        :fetch-data-url="fetchDataUrl + '?' + foreignKey + '=' + foreignValue"
        :columns="[
          { name: 'code', label: $t('code') },
          { name: 'name', label: $t('name') },
          {
            name: 'status',
            label: t('status'),
            format: Formater.enableTag(),
          },
          { name: 'lastModifier', label: t('lastModifier') },
          { name: 'lastModifyDate', label: t('lastModifyDate') },
        ]"
      ></w-grid>
    </div>
  </w-dialog>
</template>
<script setup lang="ts">
import { ref, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { Environment, Tools, EnumTools, Options, Formater } from 'platform-core';

const props = defineProps({
  opener: { type: Object, default: undefined },
  fetchDataUrl: { type: String, default: '' },
  foreignKey: { type: String, default: '' },
  foreignValue: { type: String, default: '' },
});

const emit = defineEmits<{
  (e: 'afterSelected', ids: string[], dialogComponent: any): void;
}>();

const { t } = useI18n();

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

const open = (foreignKey: string) => {
  foreignKeyRef.value = foreignKey;
  dialogRef.value.show();

  nextTick(() => {
    gridRef.value.refresh();
  });
};

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

defineExpose({
  open,
  close,
});

const DataComeFromEnum = await EnumTools.fetch('io.sc.platform.orm.api.enums.DataComeFrom');
</script>
