<template>
  <q-card class="no-shadow" style="min-width: 600px">
    <template>
      <template>
        <q-card-section class="q-pb-none text-h6">
          {{ $t('serviceMappingTitle') }}
        </q-card-section>
        <q-card-section>
          <div class="q-pb-none text-h6">{{ $t('visible') }}</div>
          <div>
            <q-table
              :columns="tableColumns"
              :data="visible"
              :pagination="pagination"
              hide-bottom
            >
              <template #header="props">
                <q-tr :props="props">
                  <q-th
                    v-for="col in props.cols"
                    :key="col.name"
                    style="font-size: 14px; font-weight: 600; text-align: left"
                  >
                    {{ col.label }}
                  </q-th>
                  <q-th />
                  <q-th />
                </q-tr>
              </template>

              <template #body="props">
                <q-tr :props="props">
                  <q-td>
                    {{ props.row.data.label }}
                  </q-td>
                  <q-td>
                    <q-btn
                      v-if="props.rowIndex > 1"
                      text-color="primary"
                      icon="arrow_upward"
                      @click="up(props.rowIndex)"
                    />
                  </q-td>
                  <q-td>
                    <q-btn
                      v-if="
                        props.rowIndex !== 0 &&
                        props.rowIndex !== visible.length - 1
                      "
                      text-color="primary"
                      icon="arrow_downward"
                      @click="down(props.rowIndex)"
                    />
                  </q-td>
                  <q-td>
                    <q-btn
                      v-if="!isDefault(props.row)"
                      text-color="secondary"
                      :label="$t('hide')"
                      @click="hideColumn(props.rowIndex)"
                    />
                  </q-td>
                </q-tr>
              </template>
            </q-table>
          </div>
        </q-card-section>
        <q-card-section>
          <div class="q-pb-none text-h6">{{ $t('hidden') }}</div>
          <div>
            <q-table
              :columns="tableColumns"
              :data="hidden"
              :pagination="pagination"
              hide-bottom
            >
              <template #header="props">
                <q-tr :props="props">
                  <q-th
                    v-for="col in props.cols"
                    :key="col.name"
                    style="font-size: 14px; font-weight: 600; text-align: left"
                  >
                    {{ col.label }}
                  </q-th>
                  <q-th />
                  <q-th />
                </q-tr>
              </template>

              <template #body="props">
                <q-tr :props="props">
                  <q-td>
                    {{ props.row.data.label }}
                  </q-td>
                  <q-td> </q-td>
                  <q-td> </q-td>
                  <q-td>
                    <q-btn
                      text-color="secondary"
                      :label="$t('show')"
                      @click="showColumn(props.rowIndex)"
                    />
                  </q-td>
                </q-tr>
              </template>
            </q-table>
          </div>
        </q-card-section>
        <q-card-section class="row justify-between">
          <q-btn
            color="secondary"
            :label="$t('returnToDefaults')"
            @click="() => (isDeleteModalVisible = true)"
          />
          <q-btn color="primary" :label="$t('save')" @click="changeColumns" />
        </q-card-section>
      </template>
    </template>

    <q-dialog class="full-width" v-model="isDeleteModalVisible">
      <q-card class="q-pa-md">
        <ConfirmationForm
          :input-data="{ title: $t('returnToDefaultsConfirmation') }"
          @submit="(e, v) => onDeleteSubmit(v.result)"
        />
      </q-card>
    </q-dialog>
  </q-card>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { TableColumn } from '@/interfaces';
import cloneDeep from 'lodash/cloneDeep';
import { Columns } from '../index.vue';
import { WithScopeAccess } from '@/interfaces/entities/Access';
import { createDefaultColumn, getKey } from '../utils/columns';
import ConfirmationForm from '@/components/forms/ConfirmationForm.vue';

