<template>
  <div class="q-pa-md q-gutter-y-md">
    <div
      class="flex justify-between items-center bg-white q-pa-md rounded-borders"
    >
      <div class="column full-width">
        <div>
          <div
            class="text-h6 flex items-center q-gutter-y-md text-grey-9 col q-pr-md"
          >
            <q-btn
              :loading="loading"
              padding="xs"
              class="text-grey-7 q-mr-md"
              color="grey-3"
              icon="arrow_back"
              @click="returnToParentView(parentRoute)"
            />
            <span class="text-h5">{{
              $t('registries.ukranianRefugeePayment.title')
            }}</span>
            <q-space />
            <div class="row items-center q-gutter-x-md q-gutter-y-sm">
              <q-btn
                :label="$t('registries.ukranianRefugeePayment.generatePaymentsRegistry')"
                color="primary"
                :loading="loading"
                @click="generateRegistry"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="bg-white rounded-borders">
      <BaseTable
        :columns="columns"
        :data="data"
        :pagination.sync="pagination"
        :loading="tableLoading"
        @update="updateTableData"
        @requestTable="updateTableData"
      >
        <template #search>
          <SearchBar
            @query="search"
            :loading="loading"
          />
        </template>
        <template v-slot:body-item-sign="props">
          <div class="row no-wrap text-no-wrap float-right">
            <q-btn
              :disable="
                (!get(props.row, 'registryFileLink') &&
                !get(props.row, 'registrySberFileLink')) ||
                noEditRole
              "
              flat
              dense
              icon="arrow_downward"
              size="16"
              style="color: rgba(0, 0, 0, 0.54)"
              color="primary"
              @click="fetchDocumentAttachment(props.row)"
            >
              <q-tooltip>
                {{ $t('registries.objectCard.download') }}
              </q-tooltip>
            </q-btn>

            <q-btn
              v-if="props.row.state === 'Подписан' 
                || (props.row.state === 'Аннулирован' && props.row.registryFileLinkSig)
                || (props.row.state === 'Аннулирован' && props.row.registrySberFileLinkSig)"
              :disable="noEditRole"
              flat
              dense
              icon="gesture"
              size="16"
              style="color: rgba(0, 0, 0, 0.54)"
              color="positive"
              @click="fetchDocumentAttachmentSig(props.row)"
            >
              <q-tooltip>
                {{ $t('registries.objectCard.signedFile') }}
              </q-tooltip>
            </q-btn>
            <q-btn
              v-else
              :disable="props.row.state !== 'Сформирован' || noEditRole"
              flat
              dense
              icon="gesture"
              size="16"
              style="color: rgba(0, 0, 0, 0.54)"
              color="primary"
              @click="addSign(props.row)"
            >
              <q-tooltip>
                {{ $t('registries.objectCard.addEDS') }}
              </q-tooltip>
            </q-btn>
            <!-- бэк не готов -->
            <!-- <AnnulPayment
              @update="updateTableData"
              :registry="props.row"
              :noEditRole="noEditRole"
            /> -->
          </div>
        </template>
      </BaseTable>
      <UploadPaymentStatus
        :open.sync="uploadModal"
        :title="$t('registries.ukranianRefugeePayment.titleDialog')"
        @upload="updateTableData"
      />
      <UploadSignDialog
        :openDialog.sync="signModal"
        :model="currentItem"
        :processInfo="currentProcess"
        @listRefresh="updateTableData"
      />
      <SignInfoDialog
        :openDialog.sync="signInfoModal"
        :model="currentItem"
        @listRefresh="updateTableData"
      />
      <AnnulInfoDialog :openDialog.sync="annulInfoModal" :model="currentItem" />
      <a ref="export" />
    </div>
  </div>
</template>

