<template>
  <w-dialog
    ref="dialogRef"
    :title="$t('re.resources.designer.parameter.grid.title')"
    :can-maximize="false"
    :maximized="false"
    :buttons="[
      {
        label: $t('confirm'),
        noCaps: true,
        click: click,
      },
    ]"
  >
    <div class="pt-2">
      <q-select v-model="modelValueRef" :label="$t('parameter')" outlined dense emit-value map-options :options="modelValueOptionsRef"></q-select>
    </div>
  </w-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { axios, Environment, Tools } from 'platform-core';

const props = defineProps({
  targetType: { type: String, default: undefined },
  target: { type: Object, default: undefined },
  processor: { type: Object, default: undefined },
});

const emit = defineEmits<{
  (e: 'afterMatched', objectProperties: any): void;
}>();

const dialogRef = ref();
const modelValueRef = ref('');
const modelValueOptionsRef = ref([]);
let currentObjectProperties = {};

const click = () => {
  let url = '';
  if (props.targetType === 'parameter') {
    url = Environment.apiContextPath('/api/re/model/parameter/processor/autoMatch');
  } else if (props.targetType === 'indicator') {
    url = Environment.apiContextPath('/api/re/indicator/processor/autoMatch');
  }

  axios
    .post(url, {
      id: modelValueRef.value,
      objectProperties: currentObjectProperties,
    })
    .then((response) => {
      emit('afterMatched', response.data);
      close();
    });
};

const open = (objectProperties) => {
  currentObjectProperties = objectProperties;
  modelValueRef.value = undefined;
  dialogRef.value.show();

  let url = '';
  if (props.targetType === 'parameter') {
    url = Environment.apiContextPath('/api/re/model/parameter/findParametersByParameterId?parameterId=' + props.target.id);
  } else if (props.targetType === 'indicator') {
    url = Environment.apiContextPath('/api/re/indicator/findIndicatorsByIndicatorId?indicatorId=' + props.target.id);
  }
  axios.get(url).then((response) => {
    const options = [];
    response.data.forEach((item) => {
      const valueType = item.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')
      ) {
        options.push({ value: item.id, label: item.name });
      }
    });
    modelValueOptionsRef.value = options;
  });
};

const close = () => {
  dialogRef.value.hide();
};

defineExpose({
  open,
  close,
});
</script>
