<i18n>
{
  "en": {
    "StatementCard": {
      "errorLoadingModel": "failed to load model",
      "infoMessage": {
        "accreditationIT": "Application information can be found on «Applicant» tab."
      }
    }
  },
  "ru": {
    "StatementCard": {
      "errorLoadingModel": "не удалось загрузить модель",
      "infoMessage": {
        "accreditationIT": "Данные по заявлению представлены на вкладке «Заявитель»."
      }
    }
  }
}
</i18n>

<template>
  <div>
    <div class="redesigned-form-generator-container form-data-override">
      <FormGeneratorWrapper
          v-if="ready && !infoMessage"
          :model="formModel"
          :schema="schema"
          :hide-nulls="true"
          :attraction-code="code"
          :padded-groups="true"
          class="form-generator-wrapper"
        />
        <div
          v-if="ready && infoMessage"
          class="text-blue-grey-9 q-py-lg"
          :style="{
            fontSize: '14px',
          }"
        >
          {{ infoMessage }}
        </div>
    </div>

    <q-inner-loading :showing="!ready">
      <q-spinner-gears color="primary" size="50px" />
    </q-inner-loading>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import FormGeneratorWrapper from '@components/common/node-generator/FormGeneratorWrapper.vue';
import cloneDeep from 'lodash/cloneDeep';
import isEmpty from 'lodash/isEmpty';
import get from 'lodash/get';

export default {
  name: 'StatementDataCard',
  components: {
    FormGeneratorWrapper,
  },
  props: ['common', 'model'],
  data() {
    return {
      code: '',
      formModel: {},
      infoMessage: null,
    };
  },

  computed: {
    ready() {
      return !isEmpty(this.formModel) && !isEmpty(this.schema);
    },
    schema() {
      return cloneDeep(
        this.$store.getters['utils/cards/getSchemaByPath']('data')
      );
    },
  },

  watch: {
    model: function (val) {
      if (val) {
        this.setFormModel().then((model) => {
          this.formModel = model;

          const serviceCode = get(this.formModel, 'serviceCode');
          const goal = get(this.formModel, 'statement.goal');

          if (serviceCode === 'accreditationIT' && goal === 1) {
            this.infoMessage = this.$t(
              'StatementCard.infoMessage.accreditationIT'
            );
          } else {
            this.infoMessage = null;
          }
        });
      }
    },
  },

  created() {
    this.$store.commit(`utils/cards/removeSchema`, { path: 'data' });
  },

  methods: {
    setSchemaToStore(schema) {
      this.$store.commit(`utils/cards/addSchema`, {
        schema,
        path: 'data',
      });
    },
    async setSchema() {
      const serviceID = get(this.model, 'system.serviceId');

      if (!serviceID) {
        console.error('[statement data][set schema] No service id, aborting', {
          model: this.model,
          serviceID,
        });

        return;
      }

      let service = this.$store.getters[
        'registryService/services/servicesCard'
      ];

      if (!service.form) {
        service = await this.$store.dispatch(
          'registryService/services/getServiceMeta',
          {
            id: serviceID,
          }
        );
      }

      const form = get(service, 'form');

      if (!form) {
        console.warn('--------------------------');
        console.warn('--------------------------');
        console.warn(
          '[Statement data] No form found in service registry for service:',
          get(service, 'shortName'),
          { service }
        );
        console.warn(
          'You can add a form at this address:',
          `${location.origin}/microws/cards/services/${serviceID}?active=forms&components=index,processes,forms,directories,verifications,documents,interagencies,stages,form_model,digital_regulations`
        );
        console.warn('--------------------------');
        console.warn('--------------------------');

        return;
      }

      this.setSchemaToStore(service.form);
    },
    async setFormModel() {
      if (!this.model) {
        return {};
      }
      if (this.model.serviceCode !== this.code) {
        await this.setSchema();
      }
      return cloneDeep(this.model);
    },
  },
};
</script>

<style lang="scss">
.subgroup-anchor + span {
  font-family: 'Golos UI', sans-serif;
  font-size: 1.5rem;
  margin-bottom: 6px;
}
// Переопределить ширину заголовков данных так как на закладке "Данные заявления"
// наименования полей, чаще, намного длинней чем их значения
.redesigned-form-generator-container.form-data-override {
  .form-generator .form-generator-field div.row > div.col-4.text-grey-9 {
    width: 48%;
  }
  & > div > .form-generator > div > div > .form-generator-field > .subgroup-holder {
    // 2. Второй уровень вложенности форм генератора
    .form-generator-field:has(>div.subgroup-holder>.form-generator-field:not(.q-my-md)) > div:not(.cursor-pointer) {
      &:has(>span.text-subtitle_group), &:has(>span.text-subtitle1) {
        margin-bottom: 4px;
      }
    }
  }
}
</style>