<template>
  <div style="height: 100%">
    <w-grid
      ref="gridRef"
      :title="$t('re.resources.designer.parameter.grid.title')"
      :draggable="true"
      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: (arg) => {
              return !readOnly;
            },
          },
          {
            extend: 'add',
            name: 'constant',
            label: $t('re.resources.designer.parameter.grid.toolbar.add.constant'),
            icon: 'bi-tag',
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'CONSTANT');
            },
          },
          'separator',
          {
            extend: 'add',
            name: 'in',
            label: $t('re.resources.designer.parameter.grid.toolbar.add.in'),
            icon: 'bi-terminal',
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'IN');
            },
          },
          {
            extend: 'add',
            name: 'inOption',
            label: $t('re.resources.designer.parameter.grid.toolbar.add.inOption'),
            icon: 'bi-list-check',
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'IN_OPTION');
            },
          },
          {
            extend: 'add',
            name: 'indicator',
            label: $t('re.resources.designer.parameter.grid.toolbar.add.indicator'),
            icon: 'bi-link',
            click: (arg) => {
              selectIndicatorDialogRef.open();
            },
          },
          'separator',
          {
            extend: 'add',
            name: 'intermediate',
            label: $t('re.resources.designer.parameter.grid.toolbar.add.intermediate'),
            icon: 'bi-superscript',
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'INTERMEDIATE');
            },
          },
          {
            extend: 'add',
            name: 'out',
            label: $t('re.resources.designer.parameter.grid.toolbar.add.out'),
            icon: 'bi-shuffle',
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'OUT');
            },
          },
          'separator',
          {
            extend: 'add',
            name: 'ruleResult',
            label: $t('re.resources.designer.parameter.grid.toolbar.add.ruleResult'),
            icon: 'bi-sliders',
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'RULE_RESULT');
            },
          },
          {
            extend: 'add',
            name: 'singleRuleResult',
            label: $t('re.resources.designer.parameter.grid.toolbar.add.singleRuleResult'),
            icon: 'bi-lightning',
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'SINGLE_RULE_RESULT');
            },
          },
          'separator',
          {
            name: 'importPmml',
            label: $t('re.resources.designer.parameter.grid.toolbar.add.importPmml'),
            icon: 'bi-file-earmark-text',
          },
        ],
        'separator',
        {
          extend: 'clone',
          enableIf: (arg) => {
            return !readOnly && arg.selected;
          },
        },
        {
          extend: 'clone',
          name: 'deepClone',
          label: $t('deepClone'),
          icon: 'bi-copy',
          enableIf: (arg) => {
            return !readOnly && arg.selected;
          },
          click: (arg) => {
            DialogManager.confirm($t('re.resources.designer.parameter.grid.toolbar.deepClone.tip'), () => {
              axios.post(Environment.apiContextPath('/api/re/model/parameter/deepClone/' + arg.selected.id)).then(() => {
                gridRef.refresh();
              });
            });
          },
        },
        {
          extend: 'edit',
          enableIf: (arg) => {
            return !readOnly && arg.selected;
          },
        },
        {
          extend: 'remove',
          enableIf: (arg) => {
            return !readOnly && arg.selected;
          },
        },
        'separator',
        {
          name: 'move',
          label: $t('re.resources.designer.parameter.grid.toolbar.move'),
          icon: 'bi-share-fill',
          enableIf: (arg) => {
            return !readOnly && arg.selected;
          },
          click: (arg) => {
            moveParameterDialogRef.open();
          },
        },
        'separator',
        'view',
        'separator',
        'export',
      ]"
      :columns="[
        { width: 60, name: 'order', label: $t('order'), sortable: false, align: 'right' },
        { width: '100%', name: 'name', label: $t('name'), sortable: false },
        { width: 150, name: 'code', label: $t('code'), sortable: false },
        { width: 110, name: 'type', label: $t('type'), sortable: false, format: Formater.enum(Enums.ParameterType) },
        {
          width: 180,
          name: 'valueType',
          label: $t('re.resources.designer.parameter.grid.entity.valueType'),
          sortable: false,
          format: (value, row) => {
            if (row.valueTypeVersion) {
              return ValueTypeMap[value] + ' (V' + row.valueTypeVersion + ')';
            }
            if (row.valueType == 'java.math.BigDecimal') {
              if (row.valueRoundingMode == 'HALF_UP') {
                return ValueTypeMap[value] + '(' + row.valueScale + ')';
              } else {
                return ValueTypeMap[value] + '(' + row.valueScale + ',' + Formater.enum(Enums.RoundingMode)(row.valueRoundingMode) + ')';
              }
            }
            var result = ValueTypeMap[value];
            result = result || row.valueType;
            if (result) {
              result = result.replace('<', '&lt;');
              result = result.replace('>', '&gt;');
            }
            return result;
          },
        },
        {
          width: 80,
          name: 'valueTypeIsList',
          label: $t('re.resources.designer.parameter.grid.entity.valueTypeIsList'),
          sortable: false,
          format: Formater.yesNo(),
        },
        { width: 200, name: 'defaultValue', label: $t('defaultValue'), sortable: false },
      ]"
      :editor="{
        dialog: {
          width: '600px',
        },
        form: {
          colsNum: 1,
          fields: [
            { name: 'type', label: $t('type'), type: 'w-select', options: Options.enum(Enums.ParameterType), 'onUpdate:modelValue': (value) => {} },
            { name: 'model', label: $t('modelId'), type: 'w-text', defaultValue: model.id, hidden: true },
            { name: 'code', label: $t('code'), type: 'w-text' },
            { name: 'name', label: $t('name'), type: 'w-text', required: true },
            { name: 'description', label: $t('description'), type: 'w-text' },
            {
              name: 'libCode',
              label: $t('re.resources.designer.parameter.grid.entity.libCode'),
              type: 'w-select',
              options: libCodeOptionsRef,
              showIf: (arg) => {
                const type = arg.form.getFieldValue('type');
                return type === 'INDICATOR';
              },
              'onUpdate:modelValue': (value) => {
                libVersionOptionsRef = IndicatorManager.getLibVersionMap(value);
              },
            },
            {
              name: 'libVersion',
              label: $t('re.resources.designer.parameter.grid.entity.libVersion'),
              type: 'w-select',
              options: libVersionOptionsRef,
              showIf: (arg) => {
                const type = arg.form.getFieldValue('type');
                return type === 'INDICATOR';
              },
              'onUpdate:modelValue': (value) => {
                const libCode = gridRef.getEditorForm().getFieldValue('libCode');
                indicatorCodeOptionsRef = IndicatorManager.getIndicatorMap(libCode, value);
              },
            },
            {
              name: 'indicatorCode',
              label: $t('re.resources.designer.parameter.grid.entity.indicatorCode'),
              type: 'w-select',
              options: indicatorCodeOptionsRef,
              showIf: (arg) => {
                const type = arg.form.getFieldValue('type');
                return type === 'INDICATOR';
              },
            },
            {
              name: 'valueType',
              label: $t('re.resources.designer.parameter.grid.entity.valueType'),
              type: 'w-select',
              options: ValueTypeList,
              defaultValue: 'java.math.BigDecimal',
              showIf: (arg) => {
                const type = arg.form.getFieldValue('type');
                if (type == 'INDICATOR' || type == 'IN_OPTION' || type == 'RULE_RESULT' || type == 'SINGLE_RULE_RESULT') {
                  return false;
                }
                return true;
              },
              'onUpdate:modelValue': (value) => {
                const valueType = gridRef.getEditorForm().getFieldValue('valueType');
                axios.get(Environment.apiContextPath('/api/re/dictionary/getVersionsByCode?code=' + valueType)).then((response) => {
                  const versions = response.data;
                  const options = [];
                  for (const version of versions) {
                    options.push({ label: version.key, value: version.value });
                  }
                  valueTypeVersionOptionsRef = options;
                });
              },
            },
            {
              name: 'valueTypeVersion',
              label: $t('re.resources.designer.parameter.grid.entity.valueTypeVersion'),
              type: 'w-select',
              clearable: true,
              options: valueTypeVersionOptionsRef,
              showIf: (arg) => {
                const type = arg.form.getFieldValue('type');
                if (type == 'INDICATOR' || type == 'IN_OPTION' || type == 'RULE_RESULT' || type == 'SINGLE_RULE_RESULT') {
                  return false;
                }
                const valueType = arg.form.getFieldValue('valueType');
                if (valueType) {
                  if (
                    valueType == 'java.lang.Boolean' ||
                    valueType == 'java.lang.Long' ||
                    valueType == 'java.lang.Float' ||
                    valueType == 'Float' ||
                    valueType == 'java.math.BigDecimal' ||
                    valueType == 'java.lang.String' ||
                    valueType == 'java.util.Date' ||
                    valueType == 'io.sc.engine.rule.core.classes.ResourceAbstract' ||
                    valueType == 'io.sc.engine.rule.core.classes.RuleResult' ||
                    valueType == 'io.sc.engine.rule.core.classes.SingleRuleResult' ||
                    valueType.startsWith('List') ||
                    valueType.startsWith('Map')
                  ) {
                    return false;
                  } else if (Tools.isUndefinedOrNull(ValueTypeMap[valueType])) {
                    return false;
                  } else {
                    return true;
                  }
                }
                return false;
              },
            },
            {
              name: 'valueScale',
              label: $t('re.resources.designer.parameter.grid.entity.valueScale'),
              type: 'w-number',
              defaultValue: 6,
              showIf: (arg) => {
                const valueType = arg.form.getFieldValue('valueType');
                const type = arg.form.getFieldValue('type');
                if (
                  valueType == 'java.math.BigDecimal' &&
                  type != 'INDICATOR' &&
                  type != 'IN_OPTION' &&
                  type != 'RULE_RESULT' &&
                  type != 'SINGLE_RULE_RESULT'
                ) {
                  return true;
                }
                return false;
              },
            },
            {
              name: 'valueRoundingMode',
              label: $t('re.resources.designer.parameter.grid.entity.valueRoundingMode'),
              type: 'w-select',
              options: Options.enum(Enums.RoundingMode),
              defaultValue: 'HALF_UP',
              showIf: (arg) => {
                const valueType = arg.form.getFieldValue('valueType');
                const type = arg.form.getFieldValue('type');
                if (
                  valueType == 'java.math.BigDecimal' &&
                  type != 'INDICATOR' &&
                  type != 'IN_OPTION' &&
                  type != 'RULE_RESULT' &&
                  type != 'SINGLE_RULE_RESULT'
                ) {
                  return true;
                }
                return false;
              },
            },
            {
              name: 'valueTypeIsList',
              label: $t('re.resources.designer.parameter.grid.entity.valueTypeIsList'),
              type: 'w-checkbox',
              defaultValue: false,
              showIf: (arg) => {
                const type = arg.form.getFieldValue('type');
                if (type == 'IN_OPTION' || type == 'INDICATOR' || type == 'RULE_RESULT' || type == 'SINGLE_RULE_RESULT') {
                  return false;
                }
                return true;
              },
            },
            {
              name: 'defaultValue',
              label: $t('defaultValue'),
              type: 'w-text',
              showIf: (arg) => {
                const type = arg.form.getFieldValue('type');
                const valueTypeIsList = arg.form.getFieldValue('valueTypeIsList');
                if (type == 'INDICATOR' || type == 'RULE_RESULT' || type == 'SINGLE_RULE_RESULT' || valueTypeIsList) {
                  return false;
                }
                return true;
              },
            },

            { name: 'order', label: $t('order'), type: 'w-number' },
          ],
        },
      }"
      :viewer="{
        panel: {
          columnNum: 1,
          fields: [
            { name: 'order', label: $t('order') },
            { name: 'id', label: $t('id') },
            { name: 'model', label: $t('model') },
            { name: 'code', label: $t('code') },
            { name: 'name', label: $t('name') },
            { name: 'description', label: $t('description') },
            { name: 'type', label: $t('type') },
            { name: 'valueType', label: $t('re.resources.designer.parameter.grid.entity.valueType') },
            { name: 'valueTypeVersion', label: $t('re.resources.designer.parameter.grid.entity.valueTypeVersion') },
            { name: 'valueScale', label: $t('re.resources.designer.parameter.grid.entity.valueScale') },
            { name: 'valueRoundingMode', label: $t('re.resources.designer.parameter.grid.entity.valueRoundingMode') },
            { name: 'valueTypeIsList', label: $t('re.resources.designer.parameter.grid.entity.valueTypeIsList') },
            { name: 'defaultValue', label: $t('defaultValue') },
            { name: 'libCode', label: $t('re.resources.designer.parameter.grid.entity.libCode') },
            { name: 'libVersion', label: $t('re.resources.designer.parameter.grid.entity.libVersion') },
            { name: 'indicatorCode', label: $t('re.resources.designer.parameter.grid.entity.indicatorCode') },

            { 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() },
          ],
        },
      }"
      @row-click="
        (args) => {
          emit('rowClick', args);
        }
      "
      @before-request-data="
        () => {
          emit('beforeRequestData');
        }
      "
      @after-editor-open="
        (row) => {
          const type = gridRef.getEditorForm().getFieldValue('type');
          if (type === 'INDICATOR') {
            axios.get(Environment.apiContextPath('/api/re/lib/isc/getLibInformationWrapper')).then((response) => {
              IndicatorManager.setWrapper(response.data);
              libCodeOptionsRef = IndicatorManager.getLibMap();
              libVersionOptionsRef = IndicatorManager.getLibVersionMap(row.libCode);
              indicatorCodeOptionsRef = IndicatorManager.getIndicatorMap(row.libCode, row.libVersion);
            });
          }

          const valueType = gridRef.getEditorForm().getFieldValue('valueType');
          if (valueType) {
            if (
              valueType !== 'java.lang.Boolean' &&
              valueType !== 'java.lang.Long' &&
              valueType !== 'java.lang.Float' &&
              valueType !== 'Float' &&
              valueType !== 'java.math.BigDecimal' &&
              valueType !== 'java.lang.String' &&
              valueType !== 'java.util.Date' &&
              valueType !== 'io.sc.engine.rule.core.classes.ResourceAbstract' &&
              valueType !== 'io.sc.engine.rule.core.classes.RuleResult' &&
              valueType !== 'io.sc.engine.rule.core.classes.SingleRuleResult' &&
              !valueType.startsWith('List') &&
              !valueType.startsWith('Map') &&
              ValueTypeMap[valueType]
            ) {
              axios.get(Environment.apiContextPath('/api/re/dictionary/getVersionsByCode?code=' + valueType)).then((response) => {
                const versions = response.data;
                const options = [];
                for (const version of versions) {
                  options.push({ label: version.key, value: version.value });
                }
                valueTypeVersionOptionsRef = options;
              });
            }
          }
        }
      "
    ></w-grid>
    <SelectIndicatorDialog ref="selectIndicatorDialogRef" :parameter-grid="gridRef" :model-id="model.id"></SelectIndicatorDialog>
    <MoveParameterDialog ref="moveParameterDialogRef" :parameter-grid="gridRef" :resource="resource"></MoveParameterDialog>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { axios, Environment, EnumTools, DialogManager, Formater, Options, Tools } from 'platform-core';
import { IndicatorManager } from '@/views/shared/IndicatorManager';
import SelectIndicatorDialog from '@/views/shared/SelectIndicatorDialog.vue';
import MoveParameterDialog from '@/views/shared/MoveParameterDialog.vue';

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 valueTypeVersionOptionsRef = ref([]);
const libCodeOptionsRef = ref([]);
const libVersionOptionsRef = ref();
const indicatorCodeOptionsRef = ref();
const selectIndicatorDialogRef = ref();
const moveParameterDialogRef = ref();

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

defineExpose({
  refresh,
});

const Enums = await EnumTools.fetch([
  'io.sc.platform.core.enums.RoundingMode',
  'io.sc.engine.rule.core.enums.ParameterType',
  'io.sc.engine.rule.core.enums.DeployStatus',
]);

let ValueTypeMap = {};
const ValueTypeList = [];
const response = await axios.get(Environment.apiContextPath('/api/re/dictionary/getAllDictionaryMap'));
if (response && response.data) {
  ValueTypeMap = {};
  ValueTypeList.splice(0, ValueTypeList.length);
  for (const item of response.data) {
    ValueTypeMap[item.key] = item.value;
    ValueTypeList.push({ value: item.key, label: item.value });
  }
}

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