<i18n>
{
  "en": {
    "ChargesCard": {
      "paymentStatus": "Accrual status",
      "balance": "Balance",
      "chargeStatus": "Charge status",
      "YIN": "Action",
      "paymentAmmount": "Accrual ammount, rub",
      "paymentPurpose": "Payment purpose",
      "payerID": "Payer ID",
      "KBK": "KBK",
      "legalPersonINN": "Legal person INN",
      "legalPersonKPP": "Legal person KPP",
      "BIK": "BIK",
      "OKTMO": "OKTMO",
      "printedFormLink": "Link to the printed form of payment",
      "noData": "No data",
      "edit": "Edit",
      "regType": "Registration results",
      "checkType": "Payment results",
      "type": "Type",
      "data": "Data",
      "requestDate": "Request date",
      "responseDate": "Response date",
      "downloadResponse": "Download response",
      "downloadRequest": "Download request",
      "discountType": "Discount type",
      "discountSize": "Payment terms with a fixed amount of discount",
      "discountSizePercent": "Discount payment terms",
      "discountValue": "Discount value",
      "discountDate": "Discount date",
      "inKopecks": "In Kopecks",
      "inPercents": "In Percents. Number from 0 to 100",
      "hidePayment": "Hide payment",
      "isEPGUPaymentRequired": "Is EPGU payment required?"
    }
  },
  "ru": {
    "ChargesCard": {
      "chargeStatus": "Статус квитирования",
      "paymentStatus": "Статус начисления",
      "balance": "Баланс",
      "YIN": "УИН",
      "paymentAmmount": "Сумма начисления, руб.",
      "paymentPurpose": "Назначение платежа",
      "payerID": "Идентификатор плательщика",
      "KBK": "КБК",
      "legalPersonINN": "ИНН юридического лица",
      "legalPersonKPP": "КПП юридического лица",
      "BIK": "БИК",
      "OKTMO": "ОКТМО",
      "printedFormLink": "Ссылка на печатную форму начисления",
      "noData": "Нет данных",
      "edit": "Редактировать",
      "regType": "Результаты регистрации",
      "checkType": "Результаты оплаты",
      "type": "Тип",
      "data": "Данные",
      "requestDate": "Дата запроса",
      "responseDate": "Дата ответа",
      "downloadResponse": "Скачать ответ",
      "downloadRequest": "Скачать запрос",
      "discountType": "Тип скидки",
      "discountSize": "Условия оплаты с фиксированной суммой скидки",
      "discountSizePercent": "Условия оплаты со скидкой",
      "discountValue": "Размер скидки",
      "discountDate": "Дата окончания скидки",
      "inKopecks": "В Копейках",
      "inPercents": "В процентах. Число от 0 до 100",
      "hidePayment": "Скрыть начисление",
      "isEPGUPaymentRequired": "Требуется оплата через ЕПГУ?"
    }
  }
}
</i18n>

