<template>
  <div v-if="common.active === 'criteria'">
    <q-card class="no-shadow q-gutter-y-md q-mx-md no-border-radius">
      <div
        class="q-gutter-y-md bg-white q-px-lg q-pb-md q-pt-sm q-mt-md q-mx-md rounded-borders"
      >
        <div class="flex justify-end q-px-md q-my-md row" style="width: 100%">
          <div class="row flex justify-between" style="width: 100%">
            <div class="text-h6">Критерии</div>
            <q-btn
              v-if="
                card.state === 'IN_PROCESS' &&
                $AC.haveScope(USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN)
              "
              color="primary"
              text-color="white"
              icon="add_box"
              label="Новый критерий"
              class="q-mr-md"
              @click="addCriteria"
            >
            </q-btn>
          </div>
        </div>
        <q-table
          :data="criteria"
          :columns="columns"
          class="no-shadow text-grey-9"
          row-key="id"
          title-class="text-subtitle1"
          :rows-per-page-options="[10, 20, 50]"
          wrap-cells
        >
          <template #body-cell-file="props">
            <q-td :props="props">
              <q-btn
                v-if="
                  $AC.haveScope(USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN)
                "
                text-color="negative"
                icon="delete"
                flat
                @click="toggleDeleteConfim(props.row)"
              >
                <q-tooltip :delay="500">Удалить</q-tooltip>
              </q-btn>
            </q-td>
          </template>
        </q-table>
      </div>

      <div
        class="q-gutter-y-md bg-white q-px-lg q-pb-md q-pt-sm q-mt-md q-mx-md rounded-borders"
      >
        <div class="flex justify-end q-px-md q-my-md row" style="width: 100%">
          <div class="row flex justify-between" style="width: 100%">
            <div class="text-h6">События</div>
            <q-btn
              v-if="
                card.state === 'IN_PROCESS' &&
                !$AC.haveScope([USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN])
              "
              color="primary"
              text-color="white"
              icon="add_box"
              label="Создать событие"
              class="q-mr-md"
              :disable="!criteria.length"
              @click="addEvent"
            >
            </q-btn>
          </div>
        </div>
        <q-table
          :data="events"
          :columns="columnsEvent"
          class="no-shadow text-grey-9"
          row-key="id"
          title-class="text-subtitle1"
          :rows-per-page-options="[10, 20, 50]"
          wrap-cells
        >
          <template #body-cell-file="props">
            <q-td :props="props">
              <div class="row no-wrap text-no-wrap float-right">
                <q-btn
                  text-color="primary"
                  icon="search"
                  flat
                  @click="openEvent(props.row)"
                >
                  <q-tooltip :delay="500">Открыть событие</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="
                    $AC.haveScope(USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN)
                  "
                  text-color="negative"
                  icon="delete"
                  flat
                  @click="toggleDeleteConfimEvent(props.row)"
                >
                  <q-tooltip :delay="500">Удалить</q-tooltip>
                </q-btn>
              </div>
            </q-td>
          </template>
        </q-table>
      </div>

      <q-dialog class="full-width" v-model="deleteConfim">
        <q-card class="no-shadow full-width">
          <q-card-section>
            <div class="text-h6">Вы уверены, что хотите удалить критерий?</div>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              @click="deleteCriteria"
              color="primary"
              :label="$t('base.delete')"
            />
            <q-btn
              color="white"
              text-color="primary"
              outline
              @click="toggleDeleteConfim"
              :label="$t('base.undo')"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
      <q-dialog class="full-width" v-model="deleteConfimEvent">
        <q-card class="no-shadow full-width">
          <q-card-section>
            <div class="text-h6">Вы уверены, что хотите удалить событие?</div>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              @click="deleteEvent"
              color="primary"
              :label="$t('base.delete')"
            />
            <q-btn
              color="white"
              text-color="primary"
              outline
              @click="toggleDeleteConfimEvent"
              :label="$t('base.undo')"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </q-card>

    <criteria-dialog ref="criteriaDialog" :cardModel="card" :common="common" />
    <event-dialog ref="eventDialog" :eventData.sync="dialogData" />
  </div>
</template>

<script lang="js">
import CriteriaDialog from './CriteriaDialog.vue';
import EventDialog from './EventDialog.vue';
import { CriteriaTypeEnum } from '@openapi/personal-accounts';
import { SettingsForServiceCriteriaApi } from '@openapi/registry-service';
import { USER_SCOPES } from '@constants/entities/Scope';
import cloneDeep from 'lodash/cloneDeep';
import axios from 'axios';

const settingsForServiceCriteriaApi = new SettingsForServiceCriteriaApi();

