<template>
  <widget-wrapper
    v-bind="$props"
    v-slot="{ inputEvents }"
    ref="widget"
    class="date-input"
  >
    <arm-datepicker
      ref="armDatepicker"
      :type="type"
      v-bind="$props"
      :value="valueId === checkboxLabel ? '' : valueId"
      :noLabels="noLabels"
      :label="fieldNode.label"
      :color="color"
      :validationError="hasErrorExt"
      :validationMessage="errorMessage"
      :required="fieldNode.mandatory"
      :readonly="isReadonly"
      @input="inputDatepicker"
    />
    <q-checkbox v-model.sync="checkboxValue" :label="checkboxLabel" />
  </widget-wrapper>
</template>

<script lang="ts">
import { Component, Prop } from 'vue-property-decorator';
import { mixins } from 'vue-class-component';
import {
  ValidatedField,
  FormWidget,
  WidgetWrapper,
  FormGeneratorDateType,
} from '@devsun/form-generator/dist';
import ArmDatepicker from '../../../datepicker/arm-datepicker.vue';
import ArmDatepickerClass from '../../../datepicker/arm-datepicker';
import { convertDateFormat } from '@utils/format-date';
import { FieldRawProps } from '@devsun/eva-models/dist/models/Field';

@Component({
  components: {
    ArmDatepicker,
    WidgetWrapper,
  },
})
export default class DateInputEx extends mixins(FormWidget, ValidatedField) {
  @Prop({ default: FormGeneratorDateType.none })
  type!: FormGeneratorDateType;
  @Prop() checkboxLabel!: string;
  @Prop({ default: false }) setDefault: FieldRawProps['setDefault'];

  $refs!: {
    widget: WidgetWrapper;
  };

  mounted(): void {
    this.setDefaultValue();
  }

  get hasErrorExt() {
    if (this.valueId === this.checkboxLabel) {
      return false;
    } else {
      return this.hasError;
    }
  }

  get valueId(): string {
    return this.value && (this.value.__id as string);
  }

  get isReadonly(): boolean {
    if (this.fieldNode.simlink) {
      return true;
    }
    return !!this.fieldNode.readonly;
  }

  get fieldClasses() {
    return {
      editable: !this.fieldNode.readonly,
      'label-uppercase': false,
      dense: this.isDense,
    };
  }

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

    if (this.setDefault === 'today') {
      const armDatepicker = this.$refs.armDatepicker as ArmDatepickerClass;
      const today = convertDateFormat(new Date(), '', armDatepicker.pattern);
      armDatepicker.onManualInput(today, void 0);
    }
  }

  inputDatepicker(e) {
    if (e !== '') {
      this.$refs.widget.inputEvents.input(e);
    }
  }

  get checkboxValue(): boolean {
    return this.valueId === this.checkboxLabel;
  }

  set checkboxValue(e) {
    if (e === true) {
      this.$refs.widget.inputEvents.input(this.checkboxLabel);
    } else {
      this.$refs.widget.inputEvents.input('');
    }
  }
}
</script>

<style scoped>
.date-input {
  margin-top: 12px;
  padding-bottom: 20px;
}
</style>
