<template>
  <div style="height: 100%">
    <w-grid
      ref="gridRef"
      :title="$t('re.parameter.grid.title')"
      dnd-mode="server"
      dense-body
      class="px-1"
      hide-bottom
      :config-button="false"
      selection="multiple"
      db-click-operation="edit"
      :checkbox-selection="true"
      :tree="false"
      :fetch-data-url="Environment.apiContextPath('/api/re/model/parameter/findParametersByModelId?modelId=' + model.id)"
      :data-url="Environment.apiContextPath('/api/re/model/parameter')"
      :pageable="false"
      :toolbar-configure="{ noIcon: false }"
      :toolbar-actions="[
        'refresh',
        'separator',
        [
          {
            extend: 'add',
            click: undefined,
            enableIf: (args) => {
              return !readOnly;
            },
          },
          {
            extend: 'add',
            name: 'constant',
            label: $t('re.parameter.grid.toolbar.add.constant'),
            icon: 'bi-tag',
            afterClick: (args) => {
              args.grid.getEditorForm().setFieldValue('type', 'CONSTANT');
            },
          },
          'separator',
          {
            extend: 'add',
            name: 'in',
            label: $t('re.parameter.grid.toolbar.add.in'),
            icon: 'bi-terminal',
            afterClick: (args) => {
              args.grid.getEditorForm().setFieldValue('type', 'IN');
            },
          },
          {
            extend: 'add',
            name: 'inOption',
            label: $t('re.parameter.grid.toolbar.add.inOption'),
            icon: 'bi-list-check',
            afterClick: (args) => {
              args.grid.getEditorForm().setFieldValue('type', 'IN_OPTION');
              args.grid.getEditorForm().setFieldValue('valueTypeSelect', 'java.lang.String');
            },
          },
          {
            name: 'indicator',
            label: $t('re.parameter.grid.toolbar.add.indicator'),
            icon: 'bi-link',
            click: (args) => {
              selectIndicatorDialogRef.open();
            },
          },
          'separator',
          {
            extend: 'add',
            name: 'intermediate',
            label: $t('re.parameter.grid.toolbar.add.intermediate'),
            icon: 'bi-superscript',
            afterClick: (args) => {
              args.grid.getEditorForm().setFieldValue('type', 'INTERMEDIATE');
            },
          },
          {
            extend: 'add',
            name: 'out',
            label: $t('re.parameter.grid.toolbar.add.out'),
            icon: 'bi-shuffle',
            afterClick: (args) => {
              args.grid.getEditorForm().setFieldValue('type', 'OUT');
            },
          },
          'separator',
          {
            extend: 'add',
            name: 'ruleResult',
            label: $t('re.parameter.grid.toolbar.add.ruleResult'),
            icon: 'bi-sliders',
            afterClick: (args) => {
              args.grid.getEditorForm().setFieldValue('type', 'RULE_RESULT');
            },
          },
          {
            extend: 'add',
            name: 'singleRuleResult',
            label: $t('re.parameter.grid.toolbar.add.singleRuleResult'),
            icon: 'bi-lightning',
            afterClick: (args) => {
              args.grid.getEditorForm().setFieldValue('type', 'SINGLE_RULE_RESULT');
            },
          },
          'separator',
          {
            name: 'importPmml',
            label: $t('re.parameter.grid.toolbar.add.importPmml'),
            icon: 'bi-file-earmark-text',
          },
        ],
        'separator',
        [
          {
            extend: 'clone',
            enableIf: (args: any) => {
              return args.selected;
            },
            click: undefined,
          },
          {
            extend: 'clone',
            enableIf: (args) => {
              return !readOnly && args.selected && args.selected.type !== 'INDICATOR';
            },
          },
          {
            extend: 'clone',
            name: 'deepClone',
            label: $t('deepClone'),
            icon: 'bi-copy',
            enableIf: (args) => {
              return !readOnly && args.selected && args.selected.type !== 'INDICATOR';
            },
            click: (args) => {
              DialogManager.confirm($t('re.parameter.grid.toolbar.deepClone.tip'), () => {
                axios.post(Environment.apiContextPath('/api/re/model/parameter/deepClone/' + args.selected.id)).then(() => {
                  gridRef.refresh();
                });
              });
            },
          },
        ],
        {
          extend: 'edit',
          enableIf: (args) => {
            return !readOnly && args.selected && args.selected.type !== 'INDICATOR';
          },
          click: (args: any) => {
            const row = args.selected;
            if (row.type === 'INDICATOR') {
              NotifyManager.warn($t('re.parameter.tip.indicatorParameterCanNotEditable'));
              return;
            }
            args._click(args);
          },
        },
        {
          extend: 'remove',
          enableIf: (args) => {
            return !readOnly && args.selected;
          },
        },
        'separator',
        {
          name: 'move',
          label: $t('re.parameter.grid.toolbar.move'),
          icon: 'bi-share-fill',
          enableIf: (args) => {
            return !readOnly && args.selected;
          },
          click: (args) => {
            moveParameterDialogRef.open();
          },
        },
        'separator',
        ...templateImportAndExportManager.getToolbarAction(),
        'separator',
        'view',
        'separator',
        'export',
      ]"
      :columns="[
        { width: '100%', name: 'name', label: $t('name') },
        { width: 130, name: 'code', label: $t('code'), showIf: false },
        { width: 100, name: 'type', label: $t('type'), format: EngineEnums.ParameterType.formater },
        {
          width: 200,
          name: 'indicatorInfo',
          label: $t('re.lib.grid.title'),
          format: LibManager.getFormater(),
        },
        ...valueTypeManager.getColumns(),
      ]"
      :editor="{
        dialog: {
          width: '600px',
        },
        form: {
          colsNum: 1,
          fields: [
            { name: 'model', label: $t('modelId'), type: 'w-text', defaultValue: model.id, showIf: false },
            {
              name: 'type',
              label: $t('type'),
              type: 'w-select',
              showIf: false,
              options: EngineEnums.ParameterType.options,
              'onUpdate:modelValue': (value) => {},
            },
            { name: 'code', label: $t('code'), type: 'w-text' },
            { name: 'name', label: $t('name'), type: 'w-text', requiredIf: true },
            { name: 'description', label: $t('description'), type: 'w-text' },
            ...valueTypeManager.getEditorFields(),
            { name: 'order', label: $t('order'), type: 'w-number' },
          ],
        },
      }"
      :viewer="{
        panel: {
          columnNum: 1,
          fields: [
            { name: 'model', label: $t('re.parameter.grid.entity.model') },
            { name: 'type', label: $t('type'), format: Formater.none() },
            { name: 'id', label: $t('id') },
            { name: 'code', label: $t('code') },
            { name: 'name', label: $t('name') },
            { name: 'description', label: $t('description') },
            { name: 'libCode', label: $t('re.parameter.grid.entity.libCode') },
            { name: 'libVersion', label: $t('re.parameter.grid.entity.libVersion') },
            { name: 'indicatorCode', label: $t('re.parameter.grid.entity.indicatorCode') },
            ...valueTypeManager.getViewerFields(),
            { name: 'order', label: $t('order') },
            ...CorporationAuditorEntityManager.getViewerFields(),
          ],
        },
      }"
      @row-click="
        (args) => {
          emit('rowClick', args);
        }
      "
      @before-request-data="
        (args) => {
          emit('beforeRequestData');
        }
      "
      @after-editor-open="
        (args: any) => {
          valueTypeManager.afterEditorOpen(args);
        }
      "
    ></w-grid>
    <SelectIndicatorDialog ref="selectIndicatorDialogRef" :parameter-grid="gridRef" :model-id="model.id"></SelectIndicatorDialog>
    <MoveParameterDialog ref="moveParameterDialogRef" :parameter-grid="gridRef" :resource="resource"></MoveParameterDialog>
    <TemplateImportAndExportDialog
      ref="templateImportAndExportDialogRef"
      :download-url="Environment.apiContextPath('/api/re/template/downloadParameterTemplate/' + props.model?.id)"
      :upload-url="Environment.apiContextPath('/api/re/template/uploadParameterTemplate/' + props.model?.id)"
      @after-imported="
        () => {
          gridRef.refresh();
        }
      "
    ></TemplateImportAndExportDialog>
  </div>
