<i18n>
{
  "en": {
    "OrganizationsFormsBasic": {
      "fullName": "Full name",
      "opf": "Legal form",
      "abbreviatedName": "Abbreviated name",
      "dns": "DNS",
      "organizationAddress": "Legal address",
      "postalOrganizationAddress": "Postal address",
      "inn": "TIN",
      "notChoose": "Not choose",
      "ogrn": "PSRN",
      "kpp": "IEC",
      "emailAddress": "E-mail address",
      "telephone": "Phone number",
      "send": "Send",
      "save": "Save",
      "parentOrganization": "Parent organization",
      "region": "Region",
      "tnsDepartmentId": "Depatment ID",
      "cancel": "Cancel",
      "oktmo": "OKTMO",
      "requiredOktmo": "The number must be 8 or 11 characters",
      "orgDate": "Date of state registration of the organization",
      "orgType": "Organization type",
      "invalidUrn": "The field must contain 6 Latin characters or numbers",
      "required": "Field is required",
      "enable": "Enable",
      "enabled": "Enabled",
      "disable": "Disable",
      "disabled": "Disabled",
      "confirmation": "Confirm",
      "questionToDisable": "Are you sure you want to block the organization? This will block all of its users.",
      "questionToDeleteCert": "Are you sure you want to delete certificate?",
      "yes": "Yes",
      "no": "No",
      "block": "Block",
      "certificate": "Certificate",
      "alias": "Alias",
      "password": "Password",
      "keys": "Keys archive",
      "attachKeys": "Attach keys",
      "attachCert": "Attach certificate",
      "download": "Download",
      "update": "Update",
      "delete": "Delete",
      "needToAdd": "The field needs to be filled"
    }
  },
  "ru": {
    "OrganizationsFormsBasic": {
      "fullName": "Полное наименование",
      "opf": "ОПФ",
      "abbreviatedName": "Сокращённое наименование",
      "dns": "DNS",
      "organizationAddress": "Адрес организации",
      "postalOrganizationAddress": "Почтовый адрес организации",
      "inn": "ИНН",
      "notChoose": "Не выбрано",
      "ogrn": "ОГРН",
      "kpp": "КПП",
      "emailAddress": "Адрес электронной почты",
      "telephone": "Телефон",
      "send": "Отправить",
      "save": "Сохранить",
      "parentOrganization": "Вышестоящая организация",
      "region": "Субъект РФ",
      "tnsDepartmentId": "ID ведомства (ЕПГУ)",
      "cancel": "Отмена",
      "oktmo": "ОКТМО",
      "requiredOktmo": "Номер должен быть 8 или 11 значный",
      "orgDate": "Дата гос. регистрации организации",
      "orgType": "Тип организации",
      "invalidUrn": "Поле дожно содержать 6 латинских символов или цифр",
      "required": "Обязательное поле",
      "enable": "Разблокировать",
      "enabled": "Разблокирована",
      "disable": "Заблокировать",
      "disabled": "Заблокирована",
      "confirmation": "Подтвердите",
      "questionToDisable": "Вы уверены, что хотите заблокировать организацию? Это приведет к блокировке всех ее пользователей.",
      "questionToDeleteCert": "Вы уверены, что хотите удалить сертификат?",
      "yes": "Да",
      "no": "Нет",
      "block": "Блокировка",
      "certificate": "Сертификат",
      "alias": "Алиас",
      "password": "Пароль",
      "keys": "Архив с ключами",
      "attachKeys": "Приложите ключи",
      "attachCert": "Приложите сертификат",
      "download": "Скачать",
      "update": "Обновить",
      "delete": "Удалить",
      "needToAdd": "Поле нужно заполнить"
    }
  }
}
</i18n>