<template>
  <div v-if="common.active === 'charges'" class="q-pb-md">
    <a v-show="false" ref="export" />
    <a v-show="false" ref="info" />
    <q-card class="no-shadow q-gutter-y-md q-mx-md no-border-radius">
      <div
        v-for="(payment, index) in paymentsLocal"
        v-if="!loading"
        :key="payment.id"
        class="q-mx-md q-pt-md q-pa-sm"
      >
        <div
          class="flex items-center justify-end full-width text-subtitle1 q-pb-md"
        >
          <span class="q-mr-auto">
            {{
              `Начисление от ${convertDateFromBackendFormat(
                payment.chargeDate
              )}`
            }}
          </span>
          <q-btn
            class="q-ml-md"
            v-if="canCheckPayment[payment.id]"
            color="primary"
            label="Проверить оплату"
            @click="checkPayment(payment)"
          />
          <q-btn
            class="q-ml-md"
            v-if="checkIfPaymentCanBeHided(payment)"
            color="warning"
            :label="$t('ChargesCard.hidePayment')"
            @click="hidePayment(payment)"
          />
          <q-btn
            class="q-ml-md"
            v-if="chargeBinded(index)"
            color="primary"
            outline
            label="Аннулировать квитирование"
            @click="quittanceForm(index, 'annulate')"
          />
          <q-btn
            v-if="isQuittance(payment, index)"
            class="q-ml-md"
            color="primary"
            outline
            label="Квитировать"
            @click="quittanceForm(index, 'quittance')"
          />
        </div>

        <div class="col text-primary q-mb-lg">
          <div class="q-gutter-y-md">
            <base-label-value
              padded-label
              :loading="loading"
            >
              <template #label>
                <div
                  class="flex content-center"
                  :style="{ 'min-height': '100%' }"
                >
                  {{ $t('ChargesCard.isEPGUPaymentRequired') }}
                  <q-badge v-if="!isEPGUSelected(index)" color="white">
                    <q-icon
                      name="error_outline"
                      color="negative"
                      style="font-size: 18px; position: relative; left: 7px"
                    />
                    <q-tooltip>Обязательно для выбора</q-tooltip>
                  </q-badge>
                </div>
              </template>
              <template 
                v-if="
                  Number(payment.systemStatus) < 3 &&
                  !payment.tableInfo.length &&
                  !payment.epguSendAbilityDisable
                "
                #value
              >
                <q-radio 
                  :val="true"
                  :value="payment.EPGUPaymentRequired"
                  @input="updateEPGUPaymentRequired(true, index)"
                  label="Да"
                />
                <q-radio 
                  :val="false"
                  :value="payment.EPGUPaymentRequired"
                  @input="updateEPGUPaymentRequired(false, index)"
                  label="Нет"
                />
              </template>
              <template v-else #value>
                {{ payment.EPGUPaymentRequired ? 'Да' : 'Нет' }}
                <q-badge
                  v-if="payment.epguSendAbilityDisableComment.length"
                  color="white"
                >
                  <q-icon name="help" flat size="18px" color="blue-grey-3" />
                  />
                  <q-tooltip>{{payment.epguSendAbilityDisableComment}}</q-tooltip>
                </q-badge>
              </template>
            </base-label-value>

            <base-label-value padded-label :loading="loading">
              <template #label>
                {{ $t('ChargesCard.paymentStatus') }}
              </template>
              <template #value>
                {{ get(payment, 'systemLabel', $t('ChargesCard.noData')) }}
              </template>
            </base-label-value>

            <div v-if="payment.quittance">
              <base-label-value padded-label :loading="loading">
                <template #label>
                  {{ $t('ChargesCard.chargeStatus') }}
                </template>
                <template #value>
                  {{ getChargeSratus(get(payment, 'quittance.billStatus')) }}
                </template>
              </base-label-value>
  
              <base-label-value padded-label class="q-mt-md" :loading="loading">
                <template #label>
                  {{ $t('ChargesCard.balance') }}
                </template>
                <template #value>
                  {{ (Number(get(payment, 'quittance.balance'))/100).toFixed(2) }} р
                </template>
              </base-label-value>
            </div>

            <base-label-value padded-label :loading="loading">
              <template #label>
                {{ $t('ChargesCard.YIN') }}
              </template>
              <template #value>
                {{
                  get(
                    payment,
                    'charge.supplierBillId',
                    $t('ChargesCard.noData')
                  )
                }}
              </template>
            </base-label-value>

            <base-label-value padded-label :loading="loading">
              <template #label>
                {{ $t('ChargesCard.paymentAmmount') }}
              </template>
              <template v-if="!paymentsIsEdited[index]" #value>
                {{ payment.charge.totalAmount }}
              </template>
              <template v-else #value>
                <q-input
                  v-model="payment.charge.totalAmount"
                  reverse-fill-mask
                  filled
                />
              </template>
            </base-label-value>

            <base-label-value
              v-if="
                paymentsAdditionalLocal[index].discountType ||
                paymentsAdditionalIsEdited[index]
              "
              padded-label
              :loading="loading"
            >
              <template #label>
                {{ $t('ChargesCard.discountType') }}
              </template>
              <template v-if="!paymentsIsEdited[index]" #value>
                {{
                  getDiscountType(paymentsAdditionalLocal[index].discountType)
                }}
              </template>
              <template v-else #value>
                <q-select
                  v-model="paymentsAdditionalLocal[index].discountType"
                  clearable
                  emit-value
                  map-options
                  filled
                  :options="discountTypes"
                  @input="paymentsAdditionalLocal[index].discountValue = ''"
                >
                  <template #selected-item="scope">
                    <q-item v-bind="scope.itemProps" v-on="scope.itemEvents">
                      <q-item-section>
                        <q-item-label>
                          {{ scope.opt.label }}
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </template>
            </base-label-value>

            <base-label-value
              v-if="
                paymentsAdditionalLocal[index].discountValue ||
                (paymentsAdditionalIsEdited[index] &&
                  paymentsAdditionalLocal[index].discountType)
              "
              padded-label
              :loading="loading"
            >
              <template #label>
                {{ $t('ChargesCard.discountValue') }}
              </template>
              <template v-if="!paymentsAdditionalIsEdited[index]" #value>
                {{ paymentsAdditionalLocal[index].discountValue }}
                <span
                  v-if="
                    paymentsAdditionalLocal[index].discountType ===
                    'discountSizePercent'
                  "
                  >%</span
                >
              </template>
              <template
                v-else-if="
                  paymentsAdditionalIsEdited[index] &&
                  paymentsAdditionalLocal[index].discountType === 'discountSize'
                "
                #value
              >
                <q-input
                  v-model="paymentsAdditionalLocal[index].discountValue"
                  :label="$t('ChargesCard.inKopecks')"
                  reverse-fill-mask
                  filled
                />
              </template>
              <template
                v-else-if="
                  paymentsAdditionalIsEdited[index] &&
                  paymentsAdditionalLocal[index].discountType ===
                    'discountSizePercent'
                "
                #value
              >
                <q-input
                  v-model="paymentsAdditionalLocal[index].discountValue"
                  type="number"
                  :label="$t('ChargesCard.inPercents')"
                  reverse-fill-mask
                  filled
                  :rules="[hittingTheIntervalRule(0, 100)]"
                />
              </template>
            </base-label-value>

            <base-label-value
              v-if="
                paymentsAdditionalLocal[index].discountDate ||
                paymentsAdditionalIsEdited[index]
              "
              padded-label
              :loading="loading"
            >
              <template #label>
                {{ $t('ChargesCard.discountDate') }}
              </template>
              <template v-if="!paymentsIsEdited[index]" #value>
                {{ paymentsAdditionalLocal[index].discountDate }}
              </template>
              <template v-else #value>
                <q-input
                  v-model="paymentsAdditionalLocal[index].discountDate"
                  filled
                >
                  <template #append>
                    <q-icon name="event" class="cursor-pointer">
                      <q-popup-proxy
                        ref="qDateProxy"
                        transition-show="scale"
                        transition-hide="scale"
                      >
                        <q-date
                          v-model="paymentsAdditionalLocal[index].discountDate"
                          mask="YYYY-MM-DD"
                        />
                      </q-popup-proxy>
                    </q-icon>
                  </template>
                </q-input>
              </template>
            </base-label-value>

            <base-label-value padded-label :loading="loading">
              <template #label>
                {{ $t('ChargesCard.paymentPurpose') }}
              </template>
              <template v-if="!paymentsIsEdited[index]" #value>
                {{ get(payment, 'charge.billFor', $t('ChargesCard.noData')) }}
              </template>
              <template v-else #value>
                <q-input v-model="payment.charge.billFor" filled />
              </template>
            </base-label-value>

            <base-label-value padded-label :loading="loading">
              <template #label>
                {{ $t('ChargesCard.payerID') }}
              </template>
              <template #value>
                {{ get(payment, 'charge.payerId', $t('ChargesCard.noData')) }}
              </template>
            </base-label-value>

            <base-label-value padded-label :loading="loading">
              <template #label>
                {{ $t('ChargesCard.KBK') }}
              </template>
              <template v-if="!paymentsIsEdited[index]" #value>
                {{ get(payment, 'charge.KBK', $t('ChargesCard.noData')) }}
              </template>
              <template v-else #value>
                <q-input v-model="payment.charge.KBK" filled />
              </template>
            </base-label-value>

            <base-label-value padded-label :loading="loading">
              <template #label>
                {{ $t('ChargesCard.legalPersonINN') }}
              </template>
              <template #value>
                {{
                  get(
                    payment,
                    'charge.organization.INN',
                    $t('ChargesCard.noData')
                  )
                }}
              </template>
            </base-label-value>

            <base-label-value padded-label :loading="loading">
              <template #label>
                {{ $t('ChargesCard.legalPersonKPP') }}
              </template>
              <template #value>
                {{
                  get(
                    payment,
                    'charge.organization.KPP',
                    $t('ChargesCard.noData')
                  )
                }}
              </template>
            </base-label-value>

            <base-label-value padded-label :loading="loading">
              <template #label>
                {{ $t('ChargesCard.BIK') }}
              </template>
              <template #value>
                {{
                  get(
                    payment,
                    'charge.organization.bank.BIK',
                    $t('ChargesCard.noData')
                  )
                }}
              </template>
            </base-label-value>

            <base-label-value padded-label :loading="loading">
              <template #label>
                {{ $t('ChargesCard.OKTMO') }}
              </template>
              <template v-if="!paymentsIsEdited[index]" #value>
                {{ get(payment, 'charge.OKTMO', $t('ChargesCard.noData')) }}
              </template>
              <template v-else #value>
                <q-input
                  v-model="payment.charge.OKTMO"
                  reverse-fill-mask
                  filled
                  :rules="[oktmoFormatRule]"
                />
              </template>
            </base-label-value>

            <template v-if="canEdit">
              <q-btn
                v-if="!paymentsIsEdited[index]"
                color="primary"
                :label="$t('ChargesCard.edit')"
                @click="setEditMode(index)"
              />
              <q-btn
                v-else
                :label="`Сохранить`"
                :loading="false"
                color="primary"
                @click="update(index)"
              />
            </template>
            <div class="q-my-md">
              <q-table
                v-if="payment.tableInfo.length"
                class="no-shadow text-grey-7"
                row-key="key"
                :columns="tableColumns"
                :data="payment.tableInfo"
                wrap-cells
                hide-bottom
              >
                <template #body="props">
                  <q-tr :props="props">
                    <q-td
                      :key="props.cols[0].name"
                      auto-width
                      :props="props"
                      style="width: 400px; font-weight: bold; padding-left: 0"
                      :colspan="props.cols.length"
                    >
                      <div class="q-pl-md">
                        {{ props.cols[0].value }}
                      </div>
                    </q-td>
                  </q-tr>
                  <template v-for="row in props.row.children">
                    <tr>
                      <td v-for="col in tableColumns">
                        <template v-if="col.name === 'data'">
                          <div class="flex column items-start justify-center">
                            <div class="q-mb-sm">
                              <q-btn
                                :disable="
                                  !Boolean(get(row, 'requestSmev')) &&
                                  !Boolean(get(row, 'requestFsmev'))
                                "
                                target="_blank"
                                size="sm"
                                style="
                                  background: #d9e2eb;
                                  color: #222;
                                  width: 120px;
                                "
                                :label="$t('ChargesCard.downloadRequest')"
                                @click="downloadInfo($event, row, 'request')"
                              />
                            </div>
                            <div>
                              <q-btn
                                :disable="
                                  !Boolean(get(row, 'responseSmev')) &&
                                  !Boolean(get(row, 'responseFsmev'))
                                "
                                target="_blank"
                                size="sm"
                                style="
                                  background: #d9e2eb;
                                  color: #222;
                                  width: 120px;
                                "
                                :label="$t('ChargesCard.downloadResponse')"
                                @click="downloadInfo($event, row, 'response')"
                              />
                            </div>
                          </div>
                        </template>
                        <template
                          v-else-if="
                            col.name === 'request' || col.name === 'response'
                          "
                        >
                          {{
                            convertDateFromBackendFormat(
                              get(row, `${col.name}.date`)
                            )
                          }}
                        </template>
                        <template v-else>
                          {{ row[col.name] }}
                        </template>
                      </td>
                    </tr>
                  </template>
                </template>
              </q-table>
            </div>
          </div>
        </div>
      </div>
      <div v-if="loading" style="padding: 100px">
        <q-inner-loading :showing="loading">
          <q-spinner-gears color="primary" size="50px" />
        </q-inner-loading>
      </div>
    </q-card>
  </div>
