<template>
  <div style="height: 100%">
    <w-grid
      ref="gridRef"
      :title="$t('re.lib.tab.indicator.title')"
      :draggable="true"
      dense
      hide-bottom
      db-click-operation="edit"
      :config-button="true"
      selection="multiple"
      :checkbox-selection="true"
      :tree="false"
      :fetch-data-url="Environment.apiContextPath('api/re/indicator?lib=' + lib.id)"
      :data-url="Environment.apiContextPath('api/re/indicator')"
      :pageable="false"
      :toolbar-configure="{ noIcon: false }"
      :toolbar-actions="[
        'query',
        'refresh',
        'separator',
        [
          {
            name: 'addGroup',
            label: $t('re.lib.grid.toolbar.addGroup'),
            icon: 'add',
            enableIf: (arg) => {
              return !readOnly;
            },
            click: undefined,
          },
          {
            extend: 'add',
            name: 'addInterface',
            label: $t('re.indicator.grid.toolbar.addInterface'),
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'INTERFACE');
            },
          },
          {
            extend: 'add',
            name: 'addIndicator',
            label: $t('re.indicator.grid.toolbar.addIndicator'),
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'INDICATOR');
            },
          },
        ],
        [
          {
            name: 'cloneGroup',
            label: $t('re.lib.grid.toolbar.cloneGroup'),
            icon: 'content_copy',
            click: undefined,
            enableIf: (arg) => {
              return !readOnly && arg.selected;
            },
          },
          'clone',
          {
            extend: 'deepClone',
            name: 'deepClone',
            label: $t('re.lib.grid.toolbar.deepClone'),
            icon: 'bi-copy',
            enableIf: (arg) => {
              return !readOnly && arg.selected;
            },
            click: (arg) => {
              DialogManager.confirm($t('re.lib.grid.toolbar.deepClone.tip'), () => {
                axios.post(Environment.apiContextPath('/api/re/lib/deepClone/' + arg.selected.id)).then(() => {
                  libTreeGridRef.refresh();
                });
              });
            },
          },
        ],
        'separator',
        {
          extend: 'edit',
          enableIf: (arg) => {
            return !readOnly && arg.selected;
          },
        },
        {
          extend: 'remove',
          enableIf: (arg) => {
            return !readOnly && arg.selected;
          },
        },
        'separator',
        'view',
        'separator',
        'export',
      ]"
      :query-form-cols-num="6"
      :query-form-fields="[
        { colSpan: 2, name: 'code', label: $t('code'), type: 'text', clearable: true },
        { colSpan: 3, name: 'name', label: $t('name'), type: 'text', clearable: true },
      ]"
      :columns="[
        { width: 60, name: 'order', label: $t('order'), align: 'right' },
        { width: 250, name: 'name', label: $t('name') },
        { width: 100, name: 'type', label: $t('type'), format: Formater.enum(Enums.IndicatorType) },
        {
          width: 200,
          name: 'valueType',
          label: $t('valueType'),
          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: 90, name: 'valueTypeIsList', label: $t('re.resources.designer.parameter.grid.entity.valueTypeIsList'), format: Formater.checkTag() },
        { width: 100, name: 'defaultValue', label: $t('defaultValue') },
      ]"
      :editor="{
        dialog: {
          width: '600px',
        },
        form: {
          colsNum: 1,
          fields: [
            { name: 'lib', label: $t('lib'), type: 'text', defaultValue: lib.id, hidden: true },
            { name: 'name', label: $t('name'), type: 'text' },
            { name: 'type', label: $t('type'), type: 'select', options: Options.enum(Enums.IndicatorType) },
            {
              name: 'valueType',
              label: $t('re.resources.designer.parameter.grid.entity.valueType'),
              type: 'select',
              options: ValueTypeList,
              'onUpdate:modelValue': (value) => {
                axios.get(Environment.apiContextPath('/api/re/dictionary/getVersionsByCode?code=' + value)).then((response) => {
                  const data = response.data;
                  const options = [];
                  for (const item of data) {
                    options.push({ label: item.key, value: item.value });
                  }
                  valueTypeVersionRef = options;
                });
              },
            },
            {
              name: 'valueTypeVersion',
              label: $t('re.resources.designer.parameter.grid.entity.valueTypeVersion'),
              type: 'select',
              options: valueTypeVersionRef,
              showIf: (arg) => {
                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: 'number',
              defaultValue: 6,
              showIf: (arg) => {
                const valueType = arg.form.getFieldValue('valueType');
                const type = arg.form.getFieldValue('type');
                if (valueType == 'java.math.BigDecimal' && type === 'INDICATOR') {
                  return true;
                }
                return false;
              },
            },
            {
              name: 'valueRoundingMode',
              label: $t('re.resources.designer.parameter.grid.entity.valueRoundingMode'),
              type: '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') {
                  return true;
                }
                return false;
              },
            },
            {
              name: 'valueTypeIsList',
              label: $t('re.resources.designer.parameter.grid.entity.valueTypeIsList'),
              type: 'checkbox',
              defaultValue: false,
            },
            {
              name: 'defaultValue',
              label: $t('defaultValue'),
              type: 'text',
            },

            { name: 'order', label: $t('order'), type: 'number' },
          ],
        },
      }"
      :viewer="{
        panel: {
          columnNum: 1,
          fields: [
            { name: 'order', label: $t('order') },
            { name: 'id', label: $t('id') },
            { name: 'lib', label: $t('lib') },
            { name: 'type', label: $t('type') },
            { name: 'code', label: $t('code') },
            { name: 'name', label: $t('name') },
            { name: 'description', label: $t('description') },
            { 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: '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() },
          ],
        },
      }"
      v-bind="attrs"
    ></w-grid>
    <ImportDialog ref="importDialogRef"></ImportDialog>
  </div>
</template>
<script setup lang="ts">
import { ref, useAttrs, onMounted } from 'vue';
import { axios, Environment, EnumTools, Formater, Options, DialogManager, Tools } from 'platform-core';
import { IndicatorManager } from '@/views/shared/IndicatorManager';
import ImportDialog from './ImportDialog.vue';

const attrs = useAttrs();

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

const gridRef = ref();
const valueTypeVersionRef = ref();

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

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

defineExpose({
  refresh,
});

const Enums = await EnumTools.fetch([
  'io.sc.engine.rule.core.enums.IndicatorType',
  'io.sc.engine.rule.core.enums.DeployStatus',
  'io.sc.platform.core.enums.RoundingMode',
]);
let ValueTypeMap = {};
let ValueTypeList = [];
const response = await axios.get(Environment.apiContextPath('/api/re/dictionary/getAllDictionaryMap'));
if (response && response.data) {
  ValueTypeMap = {};
  ValueTypeList = [];
  for (const item of response.data) {
    ValueTypeMap[item.key] = item.value;
    ValueTypeList.push({ value: item.key, label: item.value });
  }
}
</script>
