<template>
  <q-card class="full-width no-shadow" style="max-width: 800px">
    <q-form @submit="handleSave">
      <q-card-section>
        <div class="text-h6">
          Маппинг межведов
        </div>
        <div class="row q-mt-md">
          <q-input
            class="col-8"
            v-model="outerStatementId" 
            :loading="loading" 
            filled 
            dense 
            placeholder="Введите id заявления донора"
          >
            <template v-slot:append>
              <q-icon name="check" color="positive" v-if="isOuterStatement" />
              <q-icon name="error" color="negative" v-if="outerStatementError" />
            </template>
        </q-input>
        </div>
      </q-card-section>
      <q-card-section>
        <table class="q-table--horizontal-separator q-table">
          <thead>
            <tr>
              <th class="text-left">
                Код
              </th>
              <th class="text-left">
                Значение
              </th>
              <th class="text-left" />
            </tr>
          </thead>

          <tbody>
            <tr class="q-tr" v-for="item in items" :key="item.id">
              <td class="q-td vertical-top">
                <q-input v-model="item.name" filled dense />
              </td>
              <td class="q-td vertical-top">
                <NodeTreeStatement 
                  v-if="isOuterStatement"
                  :statement="outerStatement"
                  @tick="e => setValue(e, item)"
                />
                <q-input v-else ref="parsedInput" v-model="item.value" filled dense />
              </td>
              <td class="q-td text-right vertical-top">
                <q-btn
                  type="button"
                  color="red"
                  :label="$t('registries.objectCard.delete')"
                  @click="removeItem(item.id)"
                />
              </td>
            </tr>
          </tbody>
        </table>
      </q-card-section>

      <q-card-actions align="right">
        <q-btn
          type="button"
          color="primary"
          :label="$t('registries.objectCard.cancel')"
          @click="handleClose"
        />

        <q-btn
          type="button"
          icon="add"
          color="primary"
          :label="$t('registries.table.addRow')"
          @click="pushItem"
        />

        <q-btn
          type="submit"
          icon="create"
          :loading="saving"
          :label="$t('registries.objectCard.save')"
          color="primary"
        >
          <template #loading>
            <q-spinner-gears />
          </template>
        </q-btn>
      </q-card-actions>
    </q-form>
  </q-card>
</template>

<script lang="ts">
import { Component, Vue, Watch, Prop } from 'vue-property-decorator';
import { v4 as getUUID } from 'uuid';
import cloneDeep from 'lodash/cloneDeep';
import { DocumentApi } from '@openapi/document-registry';
import NodeTreeStatement from './NodeTreeStatement.vue'
import isEmpty from 'lodash/isEmpty';
import { notifyError } from '@/utils/notify';
const documentApi = new DocumentApi();

@Component({
  components: {
    NodeTreeStatement
  },
})
export default class MappingDialog extends Vue {
  @Prop({ required: true }) addMapping: MappingTableColumn[];

  dialogOpen = false;
  saving = false;
  outerStatementId = '';
  outerStatementError = false;
  outerStatement: {} = {};
  
  loading = false;
  items: MappingTableColumn[] = [];

  mounted() {
    this.items = cloneDeep(this.addMapping);
    this.pushItem();
  }

  get isOuterStatement(){
    return !isEmpty(this.outerStatement);
  }

  @Watch('outerStatementId', { immediate: true })
  setOuterStatementId() {
    this.outerStatementError = false;
    this.outerStatement = {};
    if (this.outerStatementId.trim().length === 36) {
      this.loading = true;
      documentApi
        .getDocument('Applications', this.outerStatementId, 'applicant, delegate, interDepartmentReq, payments, relatives')
        .then(({ data: statement }) => {
          this.outerStatement = statement;
          this.loading = false;
        })
        .catch(() => {
          this.outerStatementError = true;
          notifyError('Заявление не найдено');
        })
        .finally(() => this.loading = false)
    }
  }

  @Watch('items', { deep: true })
  setEmptyItem() {
    const isEmptyRows = this.items.findIndex(item => !item.name || !item.value);
    if (isEmptyRows === -1) {
      this.pushItem();
    }
  }

  pushItem() {
    this.items.push({
      id: getUUID(),
      name: '',
      value: '',
    });
  }

  removeItem(id: string) {
    this.items = this.items.filter((item) => item.id !== id);
  }
  setValue(val: string, item: MappingTableColumn) {
    const currentItemIndex = this.items.findIndex(el => el.id === item.id);
    this.items[currentItemIndex].value = val;
  }

  handleSave(): void {
    const noEmptyItems = this.items.filter((item) => item.name && item.value);

    this.$q
      .dialog({
        title: this.$t('registries.objectCard.save') as string,
        message: this.$t('registries.objectCard.saveInfo') as string,
        cancel: true,
      })
      .onOk(() => {
        this.$emit('mapping', noEmptyItems);
        this.handleClose();
      })
  }

  handleClose() {
    this.$emit('hideMapping', this.items);
  }
}

export interface MappingTableColumn {
  id: string;
  name: string;
  value: string;
}

</script>