<script lang="ts">
import { Component } from 'vue-property-decorator';
import { mixins } from 'vue-class-component';
import ReturnToParentView from '@mixins/ReturnToParentView';
import { ExportApi } from '@openapi/refugee-compensation';
import { convertDateFromTimestamp } from '@utils/format-date';
import { DateFormat } from '@constants/utils/format-date';
import QColumn from '@/types/QColumn';
import UploadPaymentStatus from '@components/registries/upload_payment_status.vue';
import { Route } from 'vue-router/types';
import { TablePagination } from '@models/base/TablePagination';
import UploadSignDialog from '@components/registries/ukranian-refugee_upload-sign-dialog.vue';
import SignInfoDialog from '@components/registries/sign_info_dialog.vue';
import AnnulInfoDialog from '@components/registries/annul_info_dialog.vue';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import { saveAs } from 'file-saver';
import SearchBar from '@components/registries/search-bars/ukranian-refugee-payment-search-bar.vue';
import { USER_SCOPES } from '@constants/entities/Scope';
import get from 'lodash/get';
import SearchQuery from '@interfaces/entities/SearchQuery';
import axios from 'axios';
import AnnulPayment from '@components/registries/annul-ukranian-refugee-payment.vue';
import { notifyError, notifySuccess } from '@utils/notify';
import last from 'lodash/last';

const CREATE_EXPORT_REFUGEE_PROCESS_KEY = 'CreateExportRefugee';
const REGISTRIES_LIST_URL = '/registries';
const getFilenameByUrl = (url: string) => last(url.split('/'));

@Component({
  components: {
    AnnulPayment,
    SearchBar,
    UploadPaymentStatus,
    UploadSignDialog,
    SignInfoDialog,
    AnnulInfoDialog,
  },
  methods: {
    get,
  },
})
export default class UkranianRefugeePaymentList extends mixins(ReturnToParentView) {
  private selected: Array<any> = [];
  private data: Array<any> = [];
  private searchQuery: SearchQuery;
  private queryString = '';
  private fulltextString = '';
  private currentProcess: Prosess | null = null;
  private tableLoading = false;
  private currentItem: any | null = null;
  private loading = false;
  private uploadModal = false;
  private signModal = false;
  private signInfoModal = false;
  private annulInfoModal = false;
  private pagination = new TablePagination({
    rowsPerPage: 100,
    descending: true,
    sortBy: 'created',
  });

  private USER_SCOPES = USER_SCOPES;

  private get parentRoute(): { name: string } | string {
    const registryListExists =
      this.$router.$history.findIndex(
        (route: Route) => route.name === 'registry-list'
      ) !== -1;
    if (registryListExists) {
      return { name: 'registry-list' };
    }
    return REGISTRIES_LIST_URL;
  }

  private get columns(): Array<QColumn> {
    return [
      {
        align: 'left',
        field: 'title',
        label: this.$t('registries.ukranianRefugeePayment.name'),
        name: 'title',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        label: this.$t('registries.ukranianRefugeePayment.createDate'),
        field: 'created',
        format: (val: any) =>
          val ? convertDateFromTimestamp(val, DateFormat.date) : '',
        name: 'created',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        label: this.$t('registries.ukranianRefugeePayment.departmentName'),
        field: 'departmentName',
        name: 'departmentName',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        label: this.$t('registries.ukranianRefugeePayment.region'),
        field: 'regionName',
        name: 'regionName',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        label: this.$t('registries.ukranianRefugeePayment.state'),
        field: 'state',
        name: 'state',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: this.$t('registries.ukranianRefugeePayment.sign'),
        field: 'sign',
        name: 'sign',
        required: true,
        sortable: false,
      },
    ];
  }

  private get currentUser(): string {
    return this.$store.getters['oidcClient/currentUser'];
  }

  private get noEditRole(): boolean {
    return !this.$AC.haveOneOfScope([
      USER_SCOPES.REFUGEE_PAYMENT_REGISTRY_OPERATOR,
      USER_SCOPES.ALL_ORG_ADMIN
    ])
  }

  created(): void {
    this.init();
  }

  search(query: SearchQuery): void {
    this.searchQuery = query;
    this.updateTableData();
  }

