<template>
  <div v-if="isActive" class="q-pb-md">
    <q-card class="no-shadow q-gutter-y-md q-mx-md no-border-radius">
      <div class="q-mx-md q-pt-md q-pa-sm">
        <div class="q-gutter-y-md q-mb-md">
          <FormGeneratorWrapper
            :model="formModel"
            :schema="schema"
            :hide-nulls="true"
            :padded-groups="true"
            class="q-mt-none"
          />
        </div>
      </div>
    </q-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import { Component, Watch, Prop } from 'vue-property-decorator';
import { BaseCardCommon } from '@/interfaces';
import { Person } from '@openapi/personal-accounts';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import cloneDeep from 'lodash/cloneDeep';
import type { Schema } from '@devsun/eva-models';
import FormGeneratorWrapper from '@/components/common/node-generator/FormGeneratorWrapper.vue';

const PERSONAL_ACCOUNT_PERSON = '05ce6b67-86f3-4cb1-9e75-044a645004c8';

@Component({
  components: {
    FormGeneratorWrapper,
  },
  methods: {
    get,
  },
})
export default class PersonalInformation extends Vue {
  @Prop({}) private common?: BaseCardCommon;
  @Prop({}) private model?: Person;

  get isActive(): boolean {
    return this.common?.active === 'personal';
  }

  loading = false;

  @Watch('model', { immediate: true })
  onModelChange(model: Person): void {
    this.setFormModel(model);
  }

  formModel: Partial<Person> = {};

  async setFormModel(model: Person): Promise<void> {
    if (!model) {
      this.formModel = {};
    }
    await this.getSchema();
    this.formModel = cloneDeep(model);
  }

  schema: Partial<Schema.MetaClassSchemaRaw> = {};

  async getSchema(): Promise<void> {
    try {
      let schema = this.$store.getters['utils/cards/getSchemaByPath'](
        'personalAccountPerson'
      );

      if (isEmpty(schema)) {
        schema = await this.$store.dispatch(
          'personalAccounts/forms/loadSchema',
          'PersonalAccountDetailsDisplay'
        );

        this.$store.commit('utils/cards/addSchema', {
          schema,
          path: 'personalAccountPerson',
        });
      }
      this.schema = cloneDeep(schema || {});
    } catch (e) {
      console.warn(
        `[perconal-accounts/personal] Couldn't get schema ${PERSONAL_ACCOUNT_PERSON} `
      );
    }
  }
}
</script>
