<template>
  <w-grid
    ref="gridRef"
    :title="$t('re.validator.grid.title')"
    dnd-mode="server"
    dense-body
    class="px-1"
    hide-bottom
    :config-button="false"
    selection="multiple"
    :checkbox-selection="true"
    db-click-operation="edit"
    :tree="false"
    :fetch-data-url="dataUrl + '?' + (type === 'indicator' ? 'indicator' : 'parameter') + '=' + owner.id"
    :data-url="dataUrl"
    :pageable="false"
    :toolbar-configure="{ noIcon: false }"
    :toolbar-actions="[
      'refresh',
      'separator',
      {
        extend: 'add',
        enableIf: (args: any) => {
          return !readOnly;
        },
      },
      {
        extend: 'edit',
        enableIf: (args: any) => {
          return !readOnly && args.selected;
        },
      },
      {
        extend: 'remove',
        enableIf: (args: any) => {
          return !readOnly && args.selected;
        },
      },
      'separator',
      'view',
      'separator',
      'export',
    ]"
    :columns="[
      { width: 60, name: 'order', label: $t('order'), sortable: false, align: 'right' },
      { width: 100, name: 'type', label: $t('type'), sortable: false, format: EngineEnums.ValidatorType.formater },
      {
        width: 300,
        name: 'content',
        label: $t('re.validator.grid.entity.content'),
        sortable: false,
        format: (value, row) => {
          const type = row.type;
          if (type == 'EMPTY' || type == 'NOT_EMPTY' || type == 'TRUE' || type == 'FALSE' || type == 'EMAIL') {
            return '';
          } else if (type == 'INTEGER_RANGE' || type == 'DECIMAL_RANGE' || type == 'LENGTH_RANGE' || type == 'DATE_RANGE') {
            return Tools.generateIntervalRange(row.minInclude, row.minValue, row.maxValue, row.maxInclude);
          } else if (type == 'PATTERN') {
            return row.pattern;
          } else if (type == 'EXPRESSION') {
            return PlaceHolder.replace(row.expression);
          }
          return value;
        },
      },
      { width: '100%', name: 'tip', label: $t('re.validator.grid.entity.tip'), sortable: false },
    ]"
    :editor="{
      dialog: {
        width: '600px',
      },
      form: {
        colsNum: 1,
        fields: [
          { name: 'parameter', label: 'parameter', type: 'w-text', defaultValue: owner.id, showIf: false },
          { name: 'indicator', label: 'indicator', type: 'w-text', defaultValue: owner.id, showIf: false },
          { name: 'id', label: $t('id'), type: 'w-text', showIf: false },
          {
            name: 'description',
            label: $t('description'),
            type: 'w-text',
          },
          { name: 'type', label: $t('type'), type: 'w-select', options: ValueTypeAndValidatorTypeMapping[owner.valueType] },
          {
            name: 'minValue',
            label: $t('minValue'),
            type: 'w-text',
            showIf: (args: any) => {
              const type = args.form.getFieldValue('type');
              if (type == 'INTEGER_RANGE' || type == 'DECIMAL_RANGE' || type == 'LENGTH_RANGE' || type == 'DATE_RANGE') {
                return true;
              }
              return false;
            },
          },
          {
            name: 'minInclude',
            label: $t('isMinValueInclude'),
            type: 'w-checkbox',
            showIf: (args: any) => {
              const type = args.form.getFieldValue('type');
              if (type == 'INTEGER_RANGE' || type == 'DECIMAL_RANGE' || type == 'LENGTH_RANGE' || type == 'DATE_RANGE') {
                return true;
              }
              return false;
            },
          },
          {
            name: 'maxValue',
            label: $t('maxValue'),
            type: 'w-text',
            showIf: (args: any) => {
              const type = args.form.getFieldValue('type');
              if (type == 'INTEGER_RANGE' || type == 'DECIMAL_RANGE' || type == 'LENGTH_RANGE' || type == 'DATE_RANGE') {
                return true;
              }
              return false;
            },
          },
          {
            name: 'maxInclude',
            label: $t('isMaxValueInclude'),
            type: 'w-checkbox',
            showIf: (args: any) => {
              const type = args.form.getFieldValue('type');
              if (type == 'INTEGER_RANGE' || type == 'DECIMAL_RANGE' || type == 'LENGTH_RANGE' || type == 'DATE_RANGE') {
                return true;
              }
              return false;
            },
          },
          {
            name: 'pattern',
            label: $t('RegExp'),
            type: 'w-text',
            showIf: (args: any) => {
              const type = args.form.getFieldValue('type');
              if (type == 'PATTERN') {
                return true;
              }
              return false;
            },
          },
          {
            name: 'expression',
            label: $t('expression'),
            type: 'w-code-mirror',
            lang: 'java',
            rows: 5,
            placeholder: true,
            lineWrap: true,
            lineBreak: false,
            autoCompletion: autoCompletionManager.autoCompletion(),
            userDefinedFunctions: userDefinedFunctionsManager.userDefinedFunctions(),
            showIf: (arg) => {
              const type = arg.form.getFieldValue('type');
              if (type == 'EXPRESSION') {
                return true;
              }
              return false;
            },
          },
          {
            name: 'tip',
            label: $t('re.validator.grid.entity.tip'),
            type: 'w-text',
          },
          { name: 'order', label: $t('order'), type: 'w-number' },
        ],
      },
    }"
    :viewer="{
      panel: {
        columnNum: 1,
        fields: [
          { name: 'id', label: $t('id') },
          { name: 'order', label: $t('order') },
          { name: 'type', label: $t('type'), format: Formater.none() },
          { name: 'description', label: $t('description') },
          { name: 'tip', label: $t('re.validator.grid.entity.tip') },
          { name: 'minInclude', label: $t('isMinValueInclude') },
          { name: 'minValue', label: $t('minValue') },
          { name: 'maxValue', label: $t('maxValue') },
          { name: 'maxInclude', label: $t('isMaxValueInclude') },
          { name: 'pattern', label: $t('RegExp') },
          ...CorporationAuditorEntityManager.getViewerFields(),
        ],
      },
    }"
    @after-editor-open="
      (args: any) => {
        if (type === 'parameter') {
          autoCompletionManager.load(Environment.apiContextPath('/api/re/common/autoCompletionByParameterId/' + owner.id));
        } else if (type === 'indicator') {
          autoCompletionManager.load(Environment.apiContextPath('/api/re/common/autoCompletionByIndicatorId/' + owner.id));
        }
        userDefinedFunctionsManager.load();
      }
    "
  ></w-grid>