  async updateTableData(val?: any): Promise<void> {
    this.tableLoading = true;
    const query = [];

    if (typeof this.searchQuery !== 'undefined') {
      this.queryString = this.searchQuery?.query || '';
      this.fulltextString = this.searchQuery?.fulltext || '';
    }

    if (this.queryString) {
      query.push(`${this.queryString}`);
    }
    try {
      const exportApi = new ExportApi();
      const { data } = await exportApi.pagingExportRecords(
        val?.pagination?.page ?? this.pagination.page,
        val?.pagination?.rowsPerPage ?? this.pagination.rowsPerPage,
        query.join(' and '),
        this.fulltextString,
        val?.pagination.sortBy || this.pagination.sortBy
          ? `${
              val?.pagination.descending || this.pagination.descending
                ? '-'
                : '+'
            }${val?.pagination.sortBy ?? this.pagination.sortBy}`
          : ''
      ) as any;

      this.pagination.rowsNumber = data.totalRows || 0;
      this.pagination.page = data.page;
      this.pagination.rowsPerPage = data.perPage;

      this.data = data.records || [];
    } catch (e) {
      notifyError(
        this.$t('registries.ukranianRefugeePayment.noRecordsFound').toString()
      );
      console.warn(`failed count ${e}`);
    } finally {
      this.tableLoading = false;
    }
  }

  private generateRegistry(): void {
    this.loading = true;
    this.$store
      .dispatch('wf/processes/dispatchProcess', {
        processKey: CREATE_EXPORT_REFUGEE_PROCESS_KEY,
        syncMode: false, 
        utStepMode: false, 
        userId: "83fb7e0a-5d86-40a7-81fa-542cc43d2959",
        data: { 
          uuid: this.currentUser.sub
        } 
      })
      .then(({ traceId }) => {
        setTimeout(async () => {
          await this.updateTableData();
          this.loading = false;
        }, 1000);
      });
  }

  private addSign(item: any, process: Prosess): void {
    this.currentProcess = process;
    this.currentItem = item;
    this.signModal = true;
  }

  private annulInfo(item: any): void {
    this.currentItem = item;
    this.annulInfoModal = true;
  }

  private getSignInfo(item: any): void {
    this.currentItem = item;
    this.signInfoModal = true;
  }

  private async init(): Promise<void> {
    await this.updateTableData();
  }

  private async fetchDocumentAttachment(document: any) {
    const allFileLinks:any[] = [];
    for (const doc in document) {
      if(doc.includes('FileLink')){
        allFileLinks.push(document[doc])
      }
    }
    if (allFileLinks.length) {
      for (const link of allFileLinks) {
        console.log('link >>> ', link);
        try {
          const { file } = await S3UrlSignerFilesService.fetchFileFromS3ByUrl({
            url: link,
          });
          saveAs(file, getFilenameByUrl(link));
        } catch (e) {
          notifyError(e.message.toString());
        }
      } 
    }
  }
  private async fetchDocumentAttachmentSig(document: any) {
    const registryFileLinkSig = document?.registryFileLinkSig;
    const registrySberFileLinkSig = document?.registrySberFileLinkSig;

    if (registryFileLinkSig) {
      try {
        const { file } = await S3UrlSignerFilesService.fetchFileFromS3ByUrl({
          url: registryFileLinkSig,
        });
        saveAs(file, getFilenameByUrl(registryFileLinkSig));
      } catch (e) {
        notifyError(e.message.toString());
      }
    }

    if (registrySberFileLinkSig) {
      try {
        const { file } = await S3UrlSignerFilesService.fetchFileFromS3ByUrl({
          url: registrySberFileLinkSig,
        });
        saveAs(file, getFilenameByUrl(registrySberFileLinkSig));
      } catch (e) {
        notifyError(e.message.toString());
      }
    }
  }
}

declare interface Prosess {
  taskId: string;
  traceId: string;
  success: boolean;
}
</script>
