<i18n>
{
  "en": {
    "edit": "Edit",
    "save": "Save",
    "saveSuccess": "Income form completed successfully",
    "saveError": "Failed to complete income form"
  },
  "ru": {
    "edit": "Редактировать",
    "save": "Сохранить",
    "saveSuccess": "Форма доходов заполнена успешно",
    "saveError": "Не получилось заполнить форму доходов"
  }
}
</i18n>

<template>
  <div>
    <div class="q-gutter-x-xs">
      <q-btn
        :color="editMode ? 'primary' : 'white'"
        :text-color="editMode ? 'white' : 'primary'"
        :outline="!editMode"
        icon="edit"
        @click="editMode = !editMode"
      >
        <q-tooltip :delay="500">{{ $t('edit') }}</q-tooltip>
      </q-btn>
      <q-btn
        v-if="!isEqual"
        :color="'primary'"
        :text-color="'white'"
        :outline="false"
        icon="save"
        @click="updateStatement"
      >
        <q-tooltip :delay="500">{{ $t('save') }}</q-tooltip>
      </q-btn>
    </div>
    <div>
      <FormGeneratorWrapper
        v-if="formModel"
        :key="formGeneratorWrapperKey"
        :model="formModel"
        :schema="incomeFormSchema"
        :mode="mode"
        :padded-groups="true"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import { Model } from '@devsun/eva-models';
import cloneDeep from 'lodash/cloneDeep';
import isEqual from 'lodash/isEqual';
import FormGeneratorWrapper from '@components/common/node-generator/FormGeneratorWrapper.vue';
import { notifyError, notifySuccess } from '@utils/notify';

@Component({
  components: {
    FormGeneratorWrapper
  }
})
export default class IncomeFormDataEditor extends Vue {
  @Prop({}) private service: any;
  @Prop({}) model: Model.Base;

  editMode = false;
  formModel: Model.Base | null = null;
  formGeneratorWrapperKey = 0;

  @Watch('model', { immediate: true })
  modelWatcher(val: any) {
    if (val && !this.formModel) {
      this.formModel = cloneDeep(val.statement);
    }
  }

  get mode() {
    this.formGeneratorWrapperKey++;
    return this.editMode ? 'edit' : 'preview';
  }

  get incomeFormSchema() {
    return this.service.formsExtra.find((f: any) => f.name === 'Income');
  }

  get isEqual() {
    return isEqual(this.model?.statement, this.formModel);
  }

  async updateStatement() {
    try {
      const applicationId = this.model.id;

      if (applicationId) {
        const response = await this.$store.dispatch('wf/processes/dispatchProcess', {
          processKey: 'IncomeApplicationUpdate',
          data: {
            applicationId,
            fields: { statement: this.formModel },
          },
        });
        if (response?.code === '200') {
          notifySuccess(this.$tc('saveSuccess'));
        }
      }
    } catch (err) {
      console.error({ err });
      notifyError(this.$tc('saveError'))
    }
  }
}
</script>