<template>
  <div class="q-my-md" v-show="!isHidden">
    <div
      class="row flex no-wrap items-center"
      v-for="field in fieldNode.rawAttrs.props.fields"
      :key="field.name"
    >
      <widget-wrapper v-bind="$props">
        <q-checkbox
          ref="checkbox"
          :value="state[field.name]"
          :color="hasError ? 'negative' : 'primary'"
          :disable="fieldNode.readonly"
          :keep-color="hasError"
          style="margin-left: -10px"
          slot-scope="{ inputEvents }"
          @input="(e) => onInput(e, field.name)"
          class="q-mx-md"
        >
        </q-checkbox>
      </widget-wrapper>
      <span class="text-grey-9">{{ field.label || '' }}</span>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop } from 'vue-property-decorator';
import { mixins } from 'vue-class-component';
import {
  ValidatedField,
  FormWidget,
  WidgetWrapper,
} from '@devsun/form-generator/dist';
import { QCheckbox, QTooltip } from 'quasar';

@Component({
  components: {
    QCheckbox,
    QTooltip,
    WidgetWrapper,
  },
})
export default class CheckboxSet extends mixins(FormWidget, ValidatedField) {
  @Prop({ default: false }) private rightLabel: boolean;
  @Prop({}) hideNulls!: boolean;

  state = {};

  mounted() {
    this.setDefault();
  }

  setDefault() {
    if (this.value.__id) return;

    const defaultVal = this.fieldNode?.rawAttrs?.props?.setDefault;
    if (defaultVal === undefined) return;

    this.$refs.checkbox.forEach((c) => {
      c.$emit('input', defaultVal);
    });
  }

  private get currentValue() {
    return this.value.__id;
  }

  get isHidden(): boolean {
    return this.hideNulls && this.currentValue === null;
  }

  onInput(val, field) {
    this.state[field] = val;
    const set = Object.assign({}, this.state) as any;
    if (Object.values(set).every((v) => !v)) {
      this.inputEvents.input('');
    } else {
      this.inputEvents.input(set);
    }
  }
}
</script>
