<template>
  <q-dialog v-model="isOpen" @hide="closeDialog">
    <q-card class="full-width no-shadow" style="max-width: 700px">
      <q-card-section>
        <div style="font-size: 1rem; height: 2rem;" class="flex justify-between">
          {{ stage === 2 ? 'Список заявлений:' : serviceName }}
          <q-btn
            v-if="isBackButton"
            padding="xs"
            class="text-grey-7 q-mr-md q-ml-auto"
            color="grey-3"
            icon="arrow_back"
            @click="returnToPrevData(stage)"
          />
        </div>
      </q-card-section>
      <q-card-section class="list">
        <q-table
          :columns="tableColumns"
          :data="rows"
          row-key="name"
          :binary-state-sort="true"
          separator="none"
          dense
          :visible-columns="visibleColumns"
          :totalRowsNumber="values.length"
          :pagination="pagination"
        >
          <template #header="props">
            <q-tr :props="props">
              <q-th v-for="col in props.cols" :key="col.name" :props="props" style="width: 200px;">
               <span class="text-gray-9"> {{ col.label }}</span>
              </q-th>
            </q-tr>
          </template>
          <template #body="props">
            <q-tr
              :props="props"
              class="styled_row q-my-xl q-gutter-y-xl"
              no-hover
            >
              <q-td colspan="3">
                <q-btn
                  v-if="!props.row.number"
                  class="statement__button q-mb-sm"
                  :style="{
                    'background-color': btnBackgroundColor || '#E0E0E0',
                  }"
                  no-caps
                  @click="rowClickHandler(props.row)" 
                  align="left"
                >
                  <p class="title2">
                    <span class="text-left">{{ props.row.name }}</span>
                    <span class="q-ml-md q-mr-xl">{{ props.row.value }}</span>
                  </p>
                </q-btn>
                <q-btn
                  v-else
                  class="statement__button q-mb-sm"
                  no-caps
                  @click="onClickStatement(props.row.number)"
                  :style="{
                    'background-color': btnBackgroundColor || '#E0E0E0',
                  }"
                  align="left"
                >
                  <p class="title3">
                    <span class="q-mr-md" style="min-width: 100px">{{ props.row.number }}</span>
                    <span>{{ props.row.name }}</span>
                    <span class="q-ml-md">{{ props.row.date }}</span>
                  </p>
                </q-btn>
              </q-td>
            </q-tr>
          </template>
          <template #pagination="scope">
            <q-btn
              icon="chevron_left"
              color="grey-8"
              round
              dense
              flat
              :disable="scope.isFirstPage || !!$props.loading"
              @click="scope.prevPage"
            />
            <q-btn
              icon="chevron_right"
              color="grey-8"
              round
              dense
              flat
              :disable="scope.isLastPage || !!$props.loading"
              @click="scope.nextPage"
            />
          </template>
        </q-table>
      </q-card-section>
      <q-card-actions align="right">
        <q-btn
          color="white"
          text-color="primary"
          outline
          @click="closeDialog"
          :label="$t('base.actions.cancel')"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import QColumn from '@/types/QColumn';
import get from 'lodash/get';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';

@Component({})
export default class DetailedListDialog extends Vue {
  @Prop() statements: Record<string, string>[];
  @Prop() byRegions: any;
  @Prop() byOrganisations: any;
  @Prop() name: string;
  private isOpen = false;
  private regions: any[] = [];
  private organisations: any[] = [];
  private values = [];
  private rows: Record<string, string>[] = [];
  private serviceName = '';
  private stage = 0;
  private btnBackgroundColor = '';
  private title = ['Субъект', 'Ведомство', 'Наименование услуги'];
  pagination = {
    rowsPerPage: 10,
  };

  @Watch('statements')
  isStatements(statements: string[][]): void {
    if (!this.statements.length) return;
    this.isOpen = true;
    this.rows = statements.map((el: string[]) => ({
      number: el[2],
      name: this.name[0],
      date: el[0],
    }));
    this.stage = 2;
  }