</template>

<script lang="ts">
import { convertDateFromBackendFormat } from '@utils/format-date';
import { oktmoFormatRule } from '@utils/field-validation/organizations';
import { hittingTheIntervalRule } from '@utils/field-validation/numbers';
import { saveFileViaLink } from '@utils/files';
import { CardNeedToUpdateType } from '@constants/models/Card';
import get from 'lodash/get';
import find from 'lodash/find';
import uniq from 'lodash/uniq';
import cloneDeep from 'lodash/cloneDeep';
import isPlainObject from 'lodash/isPlainObject';
import { notifyError, notifySuccess, notifyInfo } from '@utils/notify';
import {
  Charge,
  ChargeAdditionalDataParams,
  Payment,
  PaymentTemplate,
} from '@openapi/mz-payment-service';
import { WorkflowServiceApi } from '@openapi/wf';
import QColumn from '@/types/QColumn';
import { RequestInfo } from '@openapi/mz-history';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { BaseCardCommon } from '@/interfaces';
import { Document, DocumentApi } from '@openapi/document-registry';
import { chargeStatus } from './components/payments/ChargeStatus';

const wfApi = new WorkflowServiceApi();

const documentApi = new DocumentApi();

const FORMED_PAYMENT = 1;

enum DiscountMode {
  DiscountSize = 'discountSize',
  DiscountSizePercent = 'discountSizePercent',
}

