<template>
  <div class="q-gutter-y-md">
    <q-card flat>
      <div class="row q-gutter-x-md" style="margin-bottom: -16px">
        <div class="q-mb-md row q-gutter-x-sm items-center">
          <p class="q-ma-none">
            {{ $t('registries.status') }}
          </p>
          <q-select
            v-model="filter.status"
            filled
            stretch
            flat
            dense
            borderless
            multiple
            style="min-width: 20em"
            :emit-value="false"
            :options="statusOptions"
            @input="handleStatusChange"
          >
            <template #option="scope">
              <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>
        </div>

        <div class="q-mb-md row q-gutter-x-sm items-center">
          <p class="q-ma-none">
            {{ $t('registries.dates') }}
          </p>
          <q-field borderless dense style="min-width: 20em">
            <x-date-range
              :from.sync="filter.from"
              :to.sync="filter.to"
              @input="handleRangeChange"
            />
          </q-field>
        </div>
        <div class="q-mb-md row q-gutter-x-sm items-center">
          <q-btn
            v-if="showSearchButton"
            color="primary"
            :loading="loading"
            label="Поиск"
            @click="startSearch"
          />
          <q-btn
            v-if="showSaveButton"
            color="primary"
            :loading="loading"
            label="Сформировать выгрузку"
            @click="saveData"
          />
        </div>
      </div>
    </q-card>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { Option } from '@components/statements/components/search-bar.vue';
import { oidcClientComputed } from '@state/modules/oidc-client';
import XDateRange from '@components/statements/components/x-date-range.vue';
import { convertDateFormatWithoutLocale } from '@utils/format-date';
import { SearchBarRefs } from '@components/common/base-search-bar';

class AccountsCreateInjection extends Vue.extend({
  computed: {
    ...oidcClientComputed,
  },
}) {}

export interface MoneyOrderFilter {
  status: Option[];
  from: Date | string;
  to: Date | string;
  page?: number;
}

interface StatusOption {
      label: string;
      value: string;
}

const STATUS_OPTIONS =[
  {
    label: 'Загружено извещение УФК',
    value: 'Загружено извещение УФК',
  },
  {
    label: 'Сформировано',
    value: 'Сформировано',
  },
  {
    label: 'Подписано',
    value: 'Подписано',
  },
  {
    label: 'Аннулирован',
    value: 'Аннулирован',
  },
]

@Component({
  components: {
    XDateRange,
  },
})
export default class BaseRegistrySearchBar extends AccountsCreateInjection {
  $refs!: SearchBarRefs;
  filter: MoneyOrderFilter = {
    status: [],
    from: '',
    to: '',
  };

  @Prop({ default: false }) showSearchButton!: boolean;
  @Prop({ default: false }) showSaveButton!: boolean;
  @Prop({}) loading!: boolean;
  @Prop({ default: () => STATUS_OPTIONS}) statusOptions!: StatusOption;
  

  saveData(): void {
    this.$emit('save-data', this.filter.status);
  }

  startSearch(): void {
    const query: string[] = [];

    const { status, from, to } = this.filter;

    if (status.length) {
      query.push(status.map((e) => `state=='${e.value}'`).join(' or '));
    }
    if (from) {
      const fromTs = Math.floor(new Date(from as any).getTime() / 1000);
      query.push(`created=gt=${fromTs}`);
    }
    if (to) {
      const toPlus = new Date(to as any);
      toPlus.setDate(toPlus.getDate() + 1);
      query.push(`created=le=${Math.floor(toPlus.getTime() / 1000)}`);
    }

    const qObj = {
      query: query.join(' and '),
    };
    this.$emit('query', qObj);
  }

  handleRangeChange(): void {
    const result = ['', ''];

    if (this.filter.from !== null) {
      result[0] = convertDateFormatWithoutLocale(this.filter.from);
    }

    if (this.filter.to !== null) {
      result[1] = convertDateFormatWithoutLocale(this.filter.to);
    }
    this.startSearch();
  }

  handleStatusChange(): void {
    this.startSearch();
  }
}
</script>
