<template>
  <div class="row q-gutter-x-md range_container">
    <data-block class="col font-12" :form-data="{ label: rangeLabel ? rangeLabel.from : '' }" bolder no-padding>
      <x-date-input
        v-model="range.from"
        v-bind="$attrs"
        type="date"
        :hide-bottom-space="hideBottomSpace"
        :format="format"
        :minimal="minimal"
        :focus="focus"
        :required="required"
        placeholder="от"
      />
    </data-block>
    <data-block class="col font-12" :form-data="{ label: rangeLabel ? rangeLabel.to : '' }" bolder no-padding>
      <x-date-input
        v-model="range.to"
        v-bind="$attrs"
        type="date"
        :hide-bottom-space="hideBottomSpace"
        :format="format"
        :minimal="minimal"
        endOfDay
        :focus="focus"
        :required="required"
        placeholder="до"
      />
    </data-block>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { DateFormat } from '@constants/utils/format-date';
import XDateInput from './x-datetime-input.vue';
import dataBlock from '@components/cards/statements/components/dataBlock.vue';

interface Range {
  to?: Date;
  from?: Date;
}

interface RangeLable {
  to: string;
  from: string;
} 

@Component({
  components: { XDateInput, dataBlock },
})
export default class XDateRange extends Vue {
  @Prop() private from!: Date;
  @Prop() private to!: Date;
  @Prop() private value!: Range;
  @Prop() private default!: Range;
  @Prop() private rangeLabel?: RangeLable;
  @Prop({ default: DateFormat.backend }) private format!: string;
  @Prop({ type: Boolean, default: false }) minimal: boolean;
  @Prop({ type: Boolean, default: false }) required: boolean;
  @Prop({ type: Boolean, default: false }) focus: boolean;
  @Prop({ type: Boolean, default: true }) hideBottomSpace: boolean;

  private range: Range = {
    to: undefined,
    from: undefined,
  };

  private last?: Range;

  protected created() {
    if (this.default) {
      const { to, from } = this.default;

      if (to) {
        this.range.to = to;
      }
      if (from) {
        this.range.from = from;
      }
    }
  }

  @Watch('value', { deep: true }) vvalue(val: Range) {
    if (this.last === val) {
      return;
    }
    this.range = { ...val };
  }

  @Watch('range', { deep: true }) vrange(val: Range) {
    this.$emit(`update:from`, val.from);
    this.$emit(`update:to`, val.to);
    this.$emit('input', (this.last = { ...val }));
  }
}
</script>
<style lang="sass">
  .range_container
    aling-items: flex-start
</style>