interface TableItem {
  type: string;
  children: MessageData[];
}

interface MessageData extends RequestInfo {
  type: string;
}

export type Quitannce = {
    balance: number;
    billStatus: string;
    paymentIdData: string[];
}

interface PaymentWithTableInfo extends Payment {
  tableInfo: TableItem[];
  quittance?: Quitannce;
  EPGUPaymentRequired: boolean | undefined;
  isEPGUPaymentRequired: 'true' | 'false';
  epguSendAbilityDisable: boolean;
}

@Component({
  methods: {
    get,
    convertDateFromBackendFormat,
    oktmoFormatRule,
    hittingTheIntervalRule,
  },
})
export default class Charges extends Vue {
  @Prop() private common?: BaseCardCommon;
  @Prop() private model?: any;
  @Prop() private userTask?: any;

  $refs!: {
    info: HTMLAnchorElement;
  };

  paymentsLocal: PaymentWithTableInfo[] = [];
  paymentsAdditionalLocal: PaymentTemplate[] = [];
  paymentsIsEdited: boolean[] = [];
  paymentsAdditionalIsEdited: boolean[] = [];
  chargeStatusMap: Record<number, string> = chargeStatus;
  loading = false;
  discountTypes = [
    {
      label: this.$t('ChargesCard.discountSize').toString(),
      value: DiscountMode.DiscountSize,
    },
    {
      label: this.$t('ChargesCard.discountSizePercent').toString(),
      value: DiscountMode.DiscountSizePercent,
    },
  ];