export default {
  components: {
    CriteriaDialog,
    EventDialog,
  },
  props: ['common'],
  data() {
    return {
      USER_SCOPES: USER_SCOPES,
      deleteItem: null,
      deleteConfim: false,
      deleteItemEvent: null,
      deleteConfimEvent: false,
      criteriaTypeEnum: CriteriaTypeEnum,
      // TODO: заменить на enum, когда появится в опенапи
      criteriaEnum: {
        'Черновик': 'DRAFT',
        'Активен': 'ACTIVATED',
        'Деактивирован': 'DEACTIVATED',
      },
      dialogData: {},
      eventTypes: [],
    }
  },
  computed: {
    columns() {
      return [
        {
          align: 'left',
          field: 'name',
          label: this.$t('additionalSettings.nameCriterion'),
          name: 'name',
          sortable: true,
          style: 'width: 25%; font-size: 14px',
          headerStyle: 'width: 25%; font-size: 12px; padding-left: 15px;',
          classes: 'text-primary-9',
        },
        {
          align: 'left',
          field: 'description',
          label: this.$t('additionalSettings.description'),
          name: 'description',
          sortable: true,
          style: 'width: 25%;word-break: break-all; font-size: 14px',
          headerStyle: 'width: 25%; font-size: 12px;',
          classes: 'text-primary-9',
        },
        {
          align: 'left',
          field: (val) => { return Object.keys(this.criteriaEnum).filter(key => this.criteriaEnum[key] === val.status) || val.status },
          label: this.$t('additionalSettings.status'),
          name: 'status',
          sortable: true,
          style: 'width: 20%;word-break: break-all; font-size: 14px',
          headerStyle: 'width: 20%; font-size: 12px;',
          classes: 'text-primary-9',
        },
        {
          align: 'left',
          field: (val) => { return Object.keys(this.criteriaTypeEnum).filter(key => this.criteriaTypeEnum[key] === val.type) || val.type },
          label: this.$t('additionalSettings.type'),
          name: 'type',
          sortable: true,
          style: 'width: 20%;word-break: break-all; font-size: 14px',
          headerStyle: 'width: 20%; font-size: 12px;',
          classes: 'text-primary-9',
        },
        {
          align: 'left',
          field: (val) => val.type === 'LIST' && val.values ? val.values.join (', ') : '-',
          label: this.$t('additionalSettings.values'),
          name: 'values',
          sortable: true,
          style: 'width: 20%;word-break: break-all; font-size: 14px',
          headerStyle: 'width: 20%; font-size: 12px;',
          classes: 'text-primary-9',
        },
        {
          align: 'right',
          field: 'file',
          label: this.$t('documents.documentAction'),
          name: 'file',
          sortable: false,
          headerStyle: 'font-size: 12px;',
          classes: 'text-primary-9',
        },
      ];
    },
    columnsEvent() {
      return [
        {
          align: 'left',
          field: 'name',
          label: this.$t('additionalSettings.nameEvent'),
          name: 'name',
          sortable: true,
          style: 'width: 45%; font-size: 14px',
          headerStyle: 'width: 45%; font-size: 12px; padding-left: 15px;',
          classes: 'text-primary-9',
        },
        {
          align: 'left',
          field: (val) => this.eventTypes?.find((ev) => ev.code === val.eventType)?.value || val.eventType,
          label: this.$t('additionalSettings.eventType'),
          name: 'eventType',
          sortable: true,
          style: 'width: 45%;word-break: break-all; font-size: 14px',
          headerStyle: 'width: 45%; font-size: 12px;',
          classes: 'text-primary-9',
        },
        {
          align: 'right',
          field: 'file',
          label: this.$t('documents.documentAction'),
          name: 'file',
          sortable: false,
          headerStyle: 'font-size: 12px;',
          classes: 'text-primary-9',
        },
      ];
    },
    criteria() {
      return this.$store.getters['registryService/additionalSettings/settingsForServiceCard'].settingsforservicecriteria || [];
    },
    events() {
      return this.$store.getters['registryService/additionalSettings/settingsForServiceCard'].settingsforserviceevent || [];
    },
    card() {
      return cloneDeep(
        this.$store.getters['registryService/additionalSettings/settingsForServiceCard']
      );
    },
    cardInitial() {
      return cloneDeep(
        this.$store.getters['registryService/additionalSettings/settingsForServiceCardInitial']
      );
    },
  },
  async created() {
    const { data } = await this.$store.dispatch('registryService/additionalSettings/getSettingsDictionaryEvent', 'DictEventTypeForSettingForService');

    this.eventTypes = data[0].documents;
  },
  methods: {
    addCriteria() {
      this.$refs.criteriaDialog.open()
    },
    toggleDeleteConfim(item) {
      this.deleteConfim = !this.deleteConfim;
      this.deleteItem = item;
    },
    async deleteCriteria() {
      let criteria = cloneDeep(this.criteria);
      const findItem = (this.cardInitial?.settingsforservicecriteria || [])
        .find(e => e.id === this.deleteItem.id);

      if (findItem) {
        await axios.patch('/service/registry/service/settings-for-service', [{
          id: this.card.id, settingsforservicecriteria: [this.deleteItem.id]
        }])
      }
      await settingsForServiceCriteriaApi.deleteSettingsForServiceCriteriaById(this.deleteItem.id);
      criteria = criteria.filter(e => e.id !== this.deleteItem.id);
      this.card.settingsforservicecriteria = criteria;
      this.$store.dispatch(
        'registryService/additionalSettings/setCardForJson',
        this.card
      );
      this.toggleDeleteConfim();
    },
    addEvent() {
      this.$refs.eventDialog.open();
    },
    openEvent(event) {
      console.log(event);
      this.dialogData = event;
      this.$refs.eventDialog.open(event)
    },
    toggleDeleteConfimEvent(item) {
      this.deleteConfimEvent = !this.deleteConfimEvent;
      this.deleteItemEvent = item;
    },
    async deleteEvent() {
      let events = cloneDeep(this.events);
      const findItem = (this.cardInitial?.settingsforserviceevent || [])
        .find(e => e.id === this.deleteItemEvent.id);

      if (findItem) {
        await axios.patch('/service/registry/service/settings-for-service', [{
          id: this.card.id, settingsforserviceevent: [this.deleteItemEvent.id]
        }])
      };
      await axios.delete(`/service/registry/service/settings-for-service-event/${this.deleteItemEvent.id}`);
      events = events.filter(e => e.id !== this.deleteItemEvent.id);
      this.card.settingsforserviceevent = events;
      this.$store.dispatch(
        'registryService/additionalSettings/setCardForJson',
        this.card
      );
      this.toggleDeleteConfimEvent();
    }
  },
}
</script>
