<template>
  <div>
    <div class="bg-white flex items-center q-pa-md q-ma-md rounded-borders">
      <q-btn
        padding="xs"
        class="text-grey-7 q-mr-md"
        color="grey-3"
        icon="arrow_back"
        @click="goBack"
      />
      <div class="title text-h6">{{ card.shortName }}</div>

      <q-btn
        v-if="stateAddPayment.includes(card.state)"
        :loading="editLoading"
        color="primary"
        class="q-ml-auto"
        label="Сохранить"
        type="button"
        @click="saveService"
      />
    </div>

    <div class="bg-white q-mx-md q-pa-lg">
      <PaymentTable
        :common="common"
        :model="model"
        :card="card"
        :payments="payments"
        :state-add-payment="stateAddPayment"
        :region-code="regionCode"
        @commonModels="commonModels"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import PaymentTable from '@components/cards/services/PaymentsTable.vue';
import { updateService } from '@services/registry-service';
import { RegionApi } from '@openapi/idm';
import { notifySuccess } from '@utils/notify';

const regionApi = new RegionApi();

@Component({
  components: {
    PaymentTable,
  },
})
export default class Payments extends Vue {
  region: any = null;
  formComponent = null;
  formModel = {};
  model = {};
  common = {
    models: {
      paymentDialog: null,
    },
  };

  pagination = {
    rowsPerPage: 0,
  };

  stateAddPayment = ['signed', 'readyToPublish', 'published', 'inProgress'];

  editLoading = false;

  async created() {
    this.getService();

    this.region = await regionApi
      .getRegion(this.$route.query.regionId.toString())
      .then(({ data }) => data)
      .catch(() => {
        throw new Error('[components][cards][payments][Index][getRegion]');
      });
  }

  private goBack(): void {
    this.$router.push({
      name: 'cards',
      params: {
        id: this.$route.query.regionId.toString(),
        path: 'regions',
      },
      query: {
        active: 'payments',
        components: this.$store.getters['cardComponents/regions/components'],
      },
    });
  }

  private getService(): void {
    this.$store.dispatch('registryService/services/getServiceMeta', {
      id: this.$route.params.id,
    });
  }

  private saveService(): void {
    this.editLoading = true;
    const serviceModel = { ...this.card };
    Object.keys(serviceModel).forEach((key) => {
      if (Array.isArray(serviceModel[key])) {
        serviceModel[key] = serviceModel[key].map((i: any) => i.id || i);
      }
    });

    updateService(serviceModel)
      .then(({ data }) => {
        if (this.card) {
          this.card.modified = data.modified;
        }

        notifySuccess(this.$t('services.ServiceCart.saveSuccess').toString());
      })
      .catch((e) => {
        console.log('[Save payments] ', e);
      })
      .finally(() => {
        this.editLoading = false;
      });
  }

  private commonModels(val: any): void {
    this.common.models = val;
  }

  private get card() {
    return this.$store.getters['registryService/services/servicesCard'];
  }

  private get regionCode(): string | null {
    return this.region?.code || null;
  }

  private get payments() {
    return (this.card.paymentLinks || []).filter(
      (payment: any) => payment.regionCode === this.regionCode
    );
  }
}
</script>
