<template>
  <section>
    <div
      class="flex justify-start items-center bg-white q-pa-md q-mt-md q-mx-md rounded-borders"
    >
      <q-btn
        padding="xs"
        class="text-grey-7 q-mr-md"
        color="grey-3"
        icon="arrow_back"
        @click="$router.push({ name: 'personalAccounts' })"
      />
      <span class="text-h5">Создание личного дела</span>
    </div>
    <div class="q-gutter-y-sm bg-white q-pa-md q-mt-md q-mx-md rounded-borders">
      <div class="col text-primary q-pa-sm">
        <div class="q-gutter-y-md">
          <q-card class="no-border no-shadow">
            <template>
              <FormGeneratorWrapper
                ref="formGeneratorWrapper"
                mode="create"
                @update-validation="isFormValid = $event"
                :schema="mainSchema || {}"
                :model="formModel"
              />
            </template>
            <q-btn
              class="q-mt-sm"
              color="primary"
              label="Поиск"
              @click="doSearch"
            ></q-btn>
          </q-card>
        </div>
      </div>
    </div>
    <div
      class="bg-white q-pa-lg q-mx-md rounded-borders"
      v-if="searchResults && searchResults.length"
    >
      <span class="text-h6 text-grey-8">Найденные активные личные дела</span>
      <div
        class="lightgray q-px-md q-py-sm row q-mt-md"
        v-for="person in searchResults"
        :key="person.id"
      >
        <span class="q-my-auto" :key="person.id">
          <span class="text-weight-bold">{{ person.fullName }}</span>
          <span class="q-ml-lg">Дата рождения: {{ person.birthday }}</span>
          <span class="q-ml-lg">Снилс: {{ person.snils }}</span>
          <span class="q-ml-lg">ИНН: {{ person.inn }}</span>
        </span>
        <q-btn
          class="q-ml-auto"
          color="primary"
          label="Выбрать"
          @click="goRoute(person)"
        ></q-btn>
      </div>
    </div>
    <div
      class="bg-white q-pa-lg q-mx-md rounded-borders"
      v-if="searchResultsHiden && searchResultsHiden.length"
    >
      <span class="text-h6 text-grey-8">Найденные удаленные личные дела</span>
      <div
        class="lightgray q-px-md q-py-sm row q-mt-md"
        v-for="person in searchResultsHiden"
        :key="person.id"
      >
        <span class="q-my-auto" :key="person.id">
          <span class="text-weight-bold">{{ person.fullName }}</span>
          <span class="q-ml-lg">Дата рождения: {{ person.birthday }}</span>
          <span class="q-ml-lg">Снилс: {{ person.snils }}</span>
          <span class="q-ml-lg">ИНН: {{ person.inn }}</span>
        </span>
        <q-btn
          class="q-ml-auto"
          color="primary"
          label="Восстановить"
          @click="restore(person)"
        ></q-btn>
      </div>
    </div>
  </section>
</template>

<script lang="ts">
import { Component } from 'vue-property-decorator';
import Vue from 'vue';
import FormGeneratorWrapper from '@/components/common/node-generator/FormGeneratorWrapper.vue';
import {
  Person,
  PersonalAccountApi,
  SearchDataHiddenEnum,
} from '@/openapi/personal-accounts';
import { notifyError } from '@/utils/notify';
import axios from 'axios';
import { pushRoute } from '@/utils/routes';

const personalAccountApi = new PersonalAccountApi();

interface GroupListI {
  name: string;
  num: number;
  hideLabel: boolean;
  attrList: string[];
}

interface AttrListI {
  name: string;
  label: string;
  type: string;
  view: string;
  hidden: boolean;
  readonly: boolean;
}

type SchemaT = {
  id: string;
  modified: string;
  schema: 'Form';
  name: string;
  groupList: GroupListI[];
  attrList: AttrListI[];
};

@Component({
  components: {
    FormGeneratorWrapper,
  },
})
export default class PersonalAccounts extends Vue {
  $refs: {
    formGeneratorWrapper: any;
  };

  mainSchema: SchemaT | null = null;

  formModel = {
    firstName: '',
    lastName: '',
    middleName: '',
    snils: '',
  };

  isFormValid = false;

  searchResults: Person[] = [];
  searchResultsHiden: Person[] = [];

  goRoute(person: Person): void {
    if (!person.id) throw new Error('Карточка не содержит ID');
    pushRoute(this.$router, {
      name: 'cards',
      params: {
        id: person.id,
        path: `personal-accounts`,
      },
      query: {
        components: this.$store.getters[
          'cardComponents/personalAccounts/components'
        ],
        active: 'personal',
      },
    });
  }

  async mounted(): Promise<void> {
    this.mainSchema = await this.fetchScheme();
  }

  async fetchScheme(): Promise<SchemaT> {
    const mainSchema = import('@/constants/forms/PersonalAccountAdd.json').then(
      (it) => it.default
    ) as Promise<SchemaT>;
    return await mainSchema;
  }

  async doSearch(): Promise<void> {
    this.$refs.formGeneratorWrapper.triggerValidate();

    if (!this.isFormValid) {
      return;
    }

    try {
      const {
        data: { records: persons },
      } = await personalAccountApi.fullSearchPerson({
        searchData: {
          snils: this.formModel.snils.replace(/[^0-9]/g, ''),
          hidden: SearchDataHiddenEnum.All,
        },
      });
      this.searchResults = [];
      this.searchResultsHiden = [];

      if (!persons.length) {
        this.$router.push({
          name: 'personalAccountsCreate',
          query: this.formModel,
        });
      } else {
        persons.forEach((person) => {
          if (!person.personHidden) {
            this.searchResults.push(person);
          } else {
            this.searchResultsHiden.push(person);
          }
        });
      }
    } catch (error) {
      if (axios.isAxiosError(error)) notifyError(error.message);
    }
  }

  async restore(person: Person): Promise<void> {
    if (!person.id) throw new Error('Карточка не содержит ID');
    try {
      const { data } = await personalAccountApi.restorePerson(person.id, {});
      this.goRoute(data);
    } catch (e) {
      if (e instanceof Error) notifyError(e.message);
    }
  }
}
</script>

<style>
.lightgray {
  background-color: rgba(0, 0, 0, 0.05);
}
</style>
