<template>
  <q-form @submit="submit">
    <div class="row q-gutter-y-md">
      <q-select
        v-model="regions"
        :label="$t('notifications.region')"
        :multiple="true"
        label-value="fullname"
        :rules="[rules.required]"
        class="col-12"
        :map-options="true"
        filled
        :options="regionOptions"
        :emit-value="true"
      >
        <template #option="scope">
          <template v-if="scope.index === 0">
            <q-item>
              <q-item-section side>
                <q-checkbox
                  :value="areAllRegionsSelected"
                  :indeterminate-value="null"
                  @input="selectAll"
                />
              </q-item-section>
              <q-item-section>
                <q-item-label v-text="$t('base.all')" />
              </q-item-section>
            </q-item>
            <q-separator inset />
          </template>
          <q-item v-bind="scope.itemProps" v-on="scope.itemEvents">
            <q-item-section side>
              <q-checkbox
                :value="scope.selected"
                @input="scope.itemEvents.click"
              />
            </q-item-section>
            <q-item-section>
              <q-item-label v-html="scope.opt.label" />
            </q-item-section>
          </q-item>
        </template>
      </q-select>
      <q-btn color="primary" :label="$t('base.send')" type="submit" />
    </div>
  </q-form>
</template>

<script lang="ts">
import { Component, Prop } from 'vue-property-decorator';
import Vue from 'vue';
import InputData from '@/types/wf/InputData';

@Component({})
export default class SetRegionVisibility extends Vue {
  private rules = {
    required: (val: any) => (!!val && val.length) || 'Обязательное поле',
  };

  @Prop() readonly inputData: InputData;

  regions: any[] = [];

  get areAllRegionsSelected(): boolean {
    return this.regionOptions.length === this.regions.length;
  }

  selectAll(): void {
    this.areAllRegionsSelected
      ? (this.regions = [])
      : (this.regions = this.regionOptions.map((option: any) => option.value));
  }

  get regionOptions(): any[] {
    return (
      // @ts-ignore
      this.inputData?.regions?.map((region: any) => {
        return {
          label: region.fullname,
          value: region.id,
        };
      }) || []
    );
  }

  private submit(e: any): void {
    this.$emit('submit', e, { regionIds: this.regions });
  }
}
</script>

<style scoped></style>