</template>
<script setup lang="ts">
import 'tailwindcss/utilities.css';
import { ref, onMounted } from 'vue';
import { $t, Environment, Formater, Tools, CorporationAuditorEntityManager } from 'platform-core';
import { PlaceHolder } from '@/utils/PlaceHolder';
import { AutoCompletionManager } from '@/views/shared/AutoCompletionManager';
import { UserDefinedFunctionsManager } from '@/views/shared/UserDefinedFunctionsManager';
import { EngineEnums } from '@/views/shared/enums/EngineEnums';

const props = defineProps({
  type: { type: String, default: undefined },
  dataUrl: { type: String, default: undefined },
  owner: { type: Object, default: undefined },
  readOnly: { type: Boolean, default: false },
});

const emit = defineEmits<{
  (e: 'rowClick', evt: Event, row: any, index: number): void;
  (e: 'beforeRequestData', requestParams: URLSearchParams | any, callback: any): void;
}>();

const gridRef = ref();
const autoCompletionManager = new AutoCompletionManager();
const userDefinedFunctionsManager = new UserDefinedFunctionsManager();

const ValueTypeAndValidatorTypeMapping = {
  'java.lang.Boolean': [
    { value: 'NOT_EMPTY', label: $t('io.sc.engine.rule.core.enums.ValidatorType.NOT_EMPTY') },
    { value: 'EMPTY', label: $t('io.sc.engine.rule.core.enums.ValidatorType.EMPTY') },
    { value: 'TRUE', label: $t('io.sc.engine.rule.core.enums.ValidatorType.TRUE') },
    { value: 'FALSE', label: $t('io.sc.engine.rule.core.enums.ValidatorType.FALSE') },
    { value: 'EXPRESSION', label: $t('io.sc.engine.rule.core.enums.ValidatorType.EXPRESSION') },
  ],
  'java.lang.Long': [
    { value: 'NOT_EMPTY', label: $t('io.sc.engine.rule.core.enums.ValidatorType.NOT_EMPTY') },
    { value: 'EMPTY', label: $t('io.sc.engine.rule.core.enums.ValidatorType.EMPTY') },
    { value: 'INTEGER_RANGE', label: $t('io.sc.engine.rule.core.enums.ValidatorType.INTEGER_RANGE') },
    { value: 'EXPRESSION', label: $t('io.sc.engine.rule.core.enums.ValidatorType.EXPRESSION') },
  ],
  'java.math.BigDecimal': [
    { value: 'NOT_EMPTY', label: $t('io.sc.engine.rule.core.enums.ValidatorType.NOT_EMPTY') },
    { value: 'EMPTY', label: $t('io.sc.engine.rule.core.enums.ValidatorType.EMPTY') },
    { value: 'DECIMAL_RANGE', label: $t('io.sc.engine.rule.core.enums.ValidatorType.DECIMAL_RANGE') },
    { value: 'EXPRESSION', label: $t('io.sc.engine.rule.core.enums.ValidatorType.EXPRESSION') },
  ],
  'java.lang.String': [
    { value: 'NOT_EMPTY', label: $t('io.sc.engine.rule.core.enums.ValidatorType.NOT_EMPTY') },
    { value: 'EMPTY', label: $t('io.sc.engine.rule.core.enums.ValidatorType.EMPTY') },
    { value: 'LENGTH_RANGE', label: $t('io.sc.engine.rule.core.enums.ValidatorType.LENGTH_RANGE') },
    { value: 'EMAIL', label: $t('io.sc.engine.rule.core.enums.ValidatorType.EMAIL') },
    { value: 'PATTERN', label: $t('io.sc.engine.rule.core.enums.ValidatorType.PATTERN') },
    { value: 'EXPRESSION', label: $t('io.sc.engine.rule.core.enums.ValidatorType.EXPRESSION') },
  ],
  'java.util.Date': [
    { value: 'NOT_EMPTY', label: $t('io.sc.engine.rule.core.enums.ValidatorType.NOT_EMPTY') },
    { value: 'EMPTY', label: $t('io.sc.engine.rule.core.enums.ValidatorType.EMPTY') },
    { value: 'DATE_RANGE', label: $t('io.sc.engine.rule.core.enums.ValidatorType.DATE_RANGE') },
    { value: 'EXPRESSION', label: $t('io.sc.engine.rule.core.enums.ValidatorType.EXPRESSION') },
  ],
  'java.lang.Object': [
    { value: 'NOT_EMPTY', label: $t('io.sc.engine.rule.core.enums.ValidatorType.NOT_EMPTY') },
    { value: 'EMPTY', label: $t('io.sc.engine.rule.core.enums.ValidatorType.EMPTY') },
    { value: 'EXPRESSION', label: $t('io.sc.engine.rule.core.enums.ValidatorType.EXPRESSION') },
  ],
};

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

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

defineExpose({
  refresh,
});

await EngineEnums.init();
</script>