  get canEdit(): boolean {
    return (get(this.userTask, 'userTask.outData.actions') || []).includes(
      'editPayments'
    );
  }

  get payments(): PaymentWithTableInfo[] {
    return get(this.model, 'payments') || [];
  }

  get canCheckPayment(): Record<string, Payment> {
    if (!this.paymentsLocal || !Array.isArray(this.paymentsLocal)) return {};
    return this.paymentsLocal.reduce((result, nextPayment) => {
      // todo OPENAPI mz-payment check typings and values (got string)
      // @ts-ignore
      result[nextPayment.id] =
        // todo OPENAPI mz-payment check typings and values (got string)
        // @ts-ignore
        nextPayment.systemStatus === '3' &&
        nextPayment.EPGUPaymentRequired === true;

      return result;
    }, {} as Record<string, Payment>);
  }

  get tableColumns(): Array<QColumn> {
    return [
      {
        name: 'type',
        label: this.$t('ChargesCard.type'),
        field: 'type',
        align: 'left',
      },
      {
        name: 'data',
        label: this.$t('ChargesCard.data'),
        field: 'data',
        align: 'left',
      },
      {
        name: 'request',
        label: this.$t('ChargesCard.requestDate'),
        field: 'request',
        align: 'left',
      },
      {
        name: 'response',
        label: this.$t('ChargesCard.responseDate'),
        field: 'response',
        align: 'left',
      },
    ];
  }

