<template>
  <div style="width: 100%; height: 100%">
    <w-grid
      ref="gridRef"
      :title="$t('re.testCaseParameter.grid.title')"
      dense-body
      hide-bottom
      :config-button="true"
      selection="multiple"
      :checkbox-selection="false"
      :tree="true"
      :tree-icon="
        (row) => {
          if (row.category === 'F') {
            return { name: 'folder', color: 'amber' };
          } else {
            return { name: 'bi-p-circle' };
          }
        }
      "
      db-click-operation="edit"
      :tree-default-expand-all="true"
      :fetch-data-url="Environment.apiContextPath('/api/re/testCaseParameter/findByTestCase?testCaseId=' + Tools.initialize(testCase?.id, ''))"
      :data-url="Environment.apiContextPath('/api/re/testCaseParameter')"
      :pageable="false"
      :toolbar-configure="{ noIcon: false }"
      :toolbar-actions="[
        'refresh',
        'separator',
        'expand',
        'separator',
        {
          extend: 'edit',
          enableIf: (args: any) => {
            return args.selected && args.selected.category !== 'M';
          },
        },
        'separator',
        {
          name: 'execute',
          label: $t('execute'),
          icon: 'bi-caret-right',
          click: (args: any) => {
            axios.post(Environment.apiContextPath('/api/re/testCase/execute/' + Tools.initialize(testCase?.id, '')), {}, { loading: true }).then(() => {
              gridRef?.refresh();
            });
          },
        },
        'separator',
        {
          name: 'simulate',
          label: $t('simulate'),
          icon: 'monitor',
          click: (args: any) => {
            simulatorDialogRef.open();
          },
        },
        'separator',
        'view',
        'separator',
        'export',
      ]"
      :columns="[
        { width: '100%', name: 'name', label: $t('name'), sortable: false },
        {
          width: 100,
          name: 'parameterType',
          label: $t('type'),
          sortable: false,
          format: (value: any, row: any) => {
            if (row.parameterType) {
              return EngineEnums.ParameterType.formater(row.parameterType);
            }
            if (row.indicatorType) {
              return EngineEnums.IndicatorType.formater(row.indicatorType);
            }
          },
        },
        ...valueTypeManager.getColumns([], false),
        {
          width: 100,
          name: 'inputValue',
          label: $t('re.testCaseParameter.grid.entity.inputValue'),
          sortable: false,
          format: (value: any, row: any) => {
            return Tools.escapeHtml(value);
          },
          title: (args: any) => {
            return args.value;
          },
        },
        {
          width: 100,
          name: 'inputValueValidateMessage',
          label: $t('re.testCaseParameter.grid.entity.inputValueValidateMessage'),
          sortable: false,
          format: (value: any, row: any) => {
            if (value) {
              return '<span class=\'text-red-500\'>' + value + '</span>';
            }
            return value;
          },
          title: (args: any) => {
            return args.value;
          },
        },
        {
          width: 100,
          name: 'expectValue',
          label: $t('re.testCaseParameter.grid.entity.expectValue'),
          sortable: false,
          format: (value: any, row: any) => {
            return Tools.escapeHtml(value);
          },
        },
        {
          width: 100,
          name: 'resultValue',
          label: $t('re.testCaseParameter.grid.entity.resultValue'),
          sortable: false,
          format: (value: any, row: any) => {
            return Tools.escapeHtml(value);
          },
          title: (args: any) => {
            return args.value;
          },
        },
        {
          width: 70,
          name: 'skipCheck',
          label: $t('re.testCaseParameter.grid.entity.skipCheck'),
          sortable: false,
          format: Formater.checkTag(),
        },
        {
          width: 60,
          name: 'testResult',
          label: $t('re.testCaseParameter.grid.entity.testResult'),
          sortable: false,
          align: 'center',
          format: EngineEnums.TestResult.formater,
        },
      ]"
      :editor="{
        dialog: {
          width: '600px',
        },
        form: {
          colsNum: 1,
          fields: [
            { name: 'testCase', label: $t('testCase'), type: 'w-text', defaultValue: Tools.initialize(testCase?.id, ''), showIf: false },
            { name: 'id', label: $t('id'), type: 'w-text', showIf: false },
            { name: 'source', label: $t('source'), type: 'w-text', showIf: false },
            { name: 'parameterType', label: $t('parameterType'), type: 'w-text', showIf: false },
            { name: 'scoreCardVarType', label: $t('scoreCardVarType'), type: 'w-text', showIf: false },
            { name: 'indicatorType', label: $t('indicatorType'), type: 'w-text', showIf: false },
            {
              name: 'inputValue',
              label: $t('re.testCaseParameter.grid.entity.inputValue'),
              type: 'w-code-mirror',
              toolbar: false,
              rows: 4,
              showIf: (arg) => {
                const parameterType = arg.form.getFieldValue('parameterType');
                const scoreCardVarType = arg.form.getFieldValue('scoreCardVarType');
                const indicatorType = arg.form.getFieldValue('indicatorType');
                if (
                  (!Tools.isUndefinedOrNull(parameterType) && (parameterType === 'IN' || parameterType === 'IN_OPTION' || parameterType === 'INDICATOR')) ||
                  (!Tools.isUndefinedOrNull(scoreCardVarType) && scoreCardVarType !== 'RESULT') ||
                  (!Tools.isUndefinedOrNull(indicatorType) && indicatorType === 'INTERFACE')
                ) {
                  return true;
                }
                return false;
              },
            },
            {
              name: 'expectValue',
              label: $t('re.testCaseParameter.grid.entity.expectValue'),
              type: 'w-code-mirror',
              toolbar: false,
              rows: 4,
              showIf: (arg) => {
                const parameterType = arg.form.getFieldValue('parameterType');
                const scoreCardVarType = arg.form.getFieldValue('scoreCardVarType');
                const indicatorType = arg.form.getFieldValue('indicatorType');
                if (
                  (!Tools.isUndefinedOrNull(parameterType) &&
                    (parameterType === 'INTERMEDIATE' ||
                      parameterType === 'OUT' ||
                      parameterType === 'RULE_RESULT' ||
                      parameterType === 'SINGLE_RULE_RESULT')) ||
                  !Tools.isUndefinedOrNull(scoreCardVarType) ||
                  (!Tools.isUndefinedOrNull(indicatorType) && indicatorType === 'INDICATOR')
                ) {
                  return true;
                }
                return false;
              },
            },
            {
              name: 'resultValue',
              label: $t('re.testCaseParameter.grid.entity.resultValue'),
              type: 'w-code-mirror',
              toolbar: false,
              rows: 4,
              lang: 'json',
              editable: true,
            },
            { name: 'skipCheck', label: $t('re.testCaseParameter.grid.entity.skipCheck'), type: 'w-checkbox' },
          ],
        },
      }"
      :viewer="{
        panel: {
          columnNum: 1,
          fields: [
            { name: 'testCaseId', label: $t('re.testCaseParameter.grid.entity.testCaseId') },
            { name: 'id', label: $t('id') },
            { name: 'inputValue', label: $t('re.testCaseParameter.grid.entity.inputValue') },
            { name: 'expectValue', label: $t('re.testCaseParameter.grid.entity.expectValue') },
            { name: 'resultValue', label: $t('re.testCaseParameter.grid.entity.resultValue') },
            { name: 'skipCheck', label: $t('re.testCaseParameter.grid.entity.skipCheck') },
          ],
        },
      }"
      @after-editor-open="
        (args: any) => {
          const form = args.grid.getEditorForm();
          if (args.data.inputValueValidateMessage) {
            form.setValidationErrors([{ fieldName: 'inputValue', errorMessage: args.data.inputValueValidateMessage }]);
          } else {
            form.resetValidation();
          }
        }
      "
    ></w-grid>
    <SimulatorDialog ref="simulatorDialogRef"></SimulatorDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, useAttrs, computed } from 'vue';
import { axios, Environment, Formater, Tools } from 'platform-core';
import { ValueTypeManager } from '@/views/shared/ValueTypeManager';
import { EngineEnums } from '@/views/shared/enums/EngineEnums';
import SimulatorDialog from './SimulatorDialog.vue';

const attrs = useAttrs();
const props = defineProps({
  testCase: { type: Object, default: undefined },
});

const gridRef = ref();
const simulatorDialogRef = ref();
const valueTypeManager = new ValueTypeManager();

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

defineExpose({
  refresh,
});

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