<template>
  <div>
    <q-select
      filled
      v-if="isGoalAttribute"
      v-model="model.value"
      :options="goalsList"
      label="Код цели"
      multiple
      use-chips
    >
      <template #before>
        <slot />
      </template>
    </q-select>
    <div v-else class="row q-gutter-sm">
      <div class="col">
        <q-input
          v-model="model.attribute"
          filled
          label="Путь к атрибуту в заявлении"
        >
          <template #before>
            <slot />
          </template>
        </q-input>
      </div>

      <div class="col">
        <q-select
          v-model="model.equality"
          filled
          label="Оператор сравнения"
          :options="equalityType"
        />
      </div>

      <div class="col">
        <div class="col">
          <q-input
            v-if="typeValue === 'number'"
            v-model.number="model.value"
            filled
            type="number"
            label="С каким значением сравнивать"
            @blur="() => $forceUpdate()"
          />
          <q-checkbox
            v-else-if="typeValue === 'boolean'"
            v-model="model.value"
            label="С каким значением сравнивать"
            @blur="() => $forceUpdate()"
          />
          <q-input
            v-else
            v-model="model.value"
            filled
            label="С каким значением сравнивать"
            @blur="() => $forceUpdate()"
          />
        </div>
      </div>
      <div class="col">
        <q-select
          v-model="typeValue"
          filled
          label="Тип"
          emit-value
          map-options
          :options="typeOptions"
          @input="model.value = void 0"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { QSelectOption } from '@/models/models-ui';

const STATEMENT_GOAL_NAME = 'statement.goal';
const GOAL_EQUALITY = 'in';

@Component({})
export default class ConditionBlock extends Vue {
  @Prop() model!: conditionModel;

  @Prop({ default: [] }) goalsList!: QSelectOption;

  @Prop() typeOptions: QSelectOption;

  @Prop() equalityType: Array<string>;

  private typeValue = 'string';

  private get isGoalAttribute(): boolean {
    return this.model?.attribute === STATEMENT_GOAL_NAME;
  }

  private init(): void {
    if (!this.model) return;
    this.typeValue = typeof this.model.value;
    if (this.isGoalAttribute && this.typeValue === 'number') {
      this.model.equality = GOAL_EQUALITY;
      this.model.value = [Number(this.model.value)];
    }
  }

  mounted() {
    this.init();
  }
}

export interface conditionModel {
  attribute?: string;
  equality?: string;
  value?: string | number | boolean | Array<number>;
  typeValue?: string;
}
</script>
