<template>
  <div style="height: 100%">
    <w-grid
      ref="gridRef"
      :title="$t('re.resources.designer.processor.grid.title')"
      dense-body
      class="px-1"
      hide-bottom
      :config-button="false"
      selection="multiple"
      :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,
          },
          {
            extend: 'add',
            name: 'optionValue',
            label: Formater.enum(Enums.ProcessorType)('OPTION_VALUE'),
            icon: 'bi-card-list',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'OPTION_VALUE');
            },
          },
          /*
          {
            extend: 'add',
            name: 'mathFormula',
            label: Formater.enum(Enums.ProcessorType)('MATH_FORMULA'),
            icon: 'bi-calculator',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'MATH_FORMULA');
            },
          },*/
          {
            extend: 'add',
            name: 'arithmetic',
            label: Formater.enum(Enums.ProcessorType)('ARITHMETIC'),
            icon: 'bi-calculator',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'ARITHMETIC');
            },
          },
          {
            extend: 'add',
            name: 'ternary',
            label: Formater.enum(Enums.ProcessorType)('TERNARY'),
            icon: 'bi-question',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'TERNARY');
            },
          },
          {
            extend: 'add',
            name: 'whenThen',
            label: Formater.enum(Enums.ProcessorType)('WHEN_THEN'),
            icon: 'bi-sliders',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'WHEN_THEN');
            },
          },
          {
            extend: 'add',
            name: 'numberRange',
            label: Formater.enum(Enums.ProcessorType)('NUMBER_RANGE'),
            icon: 'bi-justify',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'NUMBER_RANGE');
            },
          },
          {
            extend: 'add',
            name: 'conditionRange',
            label: Formater.enum(Enums.ProcessorType)('CONDITION_RANGE'),
            icon: 'bi-rainbow',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'CONDITION_RANGE');
            },
          },
          {
            extend: 'add',
            name: 'decisionTable2c',
            label: Formater.enum(Enums.ProcessorType)('DECISION_TABLE_2C'),
            icon: 'bi-grid-3x2',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'DECISION_TABLE_2C');
            },
          },
          {
            extend: 'add',
            name: 'decisionTable',
            label: Formater.enum(Enums.ProcessorType)('DECISION_TABLE'),
            icon: 'bi-grid-3x3',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'DECISION_TABLE');
            },
          },
          {
            extend: 'add',
            name: 'decisionTree',
            label: Formater.enum(Enums.ProcessorType)('DECISION_TREE'),
            icon: 'bi-tree',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'DECISION_TREE');
            },
          },
          {
            extend: 'add',
            name: 'executionFlow',
            label: Formater.enum(Enums.ProcessorType)('EXECUTION_FLOW'),
            icon: 'bi-bounding-box-circles',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'EXECUTION_FLOW');
            },
          },
          {
            extend: 'add',
            name: 'pmml',
            label: Formater.enum(Enums.ProcessorType)('PMML'),
            icon: 'bi-filetype-xml',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'PMML');
            },
          },
          {
            extend: 'add',
            name: 'groovyScript',
            label: Formater.enum(Enums.ProcessorType)('GROOVY_SCRIPT'),
            icon: 'bi-code',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'GROOVY_SCRIPT');
            },
          },
          {
            extend: 'add',
            name: 'sql',
            label: Formater.enum(Enums.ProcessorType)('SQL'),
            icon: 'bi-filetype-sql',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'SQL');
            },
          },
          {
            extend: 'add',
            name: 'rule',
            label: Formater.enum(Enums.ProcessorType)('RULE'),
            icon: 'bi-shadows',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'RULE');
            },
          },
          {
            extend: 'add',
            name: 'singleRule',
            label: Formater.enum(Enums.ProcessorType)('SINGLE_RULE'),
            icon: 'bi-noise-reduction',
            enableIf: (arg) => {
              return parameter.type !== 'RULE_RESULT' && parameter.type !== 'SINGLE_RULE_RESULT';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'SINGLE_RULE');
            },
          },
        ],
        {
          extend: 'edit',
          enableIf: (arg) => {
            return arg.selected;
          },
          click: (arg) => {
            const type = arg.selected?.type;
            if ('DECISION_TREE' === type) {
              decisionTreeDialogRef.open(arg.selected?.id);
            } else if ('EXECUTION_FLOW' === type) {
              executionFlowDialogRef.open(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.replaceRow(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: Formater.enum(Enums.ProcessorType) },
        {
          width: '100%',
          name: 'content',
          label: $t('re.resources.designer.processor.grid.entity.content'),
          sortable: false,
          format: (value, row) => {
            const type = row.type;
            if ('OPTION_VALUE' === type) {
              return row.optionCode;
            } else if ('ARITHMETIC' === type) {
              return PlaceHolder.replace(row.arithmetic);
            } else if ('TERNARY' === type) {
              return row.ternaryCondition + ' <b><span>?</span></b> ' + row.ternaryTrue + ' <b><span>:</span></b> ' + row.ternaryFalse;
            } else if ('WHEN_THEN' === type) {
              let str = '';
              if (row.isWhenThenShorted) {
                str += '<span>' + $t('re.resources.designer.processor.grid.entity.isWhenThenShorted') + ', </span>';
              }
              if (row.when) {
                str += '<span>When</span> ' + PlaceHolder.replace(row.when) + ' ';
              }
              if (row.then) {
                str += '<span>Then</span> ' + PlaceHolder.replace(row.then);
              }
              return str;
            } else if ('NUMBER_RANGE' === type) {
              const objs = Tools.json2Object(row.numberRange);
              if (objs) {
                let str = `<div class='border border-b-0'>`;
                str += `<table width='100%'>`;
                for (let i = 0; i < objs.length; i++) {
                  const obj = objs[i];
                  str += '<tr>';
                  if (i == 0) {
                    str += '	<td rowspan=' + objs.length + '>' + PlaceHolder.replace(row.numberRangeVar) + '</td>';
                  }
                  str += '	<td>' + Tools.generateIntervalRange(obj.minIncluded, obj.min, obj.max, obj.maxIncluded) + '</td>';
                  str += '	<td>' + ('' + PlaceHolder.replace('' + obj.value)) + '</td>';
                  str += '</tr>';
                }
                str += '</table>';
                str += '</div>';
                return str;
              }
              return '';
            } else if ('CONDITION_RANGE' === type) {
              const objs = Tools.json2Object(row.conditionRange);
              if (objs) {
                let str = `<div class='border border-b-0'>`;
                str += `<table width='100%'>`;
                for (let i = 0; i < objs.length; i++) {
                  const obj = objs[i];
                  str += '<tr>';
                  str += '	<td>' + PlaceHolder.replace(obj.condition) + '</td>';
                  str += '	<td><span>' + ('' + PlaceHolder.replace(obj.value)) + '</span></td>';
                  str += '</tr>';
                }
                str += '</table>';
                str += `</div>`;
                return str;
              }
              return '';
            } else if ('PMML' === type) {
              return transfromContent(row.pmml);
            } else if ('GROOVY_SCRIPT' === type) {
              return transfromContent(row.groovyScript);
            } else if ('DECISION_TREE' === type) {
              return transfromContent(row.decisionTree);
            } else if ('EXECUTION_FLOW' === type) {
              return transfromContent(row.executionFlow);
            }
          },
        },
      ]"
      :editor="{
        dialog: {
          width: '800px',
        },
        form: {
          colsNum: 1,
          fields: [
            { name: 'parameter', label: 'parameter', type: 'text', defaultValue: parameter.id, hidden: true },
            { name: 'id', label: $t('id'), type: 'text', hidden: true },
            { name: 'order', label: $t('order'), type: 'number', hidden: true },
            { name: 'type', label: $t('type'), type: 'text', hidden: true },
            { name: 'description', label: $t('description'), type: 'text', hidden: true },
            { name: 'enable', label: $t('enable'), type: 'checkbox', defaultValue: true, hidden: true },
            {
              name: 'optionCode',
              label: $t('re.resources.designer.processor.grid.entity.optionCode'),
              type: 'select',
              options: optionOptionsRef,
              showIf: (arg) => {
                return 'OPTION_VALUE' === arg.form.getFieldValue('type');
              },
            } /*
            {
              name: 'mathFormula',
              label: $t('re.resources.designer.processor.grid.entity.mathFormula'),
              type: 'expression',
              showIf: (arg) => {
                return 'MATH_FORMULA' === arg.form.getFieldValue('type');
              },
            },*/,
            {
              name: 'arithmetic',
              label: $t('re.resources.designer.processor.grid.entity.arithmetic'),
              type: 'code-mirror',
              lang: 'java',
              rows: 5,
              placeholder: true,
              autoCompletion: true,
              autoCompletionOptions: autoCompletionOptionsRef,
              extAutoCompletionOptions: GroovyFunctions,
              showIf: (arg) => {
                return 'ARITHMETIC' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'ternaryCondition',
              label: $t('re.resources.designer.processor.grid.entity.ternaryCondition'),
              type: 'code-mirror',
              lang: 'java',
              rows: 1,
              placeholder: true,
              autoCompletion: true,
              autoCompletionOptions: autoCompletionOptionsRef,
              extAutoCompletionOptions: GroovyFunctions,
              showIf: (arg) => {
                return 'TERNARY' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'ternaryTrue',
              label: $t('re.resources.designer.processor.grid.entity.ternaryTrue'),
              type: 'code-mirror',
              lang: 'java',
              rows: 1,
              placeholder: true,
              autoCompletion: true,
              autoCompletionOptions: autoCompletionOptionsRef,
              extAutoCompletionOptions: GroovyFunctions,
              showIf: (arg) => {
                return 'TERNARY' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'ternaryFalse',
              label: $t('re.resources.designer.processor.grid.entity.ternaryFalse'),
              type: 'code-mirror',
              lang: 'java',
              rows: 1,
              placeholder: true,
              autoCompletion: true,
              autoCompletionOptions: autoCompletionOptionsRef,
              extAutoCompletionOptions: GroovyFunctions,
              showIf: (arg) => {
                return 'TERNARY' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'when',
              label: $t('re.resources.designer.processor.grid.entity.when'),
              type: 'code-mirror',
              lang: 'java',
              rows: 1,
              placeholder: true,
              autoCompletion: true,
              autoCompletionOptions: autoCompletionOptionsRef,
              extAutoCompletionOptions: GroovyFunctions,
              showIf: (arg) => {
                return 'WHEN_THEN' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'then',
              label: $t('re.resources.designer.processor.grid.entity.then'),
              type: 'code-mirror',
              lang: 'java',
              rows: 1,
              placeholder: true,
              autoCompletion: true,
              autoCompletionOptions: autoCompletionOptionsRef,
              extAutoCompletionOptions: GroovyFunctions,
              showIf: (arg) => {
                return 'WHEN_THEN' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'isWhenThenShorted',
              label: $t('re.resources.designer.processor.grid.entity.isWhenThenShorted'),
              type: 'checkbox',
              showIf: (arg) => {
                return 'WHEN_THEN' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'numberRangeVar',
              label: $t('re.resources.designer.processor.grid.entity.numberRangeVar'),
              showIf: (arg) => {
                return 'NUMBER_RANGE' === arg.form.getFieldValue('type');
              },
              type: 'code-mirror',
              lang: 'java',
              rows: 1,
              placeholder: true,
              autoCompletion: true,
              autoCompletionOptions: autoCompletionOptionsRef,
              extAutoCompletionOptions: GroovyFunctions,
            },
            {
              name: 'numberRange',
              label: $t('re.resources.designer.processor.grid.entity.numberRange'),
              showIf: (arg) => {
                return 'NUMBER_RANGE' === arg.form.getFieldValue('type');
              },
              type: 'w-grid',
              height: 300,
              denseBody: true,
              draggable: true,
              pageable: false,
              configButton: false,
              toolbarConfigure: { noIcon: false },
              toolbarActions: [
                'add',
                'clone',
                'edit',
                {
                  extend: 'remove',
                  click: (arg) => {
                    const grid = gridRef.getEditorForm().getFieldComponent('numberRange');
                    grid.removeRows(arg.selecteds);
                  },
                },
                'separator',
                {
                  name: 'example',
                  label: $t('example'),
                  icon: 'bi-balloon',
                  click: (arg) => {
                    const grid = gridRef.getEditorForm().getFieldComponent('numberRange');
                    const sampleData = [
                      { uuid: Tools.uuid(), minIncluded: false, min: null, max: 0, maxIncluded: false, value: 1 },
                      { uuid: Tools.uuid(), minIncluded: true, min: 0, max: 1, maxIncluded: false, value: 2 },
                      { uuid: Tools.uuid(), minIncluded: true, min: 1, max: 2, maxIncluded: false, value: 3 },
                      { uuid: Tools.uuid(), minIncluded: true, min: 2, max: 3, maxIncluded: false, value: 4 },
                      { uuid: Tools.uuid(), minIncluded: true, min: 3, max: null, maxIncluded: false, value: 5 },
                      { uuid: Tools.uuid(), minIncluded: false, min: null, max: null, maxIncluded: false, value: 0 },
                    ];
                    grid.setLocalData(sampleData);
                  },
                },
              ],
              primaryKey: 'uuid',
              columns: [
                { width: 200, name: 'uuid', label: 'uuid', hidden: true },
                {
                  width: 60,
                  name: 'minIncluded',
                  label: $t('include'),
                  align: 'center',
                  sortable: false,
                  format: (value) => {
                    if (value) {
                      return '[';
                    } else {
                      return '(';
                    }
                  },
                },
                { width: 100, name: 'min', label: $t('minValue'), align: 'right', sortable: false },
                { width: 100, name: 'max', label: $t('maxValue'), align: 'right', sortable: false },
                {
                  width: 60,
                  name: 'maxIncluded',
                  label: $t('include'),
                  align: 'center',
                  sortable: false,
                  format: (value) => {
                    if (value) {
                      return '[';
                    } else {
                      return ')';
                    }
                  },
                },
                { width: '100%', name: 'value', label: $t('value'), sortable: false },
              ],
              editor: {
                dialog: {
                  width: '600px',
                },
                form: {
                  colsNum: 4,
                  fields: [
                    { name: 'uuid', label: 'uuid', hidden: true, colSpan: 4 },
                    { name: 'min', label: $t('minValue'), type: 'text', colSpan: 3 },
                    { name: 'minIncluded', label: $t('include'), type: 'checkbox' },
                    { name: 'max', label: $t('maxValue'), type: 'text', colSpan: 3 },
                    { name: 'maxIncluded', label: $t('include'), type: 'checkbox' },
                    { name: 'value', label: $t('value'), type: 'number', colSpan: 3 },
                  ],
                },
              },
              onBeforeEditorDataSubmit: (data, callback) => {
                const grid = gridRef.getEditorForm().getFieldComponent('numberRange');
                const form = grid.getEditorForm();
                if ('add' == form.getStatus() || 'clone' == form.getStatus()) {
                  data.uuid = Tools.uuid();
                  grid.addRow(data);
                  callback(false);
                } else if ('edit' == form.getStatus()) {
                  grid.replaceRow(data);
                  callback(false);
                }
              },
            },
            {
              name: 'conditionRange',
              label: $t('re.resources.designer.processor.grid.entity.conditionRange'),
              showIf: (arg) => {
                return 'CONDITION_RANGE' === arg.form.getFieldValue('type');
              },
              type: 'w-grid',
              height: 300,
              denseBody: true,
              draggable: true,
              pageable: false,
              configButton: false,
              toolbarConfigure: { noIcon: false },
              toolbarActions: [
                'add',
                'clone',
                'edit',
                {
                  extend: 'remove',
                  click: (arg) => {
                    const grid = gridRef.getEditorForm().getFieldComponent('conditionRange');
                    grid.removeRows(arg.selecteds);
                  },
                },
                'separator',
                {
                  name: 'example',
                  label: $t('example'),
                  icon: 'bi-balloon',
                  click: (arg) => {
                    const grid = gridRef.getEditorForm().getFieldComponent('conditionRange');
                    const sampleData = [
                      { uuid: Tools.uuid(), condition: '${变量名}<=0', value: '0' },
                      { uuid: Tools.uuid(), condition: '${变量名}>0 && ${变量名}<=50', value: '50' },
                      { uuid: Tools.uuid(), condition: '${变量名}>50 && ${变量名}<=80', value: '80' },
                      { uuid: Tools.uuid(), condition: '${变量名}>80 && ${变量名}<=100', value: '100' },
                      { uuid: Tools.uuid(), condition: '${变量名}>100', value: '60' },
                    ];
                    grid.setLocalData(sampleData);
                  },
                },
              ],
              primaryKey: 'uuid',
              columns: [
                { name: 'uuid', label: 'uuid', hidden: true },
                {
                  name: 'condition',
                  label: $t('condition'),
                  align: 'left',
                  sortable: false,
                  format: (value) => {
                    return PlaceHolder.replace(value);
                  },
                },
                {
                  name: 'value',
                  label: $t('value'),
                  sortable: false,
                  format: (value) => {
                    return PlaceHolder.replace(value);
                  },
                },
              ],
              editor: {
                dialog: {
                  width: '600px',
                },
                form: {
                  colsNum: 1,
                  fields: [
                    { name: 'uuid', label: 'uuid', hidden: true },
                    {
                      name: 'condition',
                      label: $t('condition'),
                      type: 'code-mirror',
                      lang: 'java',
                      rows: 1,
                      placeholder: true,
                      autoCompletion: true,
                      autoCompletionOptions: autoCompletionOptionsRef,
                      extAutoCompletionOptions: GroovyFunctions,
                    },
                    {
                      name: 'value',
                      label: $t('value'),
                      type: 'code-mirror',
                      lang: 'java',
                      rows: 1,
                      placeholder: true,
                      autoCompletion: true,
                      autoCompletionOptions: autoCompletionOptionsRef,
                      extAutoCompletionOptions: GroovyFunctions,
                    },
                  ],
                },
              },
              onBeforeEditorDataSubmit: (data, callback) => {
                const grid = gridRef.getEditorForm().getFieldComponent('conditionRange');
                const form = grid.getEditorForm();
                if ('add' == form.getStatus() || 'clone' == form.getStatus()) {
                  data.uuid = Tools.uuid();
                  grid.addRow(data);
                  callback(false);
                } else if ('edit' == form.getStatus()) {
                  grid.replaceRow(data);
                  callback(false);
                }
              },
            },
            {
              name: 'decisionTable2C',
              label: $t('re.resources.designer.processor.grid.entity.decisionTable2C'),
              type: 'code-mirror',
              rows: 1,
              showIf: (arg) => {
                return 'DECISION_TABLE_2C' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'decisionTable',
              label: $t('re.resources.designer.processor.grid.entity.decisionTable'),
              type: 'code-mirror',
              rows: 1,
              showIf: (arg) => {
                return 'DECISION_TABLE' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'decisionTree',
              label: $t('re.resources.designer.processor.grid.entity.decisionTree'),
              type: 'code-mirror',
              rows: 20,
              lineNumber: true,
              showIf: (arg) => {
                return 'DECISION_TREE' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'executionFlow',
              label: $t('re.resources.designer.processor.grid.entity.executionFlow'),
              type: 'code-mirror',
              rows: 1,
              showIf: (arg) => {
                return 'EXECUTION_FLOW' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'pmml',
              label: $t('re.resources.designer.processor.grid.entity.pmml'),
              type: 'code-mirror',
              rows: 10,
              lineNumber: true,
              lang: 'xml',
              showIf: (arg) => {
                return 'PMML' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'groovyScript',
              label: $t('re.resources.designer.processor.grid.entity.groovyScript'),
              type: 'code-mirror',
              rows: 20,
              lineNumber: true,
              lang: 'java',
              showIf: (arg) => {
                return 'GROOVY_SCRIPT' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'sqlDatasourceName',
              label: $t('re.resources.designer.processor.grid.entity.sqlDatasourceName'),
              type: 'select',
              rows: 1,
              showIf: (arg) => {
                return 'SQL' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'sql',
              label: $t('re.resources.designer.processor.grid.entity.sql'),
              type: 'select',
              rows: 1,
              showIf: (arg) => {
                return 'SQL' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'sqlParameterValues',
              label: $t('re.resources.designer.processor.grid.entity.sqlParameterValues'),
              type: 'select',
              rows: 1,
              showIf: (arg) => {
                return 'SQL' === arg.form.getFieldValue('type');
              },
            },
            {
              name: 'sqlFieldMapping',
              label: $t('re.resources.designer.processor.grid.entity.sqlFieldMapping'),
              type: 'select',
              rows: 1,
              showIf: (arg) => {
                return 'SQL' === arg.form.getFieldValue('type');
              },
            },
          ],
        },
      }"
      :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') },
            { name: 'optionCode', label: $t('re.resources.designer.processor.grid.entity.optionCode') },
            { name: 'arithmetic', label: $t('re.resources.designer.processor.grid.entity.arithmetic') },
            { name: 'ternaryCondition', label: $t('re.resources.designer.processor.grid.entity.ternaryCondition') },
            { name: 'ternaryTrue', label: $t('re.resources.designer.processor.grid.entity.ternaryTrue') },
            { name: 'ternaryFalse', label: $t('re.resources.designer.processor.grid.entity.ternaryFalse') },
            { name: 'when', label: $t('re.resources.designer.processor.grid.entity.when') },
            { name: 'then', label: $t('re.resources.designer.processor.grid.entity.then') },
            { name: 'isWhenThenShorted', label: $t('re.resources.designer.processor.grid.entity.isWhenThenShorted') },
            { name: 'rule', label: $t('re.resources.designer.processor.grid.entity.rule') },
            { name: 'singleRule', label: $t('re.resources.designer.processor.grid.entity.singleRule') },
            { name: 'numberRange', label: $t('re.resources.designer.processor.grid.entity.numberRange') },
            { name: 'conditionRange', label: $t('re.resources.designer.processor.grid.entity.conditionRange') },
            { name: 'decisionTable2C', label: $t('re.resources.designer.processor.grid.entity.decisionTable2C') },
            { name: 'decisionTable', label: $t('re.resources.designer.processor.grid.entity.decisionTable') },
            { name: 'groovyScript', label: $t('re.resources.designer.processor.grid.entity.groovyScript') },

            { name: 'sqlDatasourceName', label: $t('re.resources.designer.processor.grid.entity.sqlDatasourceName') },
            { name: 'sql', label: $t('re.resources.designer.processor.grid.entity.sql') },
            { name: 'sqlParameterValues', label: $t('re.resources.designer.processor.grid.entity.sqlParameterValues') },
            { name: 'sqlFieldMapping', label: $t('re.resources.designer.processor.grid.entity.sqlFieldMapping') },

            { 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="
        (data, callback) => {
          const form = gridRef.getEditorForm();
          if ('NUMBER_RANGE' === data.type) {
            const grid = form.getFieldComponent('numberRange');
            const localData = grid.getLocalData();
            const ranges = [];
            for (const item of localData) {
              ranges.push({
                uuid: item.uuid,
                minIncluded: item.minIncluded,
                min: item.min,
                max: item.max,
                maxIncluded: item.maxIncluded,
                value: item.value,
              });
            }
            data.numberRange = Tools.object2Json(ranges);
          } else if ('CONDITION_RANGE' === data.type) {
            const grid = form.getFieldComponent('conditionRange');
            const localData = grid.getLocalData();
            const ranges = [];
            for (const item of localData) {
              ranges.push({
                uuid: item.uuid,
                condition: item.condition,
                value: item.value,
              });
            }
            data.conditionRange = Tools.object2Json(ranges);
          }
        }
      "
      @after-editor-open="
        (row) => {
          axios.get(Environment.apiContextPath('/api/re/model/parameter/listParemterHintsByParameterId/' + parameter.id)).then((response) => {
            const names = [];
            if (response.data?.parentParameterNames && response.data?.parentParameterNames.length > 0) {
              for (const item of response.data?.parentParameterNames) {
                names.push({ label: item, type: 'variable', apply: '${' + item + '}' });
              }
            }
            if (response.data?.parameterNames && response.data?.parameterNames.length > 0) {
              for (const item of response.data?.parameterNames) {
                names.push({ label: item, type: 'variable', apply: '${' + item + '}' });
              }
            }
            autoCompletionOptionsRef = names;
          });
          const type = gridRef.getEditorForm().getFieldValue('type');
          if ('IN_OPTION' === type) {
            axios.get(Environment.apiContextPath('/api/re/model/parameter/listParemtersByParameterId/' + parameter.id)).then((response) => {
              const parameters = [];
              if (response.data) {
                for (const parameter of response.data) {
                  if ('IN_OPTION' === parameter.type) {
                    parameters.push({ label: parameter.name, value: parameter.code });
                  }
                }
              }
              optionOptionsRef = parameters;
            });
          } else if ('NUMBER_RANGE' === type) {
            const grid = gridRef.getEditorForm().getFieldComponent('numberRange');
            const rows = Tools.json2Object(row.numberRange);
            grid.setLocalData(rows);
          } else if ('CONDITION_RANGE' === type) {
            const grid = gridRef.getEditorForm().getFieldComponent('conditionRange');
            const rows = Tools.json2Object(row.conditionRange);
            grid.setLocalData(rows);
          }
        }
      "
    ></w-grid>
    <DecisionTreeDialog ref="decisionTreeDialogRef"></DecisionTreeDialog>
    <ExecutionFlowDialog ref="executionFlowDialogRef"></ExecutionFlowDialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { axios, Environment, Formater, Tools, EnumTools, Options } from 'platform-core';
import { PlaceHolder } from '@/utils/PlaceHolder';
import GroovyFunctions from './GroovyFunctions';
import DecisionTreeDialog from './DecisionTreeDialog.vue';
import ExecutionFlowDialog from './ExecutionFlowDialog.vue';

const props = defineProps({
  fetchDataUrl: { type: String, default: '' },
  dataUrl: { type: String, default: '' },
  parameter: { 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 autoCompletionOptionsRef = ref([]);
const optionOptionsRef = ref([]);
const decisionTreeDialogRef = ref();
const executionFlowDialogRef = ref();

const transfromContent = (xml) => {
  const div = document.createElement('div');
  div.textContent = xml;
  const result = div.outerHTML;
  div.parentNode?.removeChild(div);
  return result;
};

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

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

defineExpose({
  refresh,
});

const Enums = await EnumTools.fetch(['io.sc.engine.rule.core.enums.ProcessorType']);
</script>
