<template>
  <div style="height: 100%">
    <w-grid
      ref="gridRef"
      :title="$t('re.resources.designer.processor.grid.title')"
      draggable="server"
      dense-body
      class="px-1"
      hide-bottom
      :config-button="false"
      selection="multiple"
      db-click-operation="customEdit"
      :checkbox-selection="true"
      :tree="false"
      :fetch-data-url="Environment.apiContextPath('/api/re/model/parameter/processor/findByParameterId?parameterId=' + parameter.id)"
      :data-url="Environment.apiContextPath('/api/re/model/parameter/processor')"
      :pageable="false"
      :toolbar-configure="{ noIcon: false }"
      :toolbar-actions="[
        'refresh',
        'separator',
        [
          {
            extend: 'add',
            enableIf: (arg) => {
              return !readOnly;
            },
            click: undefined,
          },
          ObjectProperties.getToolbarAction(parameter),
          OptionValue.getToolbarAction(parameter),
          MathFormula.getToolbarAction(parameter),
          Arithmetic.getToolbarAction(parameter),
          Ternary.getToolbarAction(parameter),
          WhenThen.getToolbarAction(parameter),
          NumberRange.getToolbarAction(parameter),
          ConditionRange.getToolbarAction(parameter),
          DecisionTable2c.getToolbarAction(parameter),
          DecisionTable.getToolbarAction(parameter),
          DecisionTree.getToolbarAction(parameter),
          ExecutionFlow.getToolbarAction(parameter),
          Pmml.getToolbarAction(parameter),
          GroovyScript.getToolbarAction(parameter),
          Sql.getToolbarAction(parameter),
          Rule.getToolbarAction(parameter),
          SingleRule.getToolbarAction(parameter),
        ],
        {
          extend: 'edit',
          name: 'customEdit',
          enableIf: (arg) => {
            return arg.selected;
          },
          click: (arg) => {
            const type = arg.selected?.type;
            if ('DECISION_TREE' === type) {
              decisionTreeDialogRef.open(parameter.id, arg.selected?.id);
            } else if ('EXECUTION_FLOW' === type) {
              executionFlowDialogRef.open(parameter.id, arg.selected?.id);
            } else {
              arg._click(arg);
            }
          },
        },
        {
          extend: 'remove',
          enableIf: (arg) => {
            return !readOnly && arg.selected;
          },
        },
        'separator',
        {
          name: 'enable',
          label: (arg) => {
            if (arg.selected?.enable) {
              return $t('disable');
            }
            return $t('enable');
          },
          icon: (arg) => {
            if (arg.selected?.enable) {
              return 'bi-x';
            }
            return 'bi-check';
          },
          enableIf: (arg) => {
            return !readOnly && arg.selected;
          },
          click: (arg) => {
            const data = arg.selected;
            data.enable = !data.enable;
            axios.put(Environment.apiContextPath('/api/re/model/parameter/processor/' + data.id), data).then((response) => {
              gridRef.updateLocalData(response.data);
            });
          },
        },
        'separator',
        'view',
        'separator',
        'export',
      ]"
      :columns="[
        { width: 80, name: 'enable', label: $t('isEnable'), align: 'center', sortable: false, format: Formater.enableTag() },
        { width: 60, name: 'order', label: $t('order'), sortable: false, align: 'right' },
        {
          width: 150,
          name: 'type',
          label: $t('type'),
          sortable: false,
          format: (value, row) => {
            return $t('io.sc.engine.rule.core.enums.ProcessorType.' + value);
          },
        },
        {
          width: '100%',
          name: 'content',
          label: $t('re.resources.designer.processor.grid.entity.content'),
          sortable: false,
          format: (value, row) => {
            switch (row.type) {
              case 'ARITHMETIC':
                return Arithmetic.format(row);
              case 'CONDITION_RANGE':
                return ConditionRange.format(row);
              case 'DECISION_TABLE':
                return DecisionTable.format(row);
              case 'DECISION_TABLE_2C':
                return DecisionTable2c.format(row);
              case 'DECISION_TREE':
                return DecisionTree.format(row);
              case 'EXECUTION_FLOW':
                return ExecutionFlow.format(row);
              case 'GROOVY_SCRIPT':
                return GroovyScript.format(row);
              case 'MATH_FORMULA':
                return MathFormula.format(row);
              case 'NUMBER_RANGE':
                return NumberRange.format(row);
              case 'OBJECT_PROPERTIES':
                return ObjectProperties.format(row);
              case 'OPTION_VALUE':
                return OptionValue.format(row);
              case 'PMML':
                return Pmml.format(row);
              case 'RULE':
                return Rule.format(row);
              case 'SINGLE_RULE':
                return SingleRule.format(row);
              case 'SQL':
                return Sql.format(row);
              case 'TERNARY':
                return Ternary.format(row);
              case 'WHEN_THEN':
                return WhenThen.format(row);
            }
            return '';
          },
        },
      ]"
      :editor="{
        dialog: {
          width: editorDialogWidthRef,
        },
        form: {
          colsNum: 5,
          fields: [
            { colSpan: 5, name: 'parameter', label: 'parameter', type: 'w-text', defaultValue: parameter.id, showIf: false },
            { colSpan: 5, name: 'id', label: $t('id'), type: 'w-text', showIf: false },
            { colSpan: 5, name: 'order', label: $t('order'), type: 'w-number', showIf: false },
            { colSpan: 5, name: 'type', label: $t('type'), type: 'w-text', showIf: false },
            { colSpan: 5, name: 'description', label: $t('description'), type: 'w-text', showIf: false },
            { colSpan: 5, name: 'enable', label: $t('enable'), type: 'w-checkbox', defaultValue: true, showIf: false },

            ...Arithmetic.getEditorFields(),
            ...ConditionRange.getEditorFields({ gridRef }),
            ...DecisionTable.getEditorFields({ gridRef }),
            ...DecisionTable2c.getEditorFields({ gridRef }),
            ...DecisionTree.getEditorFields(),
            ...ExecutionFlow.getEditorFields(),
            ...GroovyScript.getEditorFields(),
            ...MathFormula.getEditorFields(),
            ...NumberRange.getEditorFields({ gridRef }),
            ...ObjectProperties.getEditorFields({ gridRef, objectPropertiesMatcherDialogRef }),
            ...OptionValue.getEditorFields(),
            ...Pmml.getEditorFields({}),
            ...Rule.getEditorFields({}),
            ...SingleRule.getEditorFields({}),
            ...Sql.getEditorFields({ gridRef }),
            ...Ternary.getEditorFields(),
            ...WhenThen.getEditorFields(),
          ],
        },
      }"
      :viewer="{
        panel: {
          columnNum: 1,
          fields: [
            { name: 'order', label: $t('order') },
            { name: 'id', label: $t('id'), primaryKey: true },
            { name: 'parameter', label: $t('parameter') },
            { name: 'description', label: $t('description') },
            { name: 'enable', label: $t('enable') },
            { name: 'type', label: $t('type') },

            ...Arithmetic.getViewerFields(),
            ...ConditionRange.getViewerFields(),
            ...DecisionTable.getViewerFields(),
            ...DecisionTable2c.getViewerFields(),
            ...DecisionTree.getViewerFields(),
            ...ExecutionFlow.getViewerFields(),
            ...GroovyScript.getViewerFields(),
            ...MathFormula.getViewerFields(),
            ...NumberRange.getViewerFields(),
            ...ObjectProperties.getViewerFields(),
            ...OptionValue.getViewerFields(),
            ...Pmml.getViewerFields(),
            ...Rule.getViewerFields(),
            ...SingleRule.getViewerFields(),
            ...Sql.getViewerFields(),
            ...Ternary.getViewerFields(),
            ...WhenThen.getViewerFields(),

            { name: 'dataComeFrom', label: $t('dataComeFrom') },
            { name: 'creator', label: $t('creator') },
            { name: 'createDate', label: $t('createDate') },
            { name: 'lastModifier', label: $t('lastModifier') },
            { name: 'lastModifyDate', label: $t('lastModifyDate'), format: Formater.none() },
          ],
        },
      }"
      @before-editor-data-submit="
        (args) => {
          switch (args.data.type) {
            case 'ARITHMETIC':
              return Arithmetic.beforeEditorDataSubmit(args);
            case 'CONDITION_RANGE':
              return ConditionRange.beforeEditorDataSubmit(args);
            case 'DECISION_TABLE':
              return DecisionTable.beforeEditorDataSubmit(args);
            case 'DECISION_TABLE_2C':
              return DecisionTable2c.beforeEditorDataSubmit(args);
            case 'DECISION_TREE':
              return DecisionTree.beforeEditorDataSubmit(args);
            case 'EXECUTION_FLOW':
              return ExecutionFlow.beforeEditorDataSubmit(args);
            case 'GROOVY_SCRIPT':
              return GroovyScript.beforeEditorDataSubmit(args);
            case 'MATH_FORMULA':
              return MathFormula.beforeEditorDataSubmit(args);
            case 'NUMBER_RANGE':
              return NumberRange.beforeEditorDataSubmit(args);
            case 'OBJECT_PROPERTIES':
              return ObjectProperties.beforeEditorDataSubmit(args);
            case 'OPTION_VALUE':
              return OptionValue.beforeEditorDataSubmit(args);
            case 'PMML':
              return Pmml.beforeEditorDataSubmit(args);
            case 'RULE':
              return Rule.beforeEditorDataSubmit(args);
            case 'SINGLE_RULE':
              return SingleRule.beforeEditorDataSubmit(args);
            case 'SQL':
              return Sql.beforeEditorDataSubmit(args);
            case 'TERNARY':
              return Ternary.beforeEditorDataSubmit(args);
            case 'WHEN_THEN':
              return WhenThen.beforeEditorDataSubmit(args);
          }
        }
      "
      @after-editor-open="
        (args) => {
          args.type = 'parameter';
          args.parameter = parameter;

          editorDialogWidthRef = '70%';
          switch (args.grid.getEditorForm().getFieldValue('type')) {
            case 'ARITHMETIC':
              return Arithmetic.afterEditorOpen(args);
            case 'CONDITION_RANGE':
              return ConditionRange.afterEditorOpen(args);
            case 'DECISION_TABLE':
              return DecisionTable.afterEditorOpen(args);
            case 'DECISION_TABLE_2C':
              return DecisionTable2c.afterEditorOpen(args);
            case 'DECISION_TREE':
              return DecisionTree.afterEditorOpen(args);
            case 'EXECUTION_FLOW':
              return ExecutionFlow.afterEditorOpen(args);
            case 'GROOVY_SCRIPT':
              return GroovyScript.afterEditorOpen(args);
            case 'MATH_FORMULA':
              return MathFormula.afterEditorOpen(args);
            case 'NUMBER_RANGE':
              return NumberRange.afterEditorOpen(args);
            case 'OBJECT_PROPERTIES':
              return ObjectProperties.afterEditorOpen(args);
            case 'OPTION_VALUE':
              editorDialogWidthRef = '40%';
              return OptionValue.afterEditorOpen(args);
            case 'PMML':
              return Pmml.afterEditorOpen(args);
            case 'RULE':
              return Rule.afterEditorOpen(args);
            case 'SINGLE_RULE':
              return SingleRule.afterEditorOpen(args);
            case 'SQL':
              editorDialogWidthRef = '80%';
              return Sql.afterEditorOpen(args);
            case 'TERNARY':
              return Ternary.afterEditorOpen(args);
            case 'WHEN_THEN':
              return WhenThen.afterEditorOpen(args);
          }
        }
      "
    ></w-grid>
    <DecisionTreeDialog ref="decisionTreeDialogRef"></DecisionTreeDialog>
    <ExecutionFlowDialog ref="executionFlowDialogRef"></ExecutionFlowDialog>
    <ObjectPropertiesMatcherDialog
      ref="objectPropertiesMatcherDialogRef"
      target-type="parameter"
      :target="parameter"
      @after-matched="
        (objectProperties) => {
          const grid = gridRef.getEditorForm().getFieldComponent('objectProperties');
          grid.setLocalData(objectProperties);
        }
      "
    ></ObjectPropertiesMatcherDialog>
  </div>
</template>
<script setup lang="ts">
import 'tailwindcss/utilities.css';
import { ref, onMounted } from 'vue';
import { $t, axios, Environment, Formater } from 'platform-core';
import { PlaceHolder } from '@/utils/PlaceHolder';
import DecisionTreeDialog from './DecisionTreeDialog.vue';
import ExecutionFlowDialog from './ExecutionFlowDialog.vue';
import ObjectPropertiesMatcherDialog from '@/views/shared/ObjectPropertiesMatcherDialog.vue';
import {
  Arithmetic,
  ConditionRange,
  DecisionTable,
  DecisionTable2c,
  DecisionTree,
  ExecutionFlow,
  GroovyScript,
  MathFormula,
  NumberRange,
  ObjectProperties,
  OptionValue,
  Pmml,
  Rule,
  SingleRule,
  Sql,
  Ternary,
  WhenThen,
} from '@/views/shared/processors';

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

const gridRef = ref();
const editorDialogWidthRef = ref('50%');
const decisionTreeDialogRef = ref();
const executionFlowDialogRef = ref();
const objectPropertiesMatcherDialogRef = ref();

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

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

defineExpose({
  refresh,
});
</script>