@Component({
  components: {
    ConfirmationForm,
  },
})
export default class ServiceMapping extends Vue {
  @Prop() columns: Columns;
  @Prop() defaultColumns: Function;
  @Prop() mapping: any;

  defaultCols: WithScopeAccess<TableColumn>[] = [];

  visible: WithScopeAccess<TableColumn>[] = [];
  hidden: WithScopeAccess<TableColumn>[] = [];
  isDeleteModalVisible = false;
  tableColumns = [
    { name: 'title', align: 'left', label: this.$t('name') },
    { name: 'actions', align: 'left', label: this.$t('actions') },
  ];
  pagination = {
    rowsPerPage: 0,
  };

  async created() {
    this.defaultCols = this.defaultColumns();
    this.fillColumns();
  }

  onDeleteSubmit(result: boolean) {
    if (result) {
      this.returnToDefaults();
    }
    this.isDeleteModalVisible = false;
  }

  fillColumns() {
    this.visible = cloneDeep(this.columns.visible);
    this.hidden = cloneDeep(this.columns.hidden);
    this.mapping?.attrList.forEach((attr: any) => {
      if (
        !this.columns.visible.some(
          (c: WithScopeAccess<TableColumn>) => c.data.field === attr.value
        ) &&
        !this.columns.hidden.some(
          (c: WithScopeAccess<TableColumn>) => c.data.field === attr.value
        )
      ) {
        this.hidden.push(createDefaultColumn(attr.value, attr.name));
      }
    });
    this.visible = this.$AC.scopesSiftWithoutDataMapping(this.visible);
  }

  hideColumn(index: number) {
    const [col] = this.visible.splice(index, 1);
    this.hidden.push(col);
  }

  showColumn(index: number) {
    const [col] = this.hidden.splice(index, 1);
    this.visible.push(col);
  }

  isDefault(column: WithScopeAccess<TableColumn>) {
    const key = getKey(column);
    return this.defaultCols.some(
      (dc: WithScopeAccess<TableColumn>) => key === getKey(dc)
    );
  }

  changeColumns() {
    this.$emit('change-columns', this.visible, this.hidden);
  }

  returnToDefaults() {
    this.visible = cloneDeep(this.defaultCols);

    this.hidden = [];
    this.mapping.attrList.forEach((attr: any) => {
      this.hidden.push(createDefaultColumn(attr.value, attr.name));
    });

    this.changeColumns();

    this.$emit('clear-statements-storage');
  }

  up(index: number) {
    const tmp = this.visible[index - 1];
    this.$set(this.visible, index - 1, this.visible[index]);
    this.$set(this.visible, index, tmp);
  }

  down(index: number) {
    const tmp = this.visible[index + 1];
    this.$set(this.visible, index + 1, this.visible[index]);
    this.$set(this.visible, index, tmp);
  }
}
</script>

<style scoped lang="scss"></style>

<i18n>
{
  "ru": {
    "serviceMappingTitle": "Редактирование колонок",
    "generateRegister": "Сформировать",
    "mappingNotFound": "Маппинг для данной услуги не найден",
    "save": "Сохранить",
    "visible": "Видимые",
    "hidden": "Скрытые",
    "hide": "Спрятать",
    "show": "Показать",
    "returnToDefaults": "Вернуть к исходному состоянию",
    "returnToDefaultsConfirmation": "Вы действительно хотите вернуть колонки к изначальному состоянию?",
    "name": "Наименование",
    "actions": "Действия"
  },
  "en": {
    "serviceMappingTitle": "Columns edit",
    "generateRegister": "Generate",
    "mappingNotFound": "Mapping not found for this service",
    "save": "Save",
    "visible": "Visible",
    "hidden": "Hidden",
    "hide": "Hide",
    "show": "Show",
    "returnToDefaults": "Return to default state",
    "returnToDefaultsConfirmation": "Do you really want to return the speakers to their original state?",
    "name": "Name",
    "actions": "Actions"
  }
}
</i18n>