<template>
  <q-form @submit="submit">
    <div v-if="!readonly" class="q-gutter-y-md">
      <div class="row q-gutter-x-md">
        <div class="row col q-gutter-y-md">
          <div class="col-xs-12 col-sm q-mr-sm-md">
            <q-input
              filled
              :label="$t('OrganizationsFormsBasic.fullName') + '*'"
              v-model="fullname"
              :rules="[() => !!fullname]"
              :error-message="$t('OrganizationsFormsBasic.needToAdd')"
            />
          </div>
          <div class="col-xs-12 col-sm-3">
            <q-input
              filled
              :label="$t('OrganizationsFormsBasic.opf')"
              v-model="leg"
            />
          </div>
        </div>
      </div>
      <div class="row col">
        <div class="col-xs-12 col-sm">
          <q-input
            filled
            :label="$t('OrganizationsFormsBasic.abbreviatedName') + '*'"
            v-model="shortname"
            :rules="[() => !!shortname]"
            :error-message="$t('OrganizationsFormsBasic.needToAdd')"
          />
        </div>
        <!-- <div class="col-xs-12 col-sm-3 q-mt-xs-md q-mt-sm-none">
          <q-input
            filled
            :label="$t('OrganizationsFormsBasic.dns') + '*'"
            :readonly="!!inputData.isEditProcess"
            lazy-rules
            v-model="dns"
            :rules="[() => !!dns]"
            :error-message="$t('OrganizationsFormsBasic.needToAdd')"
          >
          </q-input>
        </div> -->
      </div>
      <div class="row col">
        <div class="col-xs-12 col-sm">
          <q-input
            filled
            label="Код военного комиссариата"
            v-model="militaryCode"
            :rules="[
              () =>
                !militaryCode ||
                militaryCode.length === 8 ||
                'Должен состоять из 8 цифр',
            ]"
            mask="########"
          />
        </div>
      </div>
      <div class="row q-qutter-x-md">
        <div class="col">
          <BasicMAddressComponent
            :id.sync="addressId"
            :value.sync="address"
            :label="$t('OrganizationsFormsBasic.organizationAddress')"
            filled
          />
        </div>
      </div>
      <div class="row q-qutter-x-md">
        <div class="col">
          <BasicMAddressComponent
            :id.sync="postalAddressId"
            :value.sync="postalAddress"
            :label="$t('OrganizationsFormsBasic.postalOrganizationAddress')"
            filled
          />
        </div>
      </div>
      <div class="row q-qutter-x-md">
        <div class="col">
          <q-select
            :options="regionOptions"
            emit-value
            filled
            :label="$t('OrganizationsFormsBasic.region') + '*'"
            map-options
            clearable
            v-model="region"
            :rules="[() => !!region]"
            :error-message="$t('OrganizationsFormsBasic.needToAdd')"
          />
        </div>
      </div>
      <div class="row col">
        <div class="col-xs-12 col-sm">
          <q-input
            filled
            label="Часовой пояс"
            v-model="timezone"
            :rules="[() => rulesTimezone(timezone)]"
          />
        </div>
      </div>
      <div class="row q-qutter-x-md">
        <div class="col">
          <!-- TODO: создать компонент q-select с инпутом -->
          <q-select
            filled
            v-model="parentOrganizationSelected"
            :label="$t('OrganizationsFormsBasic.parentOrganization')"
            :options="optionsOrg"
            :loading="loadingOrg"
            option-label="shortname"
            option-value="id"
            use-input
            input-debounce="1000"
            @filter="filterOrg"
          />
        </div>
      </div>
      <!-- <div class="row q-qutter-x-md">
        <div class="col">
          <q-input
            filled
            :label="$t('OrganizationsFormsBasic.tnsDepartmentId')"
            v-model="tnsDepartmentId"
          />
        </div>
      </div> -->
      <div class="row">
        <div class="col-xs-12 col-sm q-mr-sm-md">
          <q-select
            :options="orgTypes"
            map-options
            emit-value
            filled
            :label="$t('OrganizationsFormsBasic.orgType')"
            v-model="govOrganizationType"
          />
        </div>
        <div class="col-xs-12 col-sm q-mt-xs-md q-mt-sm-none">
          <q-input
            class="q-pb-none"
            :label="$t('OrganizationsFormsBasic.orgDate')"
            filled
            v-model="govRegistrationDate"
            :mask="inputMask"
          >
            <template v-slot:append>
              <q-icon name="event" class="cursor-pointer">
                <q-popup-proxy
                  ref="qDateProxy"
                  transition-show="scale"
                  transition-hide="scale"
                >
                  <q-date v-model="govRegistrationDate" :mask="dateMask" />
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>
        </div>
      </div>
      <div class="row">
        <div class="col-xs-12 col-sm q-mr-sm-md">
          <q-input
            filled
            :label="$t('OrganizationsFormsBasic.inn') + '*'"
            mask="##########"
            unmasked-value
            v-model="inn"
            :rules="[() => !!inn]"
            :error-message="$t('OrganizationsFormsBasic.needToAdd')"
          />
        </div>
        <div class="col-xs-12 col-sm q-mt-xs-md q-mt-sm-none">
          <q-input
            filled
            :label="$t('OrganizationsFormsBasic.ogrn') + '*'"
            mask="#############"
            unmasked-value
            v-model="ogrn"
            :rules="[() => !!ogrn]"
            :error-message="$t('OrganizationsFormsBasic.needToAdd')"
          />
        </div>
      </div>
      <div class="row">
        <div class="col-xs-12 col-sm q-mr-sm-md">
          <q-input
            filled
            :label="$t('OrganizationsFormsBasic.kpp')"
            mask="#########"
            unmasked-value
            v-model="kpp"
          />
        </div>
        <div class="col-xs-12 col-sm q-mt-xs-md q-mt-sm-none">
          <q-input
            filled
            :label="$t('OrganizationsFormsBasic.oktmo')"
            v-model="oktmo"
          />
        </div>
      </div>
      <div class="row">
        <div class="col-xs-12 col-sm q-mr-sm-md">
          <q-input
            filled
            :label="$t('OrganizationsFormsBasic.emailAddress')"
            type="email"
            v-model="email"
          >
            <template v-slot:prepend>
              <q-icon name="email" />
            </template>
          </q-input>
        </div>
        <div class="col-xs-12 col-sm q-mt-xs-md q-mt-sm-none">
          <q-input
            fill-mask
            filled
            :label="$t('OrganizationsFormsBasic.telephone')"
            mask="+7 (###) ###-##-##"
            unmasked-value
            v-model="phone"
          >
            <template v-slot:prepend>
              <q-icon name="phone" />
            </template>
          </q-input>
        </div>
      </div>
      <!-- <div
        class="row"
        v-if="certificate && !transSertDelete && existedCertificate"
      >
        <div class="col-xs-6 col-sm q-mr-sm-md">
          <a ref="download" download="certificate.cer" />
          <div class="flex justify-between items-center">
            <div class="text-subtitle2">
              {{ $t('OrganizationsFormsBasic.certificate') }}
            </div>
            <div class="flex justify-end items-center">
              <q-btn
                color="primary"
                outline
                icon="assignment_returned"
                :label="$t('OrganizationsFormsBasic.download')"
                :disable="!currentCertFile"
                style="max-width: 160px"
                @click="downloadCert"
              />
              <q-btn
                class="q-ml-md"
                color="primary"
                icon="assignment"
                :label="$t('OrganizationsFormsBasic.update')"
                :disable="!currentCertFile"
                style="max-width: 160px"
                @click="updateCert"
              />
              <q-btn
                class="q-ml-md"
                color="negative"
                icon="delete"
                :label="$t('OrganizationsFormsBasic.delete')"
                :disable="!currentCertFile"
                style="max-width: 160px"
                @click="openDeleteCertModal"
              />
            </div>
          </div>
        </div>
      </div>
      <div v-if="!existedCertificate">
        <div class="row">
          <div class="col-xs-12 col-sm q-mr-sm-md">
            <q-file
              v-model="certFile"
              :label="$t('OrganizationsFormsBasic.certificate')"
              @input="certHandler"
              accept=".cer, .cert, .crt"
              clearable
            >
              <template v-slot:append>
                <q-icon name="article" />
              </template>
            </q-file>
          </div>
          <div class="col-xs-12 col-sm q-mt-xs-md q-mt-sm-none">
            <q-file
              v-model="keysFile"
              :label="$t('OrganizationsFormsBasic.keys')"
              accept=".zip, .rar"
              clearable
            >
              <template v-slot:append>
                <q-icon name="folder" />
              </template>
            </q-file>
          </div>
        </div>
        <div class="row">
          <div class="col-xs-12 col-sm q-mr-sm-md">
            <q-input
              filled
              :label="$t('OrganizationsFormsBasic.alias')"
              type="text"
              v-model="aliasKey"
            >
            </q-input>
          </div>
          <div class="col-xs-12 col-sm q-mt-xs-md q-mt-sm-none">
            <q-input
              filled
              :label="$t('OrganizationsFormsBasic.password')"
              type="text"
              v-model="passKey"
            >
            </q-input>
          </div>
        </div>
      </div> -->
      <div class="row col q-gutter-y-md">
        <div class="col-xs-6 col-sm q-mr-sm-md">
          <q-toggle
            v-model="reportsEnabled"
            :label="
              reportsEnabled ? 'Включать в отчеты' : 'Исключать из отчетов'
            "
          />
        </div>
        <div class="col-xs-6 col-sm q-mr-sm-md">
          <q-toggle
            v-model="enabled"
            :label="
              enabled
                ? $t('OrganizationsFormsBasic.disable')
                : $t('OrganizationsFormsBasic.enable')
            "
            :true-value="false"
            :false-value="true"
            @input="showConfirmDisableModal"
          />
        </div>
      </div>
      <q-btn
        v-if="!inputData.isEditProcess"
        color="primary"
        :label="$t('OrganizationsFormsBasic.send')"
        type="submit"
      />
      <div v-if="inputData.isEditProcess" class="row q-gutter-y-md">
        <q-btn
          class="col-xs-12 col-sm-auto"
          color="primary"
          :label="$t('OrganizationsFormsBasic.cancel')"
          @click="cancelProcess"
          type="button"
          outline
        />
        <q-btn
          class="col-xs-12 col-sm-auto q-ml-sm-md"
          color="primary"
          :label="$t('OrganizationsFormsBasic.save')"
          type="submit"
          :disable="!outputData.organization.region"
        />
      </div>
    </div>
    <div v-else class="q-gutter-y-xs">
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.fullName') }}*
        </div>
        <div class="col text-grey-7">{{ fullname }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.abbreviatedName') }}*
        </div>
        <div class="col text-grey-7">{{ shortname }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.opf') }}
        </div>
        <div class="col text-grey-7">{{ leg }}</div>
      </div>
      <!-- <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.dns') }}*
        </div>
        <div class="col text-grey-7">{{ dns }}</div>
      </div> -->
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.organizationAddress') }}
        </div>
        <div class="col text-grey-7">{{ address }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.postalOrganizationAddress') }}
        </div>
        <div class="col text-grey-7">{{ postalAddress }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.region') }}
        </div>
        <div class="col text-grey-7">{{ regionLabelReadonly }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.parentOrganization') }}
        </div>
        <div class="col text-grey-7">{{ parentLabel }}</div>
      </div>
      <!-- <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.tnsDepartmentId') }}
        </div>
        <div class="col text-grey-7">{{ tnsDepartmentId }}</div>
      </div> -->
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.orgDate') }}
        </div>
        <div class="col text-grey-7">{{ govRegistrationDate }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.orgType') }}
        </div>
        <div class="col text-grey-7">{{ govOrganizationType }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.inn') }}*
        </div>
        <div class="col text-grey-7">{{ inn }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.ogrn') }}*
        </div>
        <div class="col text-grey-7">{{ ogrn }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.oktmo') }}*
        </div>
        <div class="col text-grey-7">{{ oktmo }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.kpp') }}
        </div>
        <div class="col text-grey-7">{{ kpp }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.emailAddress') }}
        </div>
        <div class="col text-grey-7">{{ email }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.telephone') }}
        </div>
        <div class="col text-grey-7">{{ phone }}</div>
      </div>
      <!-- <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.certificate') }}
        </div>
        <div class="col text-grey-7">{{ certificate }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.alias') }}
        </div>
        <div class="col text-grey-7">{{ aliasKey }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.password') }}
        </div>
        <div class="col text-grey-7">{{ passKey }}</div>
      </div> -->
      <div class="row">
        <div class="col text-grey-5">Включать в отчеты</div>
        <div class="col text-grey-7">
          {{ reportsEnabled ? 'Да' : 'Нет' }}
        </div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsBasic.block') }}
        </div>
        <div class="col text-grey-7">
          {{
            enabled
              ? $t('OrganizationsFormsBasic.enabled')
              : $t('OrganizationsFormsBasic.disabled')
          }}
        </div>
      </div>
    </div>
    <q-dialog v-model="disableModal" persistent>
      <q-card class="no-shadow">
        <q-card-section>
          <div class="text-h6">
            {{ $t('OrganizationsFormsBasic.confirmation') }}
          </div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          {{ $t('OrganizationsFormsBasic.questionToDisable') }}
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            flat
            @click="
              () => {
                this.enabled = !enabled;
                this.disableModal = false;
              }
            "
            :label="$t('OrganizationsFormsBasic.no')"
            color="primary"
          />
          <q-btn
            flat
            @click="disableModal = false"
            :label="$t('OrganizationsFormsBasic.yes')"
            color="red"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-dialog v-model="deleteCertModal">
      <q-card class="no-shadow">
        <q-card-section>
          <div class="text-h6">
            {{ $t('OrganizationsFormsBasic.confirmation') }}
          </div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          {{ $t('OrganizationsFormsBasic.questionToDeleteCert') }}
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            flat
            @click="deleteCertModal = false"
            :label="$t('OrganizationsFormsBasic.no')"
            color="primary"
          />
          <q-btn
            flat
            @click="deleteCertificate"
            :label="$t('OrganizationsFormsBasic.yes')"
            color="red"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-form>
</template>

<script lang="ts">
// @ts-nocheck
import BasicMAddressComponent from '@components/m-address/index.vue';
import BaseTreeSelector from '@components/common/base-tree-selector/index.vue';
import { v4 } from 'uuid';
import { convertDateFormat } from '@utils/format-date';
import { DateFormat } from '@constants/utils/format-date';
import get from 'lodash/get';
import isPlainObject from 'lodash/isPlainObject';
import { WorkflowServiceApi } from '@openapi/wf';
import { OrganizationApi, GraphApi, RegionApi } from '@openapi/idm';

const wfApi = new WorkflowServiceApi();
const graphApi = new GraphApi();
const regionApi = new RegionApi();
const organizationApi = new OrganizationApi();

export default {
  props: ['input-data', 'readonly'],
  components: {
    BaseTreeSelector,
    BasicMAddressComponent,
  },
  data() {
    return {
      transSertDelete: false,
      existedCertificate: false,
      certFile: null,
      keysFile: null,
      aliasKey: '',
      passKey: '',
      certificate: '',
      enabled: true,
      id: '',
      isActiveForm: true,
      email: '',
      fullname: '',
      inn: '',
      kpp: '',
      govRegistrationDate: '',
      govOrganizationType: '',
      ogrn: '',
      oktmo: '',
      phone: '',
      reportsEnabled: true,
      shortname: '',
      militaryCode: '',
      addressId: '',
      address: '',
      postalAddress: '',
      postalAddressId: '',
      dns: '',
      leg: '',
      parentOrganizationSelected: null,
      region: '',
      regionLabelReadonly: '',
      regionOptions: [],
      tnsDepartmentId: '',
      orgTypes: [],
      disableModal: false,
      deleteCertModal: false,
      optionsOrg: [],
      loadingOrg: false,
      timezone: '',
    };
  },
  async created(): Promise<void> {
    regionApi
      .searchRegions()
      .then(({ data }) => {
        if (Array.isArray(data) && data.length > 0) {
          this.regionOptions = data.map((regionObject) => {
            return {
              value: get(regionObject, 'id'),
              label: get(regionObject, 'fullname') || get(regionObject, 'name'),
            };
          });
        }
      })
      .catch(() => {
        throw new Error(
          '[components][forms][OrganizationsFormsBasic][searchRegions]'
        );
      });
    this.setDictionaryValues('rosregister_declarant_kind', this.orgTypes);
    await this.getOrganizations();
  },
  computed: {
    dateMask() {
      return this.$store.getters['i18N/localeMask'].date;
    },
    inputMask() {
      return this.$store.getters['i18N/localeMask'].input;
    },
    regionLabel() {
      let label = '';

      if (
        this.region &&
        Array.isArray(this.regionOptions) &&
        this.regionOptions.length > 0
      ) {
        const regionObject = this.regionOptions.find(
          (item) => item.value === this.region
        );

        label = get(regionObject, 'label');
      }

      return label || this.$t('OrganizationsFormsBasic.notChoose');
    },
    outputData() {
      const dataObject = {
        organization: {
          certificate: this.certificate,
          aliasKey: this.aliasKey,
          passKey: this.passKey,
          enabled: this.enabled,
          id: this.id || v4(),
          email: this.email,
          fullname: this.fullname,
          inn: this.inn,
          kpp: this.kpp,
          ogrn: this.ogrn,
          oktmo: this.oktmo,
          govOrganizationType: this.govOrganizationType,
          phone: this.phone,
          reportsEnabled: this.reportsEnabled,
          shortname: this.shortname,
          militaryCode: this.militaryCode?.length
            ? this.militaryCode
            : 'emptyValue',
          timezone: this.timezone,
          addressId: this.addressId,
          address: this.address,
          postalAddressId: this.postalAddressId,
          postalAddress: this.postalAddress,
          dns: this.dns,
          name: this.dns,
          leg: this.leg,
          parent: this.parentOrganizationSelected?.id || this.region || '',
          region: this.region || '',
          tnsDepartmentId: this.tnsDepartmentId,
        },
        transSertDelete: this.transSertDelete,
        transExit: false,
        parentLabel:
          this.parentOrganizationSelected?.shortname ||
          this.$t('OrganizationsFormsBasic.notChoose'),
        regionLabel: this.regionLabel,
      };

      if (this.govRegistrationDate) {
        dataObject.organization.govRegistrationDate = convertDateFormat(
          this.govRegistrationDate,
          this.dateMask,
          DateFormat.dashedDate
        );
      }

      return dataObject;
    },
    currentCertFile() {
      if (this.certificate) {
        const bs = atob(this.certificate);
        const buffer = new ArrayBuffer(bs.length);
        const ba = new Uint8Array(buffer);
        for (let i = 0; i < bs.length; i++) {
          ba[i] = bs.charCodeAt(i);
        }
        const blob = new Blob([ba], { type: 'application/x-x509-ca-cert' });
        const url = window.URL.createObjectURL(blob);
        return url;
      }
      return null;
    },
  },
  methods: {
    get,
    /**
     * Функция получения списка организаций
     * @param {string} findOrgString строка из поля ввода поиска в селекте организаций
     */
    async getOrganizations(findOrgString?: string): Promise<void> {
      if (!this.loadingOrg) {
        this.loadingOrg = true;
        const query = findOrgString
          ? `fullname=like='%${findOrgString}%' or name=like='%${findOrgString}%'`
          : '';
        await organizationApi
          .searchOrganizations(undefined, query)
          .then((response) => {
            this.optionsOrg = response.data || [];
          })
          .finally(() => {
            this.loadingOrg = false;
          });
      }
    },
    rulesTimezone(timezone) {
      const regex = /^[+|-]((0[0-9]|1[0-1]):([0-5][0-9])|12:00)$/;
      const regexMinusZero = /^-00:00$/;
      return (
        !timezone ||
        (regex.test(timezone) && !regexMinusZero.test(timezone)) ||
        'Должен быть в формате +01:30'
      );
    },
    /**
     * Функция фильтрации в поле выбора ролей
     * @param {string} val
     * @param {function} update
     */
    async filterOrg(val: string, update: () => void): Promise<void> {
      if (val.length > 1 || val === '') {
        await this.getOrganizations(val);
        update();
      }
    },
    // certHandler(val) {
    //   if (val) {
    //     const reader = new FileReader();
    //     // eslint-disable-next-line @typescript-eslint/no-this-alias
    //     const that = this;
    //     reader.onload = (function () {
    //       return function (e) {
    //         const binaryData = e.target.result;
    //         const base64String = window.btoa(binaryData);
    //         that.certificate = base64String;
    //       };
    //     })(that.certFile);
    //     reader.readAsBinaryString(that.certFile);
    //   }
    // },
    downloadCert() {
      const a = this.$refs.download;
      const url = this.currentCertFile;
      a.href = url;
      a.click();
      window.URL.revokeObjectURL(url);
    },
    updateCert() {
      this.certificate = null;
      this.passKey = '';
      this.aliasKey = '';
      this.existedCertificate = false;
    },
    openDeleteCertModal() {
      this.deleteCertModal = true;
    },
    deleteCertificate() {
      this.transSertDelete = true;
      this.certificate = '';
      this.aliasKey = '';
      this.passKey = '';
      this.deleteCertModal = false;
    },
    showConfirmDisableModal() {
      if (!this.enabled) {
        this.disableModal = true;
      }
    },
    setDictionaryValues(id, data, valueName = 'value') {
      this.$store
        .dispatch('registryService/referenceBooks/fetchReferenceBook', {
          id: id,
          limit: 200,
        })
        .then((dict) => {
          if (isPlainObject(dict)) {
            // eslint-disable-next-line array-callback-return
            Object.entries(dict).map(([key, value]) => {
              data.push({
                value: key,
                label: value[valueName] || '',
              });
            });
          }
        });
    },
    submit(e) {
      if (this.keysFile) {
        wfApi.submitFormWithFiles(
          this.inputData.userTaskId,
          undefined,
          undefined,
          this.keysFile,
          JSON.stringify(this.outputData)
        );
      } else {
        this.$emit('submit', e, this.outputData);
      }
    },
    cancelProcess(e) {
      this.$emit('submit', e, { transExit: true });
    },
  },
  watch: {
    inputData: {
      handler: function (val) {
        let organization = val.organization;

        if (val.isEditProcess) {
          organization = val.organization;
          this.region = organization.region;
          if (!this.region) {
            graphApi
              .flatten('Organization', 'outgoing', [organization.id], 1000, [
                'Region,Organization',
              ])
              .then(({ data }) => {
                if (Array.isArray(data) && data.length > 0) {
                  const regionObject = data.find(
                    (item) => get(item, 'schema') === 'Region'
                  );

                  this.region = get(regionObject, 'id');
                }
              })
              .catch(() => {
                throw new Error(
                  '[components][forms][OrganizationsFormBasic][graphApi]'
                );
              });
          }
        }
        if (organization) {
          if (organization.govRegistrationDate) {
            this.govRegistrationDate = convertDateFormat(
              organization.govRegistrationDate,
              DateFormat.dashedDate,
              this.dateMask
            );
          }

          if (organization.certificate) {
            this.existedCertificate = true;
          }

          this.certificate = organization.certificate || '';
          this.aliasKey = organization.aliasKey || '';
          this.passKey = organization.passKey || '';
          this.enabled = organization.enabled;
          this.id = organization.id || v4();
          this.email = organization.email || '';
          this.fullname = organization.fullname || '';
          this.inn = organization.inn || '';
          this.kpp = organization.kpp || '';
          this.ogrn = organization.ogrn || '';
          this.oktmo = organization.oktmo || '';
          this.phone = organization.phone || '';
          this.reportsEnabled = organization.reportsEnabled;
          this.shortname = organization.shortname || '';
          this.militaryCode = organization.militaryCode || '';
          this.timezone = organization.timezone || '';
          this.address = organization.address || '';
          this.addressId = organization.addressId || '';
          this.postalAddressId = organization.postalAddressId || '';
          this.postalAddress = organization.postalAddress || '';
          this.dns = organization.dns || '';
          this.leg = organization.leg || '';
          this.parentLabel = get(val, 'parentLabel') || '';
          this.parentOrganizationSelected =
            organization?.parent?.schema !== 'Region'
              ? organization.parent
              : null;
          this.regionLabelReadonly = get(val, 'regionLabel') || '';
          this.tnsDepartmentId = organization.tnsDepartmentId || '';
          this.govOrganizationType = organization.govOrganizationType || '';
          // }
        }
      },
      immediate: true,
    },
  },
};
</script>
