<template>
  <q-dialog v-model="settingsDialog">
    <q-card class="full-width no-shadow" style="max-width: 800px">
      <q-card-section>
        <div class="text-h6">Событие</div>
      </q-card-section>
      <div>
        <q-card-section class="q-pb-md q-gutter-y-md">
          <q-input
            v-model="dialogData.name"
            :rules="[requiredHendler]"
            :disable="viewMode"
            filled
            label="Наименование"
            error-message="Поле должно быть заполнено"
          />
          <q-select
            v-model="dialogData.eventType"
            :options="eventTypes"
            filled
            option-value="code"
            option-label="value"
            :disable="viewMode"
            :rules="[requiredHendler]"
            emit-value
            map-options
            class="full-width"
            label="Тип процесса"
            error-message="Поле должно быть заполнено"
          />
          <filters
            :value="dialogData.filters"
            :visibleColumns="visibleColumns"
            :viewMode="viewMode"
            class="q-mb-lg"
            @changeFilter="changeFilter"
          />
        </q-card-section>
        <q-card-actions align="right">
          <q-btn
            v-if="!viewMode"
            label="Создать"
            unelevated
            color="primary"
            @click="create"
          />
          <q-btn
            @click="settingsDialog = false"
            label="Закрыть"
            color="white"
            text-color="primary"
            outline
          />
        </q-card-actions>
      </div>
      <q-inner-loading :showing="loading">
        <q-spinner-gears color="primary" size="50px" />
      </q-inner-loading>
    </q-card>
  </q-dialog>
</template>

<script>
import { notifyError } from '@utils/notify';
import Filters from './components/Filters.vue';
import axios from 'axios';
import cloneDeep from 'lodash/cloneDeep';

export default {
  name: 'EventDialog',
  props: ['eventData'],
  components: {
    Filters,
  },
  data() {
    return {
      dialogData: {
        name: '',
        eventType: '',
        filters: [],
      },
      loading: true,
      settingsDialog: false,
      viewMode: false,
      visibleColumns: ['globalOperator', 'guidFilter', 'operator', 'value'],
      eventTypes: [],
    };
  },
  computed: {
    events() {
      return (
        this.$store.getters[
          'registryService/additionalSettings/settingsForServiceCard'
        ].settingsforserviceevent || []
      );
    },
  },
  methods: {
    open(event) {
      this.clearForm();
      this.loading = false;
      this.settingsDialog = true;
      this.eventTypes = this.$store.getters[
        'registryService/additionalSettings/setSettingsDictionary'
      ].DictEventTypeForSettingForService;
      let eventTypesFilt = this.events.map((e) => e.eventType);

      if (event) {
        this.dialogData = event;
        this.viewMode = true;
        this.visibleColumns.splice(4, 1);
        eventTypesFilt = eventTypesFilt.filter((e) => e !== event.eventType);
      } else {
        this.visibleColumns.push('actions');
      }
      this.eventTypes = this.eventTypes.filter(
        (e) => !eventTypesFilt.includes(e.code)
      );
    },
    changeFilter(filters) {
      this.dialogData.filters = filters.map((e, index) => ({
        ...e,
        filterId: (index + 1).toString(),
      }));
    },
    async create() {
      if (
        !this.requiredHendler(this.dialogData.name) ||
        !this.requiredHendler(this.dialogData.eventType)
      ) {
        this.$q.notify({
          color: 'negative',
          icon: 'error',
          message: 'Все поля должны быть заполнены',
        });
        return;
      }
      if (!this.dialogData?.filters.length) {
        this.$q.notify({
          color: 'negative',
          icon: 'error',
          message: 'Поле фильтры обязательно для заполнения',
        });
        return;
      }
      await axios
        .post(`/service/registry/service/settings-for-service-event`, [
          this.dialogData,
        ])
        .then((eventId) => {
          const card = cloneDeep(
            this.$store.getters[
              'registryService/additionalSettings/settingsForServiceCard'
            ]
          );
          const event = card.settingsforserviceevent || [];

          event.push({ ...this.dialogData, id: eventId.data.objectIds[0] });
          card.settingsforserviceevent = event;
          this.$store.dispatch(
            'registryService/additionalSettings/setCardForJson',
            card
          );
          this.$store.dispatch(
            'registryService/additionalSettings/setunsavedChanges',
            'criteria'
          );
          this.settingsDialog = false;
        })
        .catch((e) => {
          notifyError(e.message.toString());
        });
    },

    clearForm() {
      this.dialogData = {
        name: '',
        eventType: '',
        filters: [],
      };
      this.viewMode = false;
    },
    requiredHendler(val) {
      return !!(val && val.length !== 0);
    },
  },
};
</script>
