<template>
  <q-card class="no-shadow q-pa-xs">
    <q-card-section>
      <span class="text-h6">
        Редактирование статуса выплаты
      </span>
    </q-card-section>

    <q-card-section>
      <base-label-value padded-label class="items-center">
        <template v-slot:label>
          Статус выплаты
        </template>
        <template v-slot:value>
          <q-select :options="options" v-model="status" 
            map-options emit-value option-value="label"
          />
        </template>
      </base-label-value>
    </q-card-section>
    <q-card-section>
      <arm-datepicker v-model="paymentDate" :value="paymentDate" 
        format="DD.MM.YYYY" type="date" label="Дата выплаты"
        :validation-error="hasError"
       />
    </q-card-section>

    <q-card-section>
      <q-input
        v-model="comment"
        label="Комментарий"
        filled
        type="textarea"
      />
    </q-card-section>

    <q-card-actions align="right">
      <q-btn flat @click="$emit('close')" label="Отмена"
       color="red" />
      <q-btn :disabled="hasError" flat @click="onSaveClick" label="Сохранить"
       color="primary" />
    </q-card-actions>
  </q-card>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { Model } from '@devsun/eva-models';
import { BaseCardCommon } from '@/interfaces';
import uniq from 'lodash/uniq';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import has from 'lodash/has';
import cloneDeep from 'lodash/cloneDeep';
import ArmDatepicker from '@components/common/node-generator/components-lib/datepicker/arm-datepicker.vue';
import { DocumentApi } from '@openapi/registry-data';
import { notifyError } from '@utils/notify';
import { CardNeedToUpdateType } from '@constants/models/Card';

export type ReferenceBooksItemOption = ReferenceBooksItemSingleOption &
  ReferenceBooksItemMultipleOption;

export interface ReferenceBooksItemSingleOption {
  label: string;
  value?: string;
}

export interface ReferenceBooksItemMultipleOption {
  label: string;
  children?: ReferenceBooksItemOption[];
}

@Component({
  components: {
    ArmDatepicker
  },
})
export default class RefugeeEditStatusModal extends Vue {
  @Prop() model: Model.Base;
  @Prop() common: BaseCardCommon;
  @Prop({ default: 'value' }) name!: string;
  @Prop({ default: false }) nested!: boolean;
  @Prop() selectedGroupIndex!: number; // using only for "nested" case

  status = '';
  paymentDate = '';
  objModel: any = {}; // todo type RegistryRecord
  comment = '';
  loading = false;

  @Watch('model', { deep: true, immediate: true })
  modelWatcher(val: any) {
    const { paymentStatus, paymentComment, paymentDate } = val.statement;
    this.status = paymentStatus;
    this.comment = paymentComment;
    this.paymentDate = paymentDate;
  }

  get referenceBook() {
    return this.$store.getters['registryService/referenceBooks/referenceBooks'][
      'RefugeePayment_1_0_1_paymentStatus'
    ];
  }

  get options() {
    if (isEmpty(this.referenceBook)) {
      return [{"label":"Запись сформирована","value":"Запись сформирована"},{"label":"Сформирован реестр на выплату","value":"Сформирован реестр на выплату"},{"label":"Выплата произведена","value":"Выплата произведена"},{"label":"Отказ кредитной организации","value":"Отказ кредитной организации"}];
    }

    const GROUPS: string[] = uniq([
      ...Object.values(this.referenceBook)
        .map((value: any) => Object.keys(value))
        .flat(1),
    ]);

    let options: ReferenceBooksItemOption[];

    if (GROUPS.length > 1 && this.nested) {
      options = GROUPS.map((group) => {
        const groupChildren: ReferenceBooksItemOption[] = [];

        Object.entries(this.referenceBook).forEach(([key, value]: any[]) => {
          if (value[group]) {
            groupChildren.push({
              label: value[group],
              value: key,
            });
          }
        });

        return {
          label: group,
          children: groupChildren,
        };
      });

      if (
        this.selectedGroupIndex !== null &&
        has(options, [this.selectedGroupIndex, 'children'])
      ) {
        options = options[this.selectedGroupIndex]
          .children as ReferenceBooksItemOption[];
      }
    } else {
      options = Object.entries(this.referenceBook).map(
        ([key, value]: any[]) => ({
          label: value[this.name],
          value: key,
        })
      );
    }

    return options;
  }

  get hasError() {
    return !this.paymentDate && this.status === 'Выплата произведена';
  }

  async onSaveClick() {
    try {
      const { traceId } = await this.$store.dispatch('wf/processes/dispatchProcess', {
        "processKey": "RefugeeRegistryUpdate", 
        "syncMode": false, 
        "utStepMode": false, 
        "userId": "83fb7e0a-5d86-40a7-81fa-542cc43d2959", 
        "data": { 
          "recordId": this.model.id,
          "status": this.status,
          "paymentDate": this.paymentDate,
          "paymentComment": this.comment
        } 
      });
      if (traceId) {
        const handler = (e: any) => {
          const data = JSON.parse(get(e, 'data', '{}'));
          if (data.traceId === traceId) {
            const model = cloneDeep(!isEmpty(this.objModel) ? this.objModel : this.model);
            model.statement.paymentStatus = this.status;
            model.statement.paymentDate = this.paymentDate;
            model.statement.paymentComment = this.comment;
            
            this.objModel = model;
            this.$store.commit(`utils/cards/addModel`, {
              model,
              path: 'registry-object',
            });
            this.$store.commit(
              'utils/cards/needToUpdate',
              CardNeedToUpdateType.MODEL
            );
            this.$store.commit(`utils/cards/addModel`, {
              model: true,
              path: 'registryRefugeeRegistry.paymentStatusSaved',
            });
            this.$emit('close');

            this.$websockets.removeListener(handler);
          }
        };
        this.$websockets.addListener(handler);
      }
    }
    catch (e) {
      notifyError(e.message.toString());
    }
  }

}
</script>