  chargeBinded(index: number): boolean {
    return !!(typeof this.paymentsLocal[index].quittance !== 'undefined');
  }

  isQuittance(payment: PaymentWithTableInfo, index: number): boolean {
    return (
      Number(payment.systemStatus) === 3 &&
      !this.chargeBinded(index) &&
      payment.EPGUPaymentRequired === false
    );
  }

  private async quittanceForm(
    index: number,
    type: 'annulate' | 'quittance'
  ): Promise<void> {
    this.loading = true;
    const charge = this.paymentsLocal[index];
    let bindedPayments = [];
    if (type === 'annulate') {
      bindedPayments = get(charge, 'quittance.paymentIdData', []);
    }

    const sendData = {
      applicationId: this.common?.id,
      chargeId: charge.id,
      paymentReceivedIdList: bindedPayments.length ? bindedPayments : undefined,
      withoutPayment: type === 'quittance' ? true : undefined,
      action: type === 'quittance' ? 'reconcile' : 'annulmentReconcile',
    };

    const { traceId } = await this.$store
      .dispatch('wf/processes/dispatchProcess', {
        processKey: 'PaymentsQuittancesProcess',
        data: sendData,
      })
      .catch((e) => notifyError(e.toString()))
      .finally(() => {
        delete this.model.charge;
        this.loading = false;
        notifyInfo('Запрос отправлен');
      });

    if (traceId) {
      const handler = (e: any) => {
        const data = JSON.parse(get(e, 'data', '{}'));
        if (data.traceId === traceId) {
          console.log('console >>> ', data);
          // this.$store.commit(
          //   'utils/cards/needToUpdate',
          //   CardNeedToUpdateType.MODEL
          // );
          // this.$websockets.removeListener(handler);
        }
      };
      this.$websockets.addListener(handler);
    }
  }

  isEPGUSelected(index: number): boolean {
    return !!(
      typeof this.paymentsLocal[index].EPGUPaymentRequired !== 'undefined'
    );
  }

  getChargeSratus(index: string): string {
    return this.chargeStatusMap ? this.chargeStatusMap[Number(index)] : '';
  }

  @Watch('payments')
  paymentsHandler(): void {
    this.init();
  }

