<i18n>
{
  "en": {
    "OrganizationsFormsSearch": {
      "innOrOgrn": "TIN or PSRN",
      "search": "Search",
      "createWithoutSearch": "Create without search",
      "organization": "Organization",
      "choose": "Choose",
      "name": "Name",
      "inn": "TIN",
      "ogrn": "PSRN"
    }
  },
  "ru": {
    "OrganizationsFormsSearch": {
      "innOrOgrn": "ИНН или ОГРН",
      "search": "Поиск",
      "createWithoutSearch": "Создать без поиска",
      "organization": "Организация",
      "choose": "Выбрать",
      "name": "Наименование",
      "inn": "ИНН",
      "ogrn": "ОГРН"
    }
  }
}
</i18n>

<template>
  <q-form @submit="submit">
    <div v-if="readonly" class="q-gutter-y-xs">
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('OrganizationsFormsSearch.innOrOgrn') }}*
        </div>
        <div class="col text-grey-7">{{ search }}</div>
      </div>
    </div>
    <q-input
      v-else
      v-model="search"
      filled
      :label="$t('OrganizationsFormsSearch.innOrOgrn')"
      type="search"
      unmasked-value
      :rules="[innFormatRule]"
    >
      <template #append>
        <q-icon name="search" />
      </template>
    </q-input>
    <div class="q-my-md row q-gutter-y-md">
      <q-btn
        v-if="!readonly"
        color="primary"
        class="col-xs-12 col-sm-auto"
        :label="$t('OrganizationsFormsSearch.search')"
        type="button"
        :disable="disableSearch"
        @click="sendSearch"
      />
      <q-btn
        v-if="!readonly"
        color="grey-5"
        class="col-xs-12 col-sm-auto q-ml-sm-md"
        :label="$t('OrganizationsFormsSearch.createWithoutSearch')"
        type="button"
        @click="createNew"
      />
    </div>
    <q-table
      v-if="this.inputData.searchData && this.inputData.searchData.transSearch"
      :title="$t('OrganizationsFormsSearch.organization')"
      :data="data"
      :columns="columns"
      row-key="id"
      selection="single"
      :selected.sync="selected"
      :hide-bottom="!!data.length"
      :grid="$q.screen.xs"
    >
      <template #header="props">
        <q-tr :props="props">
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            {{ col.label }}
          </q-th>
          <q-th auto-width />
        </q-tr>
      </template>
      <template #body="props">
        <q-tr :props="props">
          <q-td v-for="col in props.cols" :key="col.name" :props="props">
            {{ col.value }}
          </q-td>
          <q-td auto-width>
            <q-icon
              v-if="inputData.exist"
              style="color: #68b857"
              size="sm"
              name="check_circle_outline"
            />
          </q-td>
        </q-tr>
      </template>
      <template #item="props">
        <div class="col-12 q-px-md q-py-xs">
          <q-card
            class="q-table__grid-item col-12 overflow-auto"
            :class="{
              'bg-grey-2': !!props.selected,
              'cursor-pointer': !!rowsHandler,
            }"
            @click="rowsHandlerCast(props.row)"
          >
            <q-card-section v-if="inputData.exist">
              <q-icon
                style="color: #68b857"
                size="sm"
                name="check_circle_outline"
              />
            </q-card-section>
            <q-separator v-if="inputData.exist" />
            <div class="q-table__grid-item-card">
              <div
                v-for="col in props.cols.filter((col) => col.name !== 'desc')"
                :key="col.name"
                class="q-table__grid-item-row"
              >
                <div class="q-table__grid-item-title">
                  {{ col.label }}
                </div>
                <div class="q-table__grid-item-value">
                  {{ col.value }}
                </div>
              </div>
            </div>
          </q-card>
        </div>
      </template>
    </q-table>
  </q-form>
</template>

<script lang="ts">
// @ts-nocheck
import { innFormatRule } from '@utils/field-validation/organizations';

export default {
  props: ['input-data', 'readonly'],
  data() {
    return {
      selected: [],
      data: [],
      search: '',
    };
  },
  computed: {
    disableSearch() {
      const pattern = /^(?!(?:10|12|13|15)$)[0-9]*$/;
      return !this.search.length || pattern.test(String(this.search.length));
    },
    outputData() {
      return {
        search: this.search,
      };
    },
    columns() {
      return [
        {
          name: 'name',
          label: this.$t('OrganizationsFormsSearch.name'),
          align: 'left',
          field: 'name',
        },
        {
          name: 'inn',
          align: 'left',
          label: this.$t('OrganizationsFormsSearch.inn'),
          field: 'inn',
        },
        {
          name: 'ogrn',
          align: 'left',
          label: this.$t('OrganizationsFormsSearch.ogrn'),
          field: 'ogrn',
        },
      ];
    },
  },
  watch: {
    inputData: {
      handler: function (val) {
        const searchValue = val && val.searchData && val.searchData.search;

        if (searchValue) {
          this.search = searchValue;
        }
        if (!this.search && val.search) {
          this.search = val.search;
        }

        // В старой логику в таблицу клали только первый найденный элемент
        // По логике при поиске по inn или ogrn он и должен возвращаться один
        // но на всякий случай реализован функционал, что при возвращении списка
        // в data и selected кладу все найденные организации

        if (val?.organizationData?.length) {
          this.data.splice(0, this.selected.length);

          this.data = val.organizationData.map((organization: any) => {
            return {
              name: organization.fullname || organization.shortname || '',
              inn: organization.inn || '',
              ogrn: organization.ogrn || '',
            };
          });

          this.selected.splice(0, this.selected.length);
          this.selected.push(...this.data);
        }
      },
      immediate: true,
    },
  },
  methods: {
    submit(e) {
      this.$emit('submit', e, this.outputData);
    },
    sendSearch(e) {
      this.$emit('submit', e, {
        ...this.outputData,
        transSearch: true,
        transCreate: false,
      });
    },
    createNew(e) {
      this.$emit('submit', e, {
        ...this.outputData,
        transSearch: false,
        transCreate: true,
      });
    },
    innFormatRule,
  },
};
</script>
