import useScopedStyleMixin from '../../useScopedStyleMixin.js';
import DatetimeConditionStyles from './DatetimeConditionStyles.js';

const DatetimeCondition = {
  props: {
    storeFieldId: String,
    dataSource: Object,
    fieldsSource: Object,
    dataValue: String,
    required: String,
    size: String,
    width: String,
  },
  data() {
    return {
      componentClass: 'datetime-condition',
    }
  },
  components: { 'Dropdown': primevue.dropdown },
  mixins: [useScopedStyleMixin, DatetimeConditionStyles],
  inheritAttrs: false,
  mounted() {
    let dateParams = ['value', 'oper', 'interval', 'period', 'fixed'];
    this.$watch("dataSource." + this.storeFieldId, (newVar, oldVar) => {
      if (typeof newVar !== 'object' || newVar === null) {
          this.dataSource[this.storeFieldId] = {}; // Преобразуем в пустой объект
      }
      //Заполняем все поля пустым или по-умолчанию
      dateParams.forEach((param) => {
        if ((newVar === undefined) || (newVar[param] === undefined) || !newVar[param]) {
          this.dataSource[this.storeFieldId][param] = this.fieldsSource[this.storeFieldId]?.default?.[param] ?? '';
        }
      });
    },
    { immediate: true });
  },
  computed: {
    fieldData: {
      get() {
        return this.dataSource[this.storeFieldId] || {};
      },
      set(newValue) {
        this.$set(this.dataSource, this.storeFieldId, newValue);
      }
    },
    isFixed() {
      return this.fieldData['value'] === 'fixed'
    },
    isNow() {
      return this.fieldData['value'] === 'now'
    }
  },
  template: /*html*/`
    <div :class="componentClass + hash">
      <div :class="componentClass + '__row' + hash">
        <Dropdown
          :class="componentClass + '__condition-selector' + hash"
          v-model="fieldData['value']"
          optionLabel="name"
          optionValue="id"
          :options="[
            { id: 'last', name: 'Последний запуск интеграции' },
            { id: 'now', name: 'Текущая дата/время' },
            { id: 'fixed', name: 'Фиксированная дата/время' }
          ]"
        />
      </div>
      <div 
        v-if="isFixed"
        :class="componentClass + '__row' + hash"
      >
        <input 
          type="datetime-local" 
          v-model="fieldData['fixed']" 
          :fieldsize="size" 
          class="form-control" 
        />
      </div>
      <div 
        v-if="isNow || isFixed"
        :class="componentClass + '__row' + hash"
      >
        <Dropdown 
          :class="componentClass + '__increment-selector' + hash"
          v-model="dataSource[storeFieldId]['oper']"
          optionLabel="name"
          optionValue="id"
          :options="[
            { id: '-', name: '-' },
            { id: '+', name: '+' }
          ]"
        />
        <input 
          type="number" 
          v-model="dataSource[storeFieldId]['interval']" 
          :fieldsize="size"
          class="form-control"
          @input="onIntervalInput"
        />
        <Dropdown 
          v-model="dataSource[storeFieldId]['period']"
          :class="componentClass + '__timetype-selector' + hash"
          optionLabel="name"
          optionValue="id"
          :options="[
            { id: '', name: '---' },
            { id: 'days', name: 'дней' },
            { id: ' months', name: 'месяцев' },
            { id: 'years', name: 'лет' },
            { id: 'hours', name: 'часов' },
            { id: 'minutes', name: 'минут' }
          ]"
        />
      </div>
    </div>
  `,  
  methods: {
    onIntervalInput(event) {
      let value = event.target.value;
      if (value < 0) {
        event.target.value = 0;
        this.dataSource[this.storeFieldId]['interval'] = 0;
      }
    }
  }
};

export default DatetimeCondition;