  async init(): Promise<void> {
    this.loading = true;
    this.paymentsLocal = cloneDeep(this.payments);
    this.initAdditionalParams();
    for (let i = 0; i < this.paymentsLocal.length; i++) {
      this.paymentsIsEdited[i] = false;
      this.paymentsAdditionalIsEdited[i] = false;
      const payment = this.paymentsLocal[i];
      this.paymentsLocal[i].tableInfo = await this.getMzInfos(payment);
      if (
        payment.epguSendAbilityDisable &&
        typeof payment.EPGUPaymentRequired === 'undefined'
      ) {
        this.updateEPGUPaymentRequired(false, i);
      }
    }
    this.loading = false;
  }

  initAdditionalParams(): void {
    this.paymentsLocal.forEach((payment) => {
      const additionalParams: PaymentTemplate = {
        discountType: '',
        // todo OPENAPI mz-payment check types
        // @ts-ignore
        discountValue: '',
        discountDate: '',
      };
      const params: ChargeAdditionalDataParams[] = get(
        payment,
        'charge.additionalData.params',
        null
      );
      if (params) {
        params.forEach((param) => {
          switch (param.name) {
            case 'discountDate':
              // todo OPENAPI
              // @ts-ignore
              additionalParams.discountDate = param.value;
              break;
            case 'discountSize':
            case 'discountSizePercent':
              additionalParams.discountType = param.name;
              // todo OPENAPI mz-payment check types
              // @ts-ignore
              additionalParams.discountValue = param.value;
              break;
            default:
              break;
          }
        });
        this.paymentsAdditionalLocal.push(additionalParams);
      } else {
        this.paymentsAdditionalLocal.push(additionalParams);
      }
    });
  }

  getDiscountType(type: DiscountMode): string {
    const typeObj = find(this.discountTypes, (opt) => opt.value === type);
    return typeObj?.label || '-';
  }

  setEditMode(index: number): void {
    this.paymentsIsEdited.splice(index, 1, true);
    this.paymentsAdditionalIsEdited.splice(index, 1, true);
  }

  update(index: number): void {
    const documentObject = {
      id: this.paymentsLocal[index].id,
      // todo OPENAPI mz-payment add modified
      // @ts-ignore
      modified: this.paymentsLocal[index].modified,
      systemLabel: this.paymentsLocal[index].systemLabel,
      charge: {
        totalAmount: parseInt(
          get(this.paymentsLocal, `[${index}].charge.totalAmount`)
        ),
        KBK: get(this.paymentsLocal, `[${index}].charge.KBK`),
        OKTMO: get(this.paymentsLocal, `[${index}].charge.OKTMO`),
        billFor: get(this.paymentsLocal, `[${index}].charge.billFor`),
        additionalData: {
          params: [],
        },
      } as Charge,
    };
    if (
      get(this.paymentsAdditionalLocal, `[${index}].discountType`, '') &&
      get(this.paymentsAdditionalLocal, `[${index}].discountValue`, '')
    ) {
      documentObject.charge.additionalData?.params?.push({
        name: get(this.paymentsAdditionalLocal, `[${index}].discountType`, ''),
        value: get(
          this.paymentsAdditionalLocal,
          `[${index}].discountValue`,
          ''
        ),
      });
    }
    if (get(this.paymentsAdditionalLocal, `[${index}].discountDate`, '')) {
      documentObject.charge.additionalData?.params?.push({
        name: 'discountDate',
        value: get(this.paymentsAdditionalLocal, `[${index}].discountDate`, ''),
      });
    }
    documentApi
      .updateDocument('Payment', [documentObject as Document])
      .then(() => {
        this.$store.commit(
          'utils/cards/needToUpdate',
          CardNeedToUpdateType.MODEL
        );
      });
    this.paymentsIsEdited[index] = false;
  }

