<template>
  <div v-if="common.active === 'data'" class="q-pb-md">
    <q-card class="no-shadow q-mx-md q-pa-md no-border-radius">
      <div class="flex justify-end">
        <q-btn
          v-if="isRefugeeRegistry"
          class="q-mr-md"
          color="primary"
          icon="edit"
          style="height: 36px;"
          @click="() => editStatusModal = !editStatusModal"
        >
          <q-tooltip :delay="500">Редактировать статус выплаты</q-tooltip>
        </q-btn>
        <q-btn
          v-else-if="!revisionNumber && !isChildrensRestCashback && isAllowedToBeEdited(registryCode)"
          :color="editMode ? 'primary' : 'white'"
          :text-color="editMode ? 'white' : 'primary'"
          :outline="!editMode"
          icon="edit"
          class="q-mb-md"
          @click="editMode = !editMode"
        >
          <q-tooltip :delay="500">Редактировать</q-tooltip>
        </q-btn>
      </div>
      <FormGeneratorWrapper
        v-if="model && model.document && schema"
        :model="formModel"
        :hide-nulls="mode === 'preview'"
        :schema="schema"
        :padded-groups="true"
        :mode="mode"
        @update="updateModel"
      />
      <div v-else class="flex justify-center">
        <p>{{ $t('registries.objectCard.noData') }}</p>
      </div>
    </q-card>
    <q-dialog
      v-model="editStatusModal"
    >
      <RefugeeEditStatusModal 
        :model="model"
        :common="common"
        @close="editStatusModal = false"
      />
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import FormGeneratorWrapper from '@components/common/node-generator/FormGeneratorWrapper.vue';
import { Model, Schema } from '@devsun/eva-models';
import cloneDeep from 'lodash/cloneDeep';
import createView from '@utils/registry-view-generator';
import { MetaClassSchemaRaw } from '@devsun/eva-models/dist/models/Schema';
import { DocumentApi, Registry } from '@openapi/registry-service';
import { CardNeedToUpdateType } from '@constants/models/Card';
import { BaseCardCommon } from '@/interfaces';
import get from 'lodash/get';
import RefugeeEditStatusModal from './RefugeeEditStatusModal.vue'

const CHILDRENS_REST_CASHBACK_CODE = 'RegistryKompensDetskOtdMIR';
const documentApi = new DocumentApi();
const REFUGEE_REGISTRY_CODE = 'registryRefugeeRegistry';

function isAllowedToBeEdited(registryCode: string) {
  const allowedCodes = [
    // REFUGEE_REGISTRY_CODE, // - Этот код здесь ни на что не влияет, при нём работает свой режим редактирования
    // CHILDRENS_REST_CASHBACK_CODE, // - Этот код тоже не влияет так как проверяется ранее, решил не трогать связанную с ним логику
    "registryUcrainianRefugeeAccept",
    "RegistryAccreditation",
  ];
  return allowedCodes.indexOf(registryCode) > -1;
}

@Component({
  components: {
    FormGeneratorWrapper,
    RefugeeEditStatusModal,
  },
  methods: {
    isAllowedToBeEdited,
  },  
})
export default class RegistryData extends Vue {
  @Prop() model: Model.Base;
  @Prop() common: BaseCardCommon;

  formModel: Model.Base;
  registryId = this.$route.query.regid;
  registryCode: string = (this.$route.query.reg as string) ?? '';
  schema: Schema.MetaClassSchemaRaw | null = null;
  editMode = false;
  isChildrensRestCashback = false;
  editStatusModal = false;

  @Watch('model')
  modelWatcher(val: any) {
    if (
      (val && !this.formModel) ||
      (val && this.common.needToUpdate === CardNeedToUpdateType.MODEL)
    ) {
      this.formModel = cloneDeep(val);
      this.isChildrensRestCashback =
        this.formModel?.schema === CHILDRENS_REST_CASHBACK_CODE;
      this.editMode = false;
      if (val && this.common.needToUpdate === CardNeedToUpdateType.MODEL) {
        this.$store.commit(
          'utils/cards/needToUpdate',
          CardNeedToUpdateType.FALSE
        );
      }
    }
  }

  @Watch('registry')
  async registryWatcher(registry: Registry) {
    if (!this.schema) {
      const isCustomForm = get(registry, 'isCustomForm', true);
      // @ts-ignore todo registry.form OPENAPI
      if (isCustomForm && registry?.form) {
        // @ts-ignore todo registry.form OPENAPI
        this.schema = cloneDeep(registry.form);
      } else {
        const docCode = get(this, 'formModel.document.type.code');
        const serviceId = get(this, 'formModel.applicationSystem.serviceId');
        const goal = get(this, 'formModel.Goal');

        if (!docCode) {
          return;
        }

        const service = await this.$store.dispatch(
          'registryService/services/getServiceMeta',
          { id: serviceId }
        );

        const responseDocs = await documentApi
          .searchDocuments(
            'ServiceDocument',
            `code==${docCode}`,
            undefined,
            undefined,
            'form'
          )
          .then(({ data }) => data || []);

        const formCode = (service?.stages || [])
          .flatMap((st: any) => [
            ...(st?.documents?.apply || []),
            ...(st?.documents?.reject || []),
          ])
          .filter((doc: any) => doc.code && doc.form && doc.goal)
          .find((doc: any) => doc.goal.includes(goal) && doc.code === docCode)
          ?.form;

        if (formCode) {
          responseDocs.forEach((doc: any) => {
            doc.form = (doc.form || []).filter(
              (form: any) => form.name === formCode
            );
          });
        }

        this.schema = createView(responseDocs) as MetaClassSchemaRaw;
      }
    }
  }

  @Watch('mode')
  modeWatcher() {
    const schema = { ...this.schema };
    this.schema = null;
    this.$nextTick(() => {
      this.schema = schema as Schema.MetaClassSchemaRaw;
    });
  }

  get registry(): Registry {
    const models = this.$store.getters[`utils/cards/models`] || {};
    return models[this.registryCode];
  }

  get revisionNumber() {
    return this.$route.query.num;
  }

  get mode() {
    return this.revisionNumber || !this.editMode ? 'preview' : 'edit';
  }

  get isRefugeeRegistry() {
    return this.registry?.code === REFUGEE_REGISTRY_CODE;
  }

  updateModel(model: Model.Base) {
    //  to update the current version
    if (this.common.needToUpdate === CardNeedToUpdateType.FALSE) {
      this.$store.commit(`utils/cards/addModel`, {
        model,
        path: 'registry-object',
      });
    }
  }
}
</script>