  @Watch('byRegions')
  isRegions(): void {
    if (this.byRegions?.values?.length) {
      this.isOpen = true;
      this.btnBackgroundColor = this.byRegions.color?.[0];
      this.regions = this.byRegions.names;
      this.values = this.byRegions.values[0].values[0];
      this.serviceName = get(this.byRegions, 'values.0.values.1.0');
      const regionCodes = get(this.byRegions, 'values.0.values.3');
      const targetIds = get(this.byRegions, 'values.0.values.2');
      this.regions = this.regions.map((region, index) => ({
        name: region,
        regionCode: !!regionCodes?.length && regionCodes[index],
        targetId: !!targetIds?.length && targetIds[0],
        value: this.values[index],
      }));
      this.rows = this.regions;
    }
  }

  @Watch('byOrganisations')
  isOrganisations(): void {
    if (this.byOrganisations?.values?.length) {
      this.isOpen = true;
      this.organisations = this.byOrganisations.names;
      this.values = get(this.byOrganisations, 'values.0.values.0');
      const orgId = get(this.byOrganisations, 'values.0.values.2');
      this.organisations = this.organisations.map((organisation, index) => ({
        name: organisation,
        orgId: !!orgId?.length && orgId[0],
        value: this.values[index],
      }));
      this.rows = this.organisations;
      this.stage = 1;
    }
  }

  get visibleColumns(): string[] {
    if (this.stage === 2) {
      return ['number', 'title', 'date'];
    } else {
      return ['title', 'value'];
    }
  }

  get isBackButton(): boolean {
    return !!(
      (this.stage === 1 || this.stage === 2) &&
      (this.regions.length || this.organisations.length)
    );
  }

  onClickStatement(statementNumber: string): void {
    this.$router.push({
      path: '/statements',
      query: { search: statementNumber },
    });
    this.closeDialog();
  }

  closeDialog(): void {
    this.$emit('close');
    this.isOpen = false;
    this.stage = 0;
  }

  rowClickHandler(row: { regionCode?: string; orgId?: string }): void {
    this.$emit('row-handler', row);
  }

  returnToPrevData(stage: number): void {
    if (stage === 1) {
      this.rows = this.regions;
      this.stage = 0;
    }
    if (stage === 2) {
      this.rows = this.organisations;
      this.stage = 1;
    }
  }

  get tableColumns(): Array<QColumn> {
    return [
      {
        name: 'number',
        label: 'Номер',
        field: 'number',
        align: 'left',
        sortable: true,
        style: 'white-space: normal; width: 80px',
      },
      {
        name: 'title',
        label: this.title[this.stage],
        field: 'name',
        align: this.stage === 2 ? 'center' : 'left',
        style: 'white-space: normal;',
      },
      {
        name: 'value',
        label: 'Количество заявлений',
        field: 'value',
        align: 'right',
        sortable: true,
      },
      {
        name: 'date',
        label: 'Дата подачи заявления',
        field: 'date',
        align: 'right',
        sortable: true,
      },
    ];
  }
}
</script>
<style lang="sass">
.statement
  &__button
    background: rgba(255, 0, 0, 0.1)
    color: #000000
    display: block
    width: 70%
    min-width: 100%
    white-space: normal
    text-align: left
    .title2
      display: flex
      width: 100%
      margin-bottom: 0
      justify-content: space-between
    .title3
      display: flex
      width: 100%
      margin-bottom: 0
      text-align: start
      justify-content: space-between
  &__list
    display: grid
    grid-auto-flow: column
    grid-gap: 16px 16px
.list
  overflow: auto
  max-height: 70vh
  min-height: 400px
.styled_row
  border-radius: 5px
  border-color: #0000
  border-width: 0
  :hover
    cursor: pointer
.q-table__bottom
  border-width: 0
.q-table tr
  border-width: 0
  border-color: #0000
  border: none
</style>
