<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">
          <BaseTable
            :columns="columns"
            :data.sync="critList"
            :rows-per-page-options="[10, 20, 50, 100]"
            :pagination.sync="pagination"
            :title="$t('criteriaDirectory.label')"
            @update:pagination="init"
            @requestTable="init"
            @update="init"
          >
            <template #search>
              <q-input
                v-model="filter"
                dense
                filled
                debounce="1000"
                placeholder="Введите название критерия"
                @input="handleSearchChange"
                @keydown.enter="handleSearchChange"
                @keydown.esc="filter = ''"
              />
            </template>
            <template v-slot:body-item-activity="props">
              <div class="row no-wrap text-no-wrap float-left">
                <q-checkbox
                  :value="props.row.activity"
                  @input="activityEdit(props.row)"
                />
              </div>
            </template>
          </BaseTable>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn 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 { CriteriaApi } from '@openapi/personal-accounts';
import { SettingsForServiceCriteriaApi } from '@openapi/registry-service';
import cloneDeep from 'lodash/cloneDeep';
import { notifyError } from '@utils/notify';

const criteriaApi = new CriteriaApi();
const settingsForServiceCriteriaApi = new SettingsForServiceCriteriaApi();

export default {
  name: 'CriteriaDialog',
  data() {
    return {
      pagination: {
        rowsPerPage: 10,
        rowsNumber: 0,
        page: 1,
        descending: true,
        sort: '-modified',
      },
      settingsDialog: false,
      critList: [],
      filter: '',
      loading: true,
    };
  },
  computed: {
    columns() {
      return [
        {
          align: 'left',
          field: 'activity',
          name: 'activity',
          sortable: true,
          style: 'width: 15%; font-size: 14px',
          headerStyle: 'width: 15%; font-size: 12px; padding-left: 15px;',
          classes: 'text-primary-9',
        },
        {
          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: '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: 'status',
          label: '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',
        },
      ];
    },
    cardCriteria() {
      return (
        this.$store.getters[
          'registryService/additionalSettings/settingsForServiceCard'
        ].settingsforservicecriteria || []
      );
    },
  },
  methods: {
    handleSearchChange() {
      this.query();
    },
    activityEdit(row) {
      row.activity = !row.activity;
    },
    init({ pagination } = {}) {
      if (pagination) {
        this.pagination.page = pagination.page;
        this.pagination.rowsPerPage = pagination.rowsPerPage;
      }
      this.query();
    },
    async query() {
      this.loading = true;
      this.pagination.query = '';
      if (this.filter !== '') {
        const and = this.pagination.query === '' ? '' : ' and ';
        this.pagination.query = this.pagination.query.concat(
          `${and}name=like=*${this.filter}*`
        );
      }

      if (this.cardCriteria.length) {
        const cardCriteria = this.cardCriteria.map((e) => e.criteriaId);
        const and = this.pagination.query === '' ? '' : ' and ';
        this.pagination.query = this.pagination.query.concat(
          `${and}id=out=(${cardCriteria.join(',')})`
        );
      }

      await criteriaApi
        .pagingCriteria(
          this.pagination.page,
          this.pagination.rowsPerPage,
          this.pagination.query,
          undefined,
          this.pagination.sort,
          '',
          {}
        )
        .then((criteries) => {
          this.critList = criteries.data.records.map((e) => ({
            ...e,
            activity: false,
          }));
          this.pagination.rowsNumber = criteries.data.totalRows;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    open() {
      this.clearForm();
      this.loading = true;
      this.settingsDialog = true;
    },
    create() {
      const criteriaFilter = this.critList
        .filter((e) => e.activity)
        .map((e) => ({ ...e, criteriaId: e.id }));

      criteriaFilter.map((e) =>
        settingsForServiceCriteriaApi
          .createSittingsForServiceCriteria([{ criteriaId: e.criteriaId }])
          .then((res) => {
            const card = cloneDeep(
              this.$store.getters[
                'registryService/additionalSettings/settingsForServiceCard'
              ]
            );
            const criteria = card.settingsforservicecriteria || [];

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

    clearForm() {
      this.pagination = {
        rowsPerPage: 10,
        rowsNumber: 0,
        page: 1,
        descending: true,
        sort: '-modified',
      };
      this.filter = '';
    },
  },
};
</script>