  updateEPGUPaymentRequired(value: boolean, index: number): void {
    this.paymentsLocal[index].EPGUPaymentRequired = value;

    const documentObject = {
      id: this.paymentsLocal[index].id,
      EPGUPaymentRequired: this.paymentsLocal[index].EPGUPaymentRequired,
    };

    documentApi
      .updateDocument('Payment', [documentObject as Document])
      .then(() => {
        this.$store.commit(
          'utils/cards/needToUpdate',
          CardNeedToUpdateType.MODEL
        );
      });
  }

  checkPayment(payment: Payment): void {
    // todo OPENAPI
    // @ts-ignore
    // eslint-disable-next-line eqeqeq
    if (payment.systemStatus != '3') return;

    const applicationId = this.model && this.model.id;

    if (applicationId) {
      this.$store.dispatch('wf/processes/dispatchProcess', {
        processKey: 'GisGMPCheckPaymentsSubProcess',
        data: { applicationId },
      });
    }
  }

  checkIfPaymentCanBeHided(payment: PaymentWithTableInfo): boolean {
    return (
      // todo OPENAPI systemStatus
      // @ts-ignore
      // eslint-disable-next-line eqeqeq
      payment.systemStatus == FORMED_PAYMENT && !payment.registrationRequestIds
    );
  }

  async hidePayment(payment: Payment): Promise<void> {
    this.loading = true;
    const sendData = {
      paymentId: payment.id,
      id: 'hidePayments',
    };

    const taskId = get(this.userTask, 'userTask.taskId');
    if (!taskId) {
      return;
    }
    wfApi
      .submitForm(taskId, sendData as any)
      .catch((e) => {
        notifyError(e.message.toString());
      })
      .finally(() => {
        this.$store.dispatch('commonComponents/charges/setLoading', false);
        const route = this.$route;

        if (route.query.active === 'charges') {
          this.$router.push({
            name: route.name || '',
            params: route.params || {},
            query: {
              ...route.query,
              active: 'author',
            },
          });
        }
      });
  }

  getMzInfos(payment: Payment): Promise<TableItem[]> {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve) => {
      const regIds = get(payment, 'registrationRequestIds', []);
      const checkIds = get(payment, 'paymentCheckRequestIds', []);
      const uniqRegIds = uniq(regIds);
      const uniqCheckIds = uniq(checkIds);
      const tableData = [];
      if (uniqRegIds.length) {
        const regData: TableItem = {
          type: this.$t('ChargesCard.regType').toString(),
          children: [],
        };
        for (const id of uniqRegIds) {
          await this.$store
            .dispatch('mz/history/getHistoryInfo', id)
            .then((data: RequestInfo) => {
              regData.children.push({
                type: id,
                ...data,
              });
            })
            // eslint-disable-next-line @typescript-eslint/no-empty-function
            .catch(() => {});
        }
        tableData.push(regData);
      }
      if (uniqCheckIds.length) {
        const checkData: TableItem = {
          type: this.$t('ChargesCard.checkType').toString(),
          children: [],
        };
        for (const id of uniqCheckIds) {
          await this.$store
            .dispatch('mz/history/getHistoryInfo', id)
            .then((data: RequestInfo) => {
              checkData.children.push({
                type: id,
                ...data,
              });
            })
            // eslint-disable-next-line @typescript-eslint/no-empty-function
            .catch(() => {});
        }
        tableData.push(checkData);
      }
      resolve(tableData);
    });
  }

  downloadInfo($event: Event, info: TableItem, target: string): void {
    if (isPlainObject(info)) {
      const smev = get(info, `${target}Smev.content`, null);
      const fsmev = get(info, `${target}Fsmev.content`, null);
      const currentInfo = fsmev || smev;
      const blob = new Blob([currentInfo], { type: 'text/xml' });
      const file = new File([blob], `${target}.xml`);
      const url = URL.createObjectURL(file);
      saveFileViaLink({
        anchor: this.$refs.info,
        hrefData: url,
        fileName: `${target}.xml`,
      });
    }
  }
}
</script>