</template>
<script setup lang="ts">
import 'tailwindcss/utilities.css';
import { onMounted, ref } from 'vue';
import { axios, Environment, DialogManager, NotifyManager, Formater, CorporationAuditorEntityManager } from 'platform-core';
import SelectIndicatorDialog from '@/views/shared/SelectIndicatorDialog.vue';
import MoveParameterDialog from '@/views/shared/MoveParameterDialog.vue';
import TemplateImportAndExportDialog from '@/views/shared/TemplateImportAndExportDialog.vue';
import { ValueTypeManager } from '@/views/shared/ValueTypeManager';
import { LibManager } from '@/views/shared/LibManager';
import { TemplateImportAndExportManager } from '@/views/shared/TemplateImportAndExportManager';
import { EngineEnums } from '@/views/shared/enums/EngineEnums';

const props = defineProps({
  resource: { type: Object, default: undefined },
  model: { type: Object, default: undefined },
  readOnly: { type: Boolean, default: false },
});

const emit = defineEmits<{
  (e: 'rowClick', args): void;
  (e: 'beforeRequestData', requestParams: URLSearchParams | any, callback: any): void;
}>();

const gridRef = ref();
const selectIndicatorDialogRef = ref();
const moveParameterDialogRef = ref();
const templateImportAndExportDialogRef = ref();
const valueTypeManager = new ValueTypeManager();
const templateImportAndExportManager = new TemplateImportAndExportManager(templateImportAndExportDialogRef);

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

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

defineExpose({
  refresh,
});

await EngineEnums.init();
await valueTypeManager.init();
await LibManager.load();
</script>
