<i18n>
{
    "en": {
        "MezhvedsCard": {
            "tab": "Interagency requests",
            "mezhvedStatus": "Status",
            "mezhvedRequestData": "Data",
            "mezhvedName": "Name details",
            "mezhvedRequest": "Request",
            "mezhvedDateRequest": "Date of request",
            "mezhvedDateReply": "Date of answer",
            "noChecksResult": "No results for request"
        }
    },
    "ru": {
        "MezhvedsCard": {
            "tab": "Межведомственные запросы",
            "mezhvedStatus": "Статус",
            "mezhvedRequestData": "Данные",
            "mezhvedName": "Наименование сведений",
            "mezhvedRequest": "Запрос",
            "mezhvedDateRequest": "Дата запроса",
            "mezhvedDateReply": "Дата ответа",
            "noChecksResult": "Нет результатов по запросам"
        }
    }
}
</i18n>
<template>
  <div class="q-gutter-y-md">
    <div v-if="!this.model" class="full-width text-center">
      <q-spinner-gears color="primary" size="50px" />
    </div>

    <ExpandingTable
      v-else-if="modelCast.mezhveds && !!modelCast.mezhveds.length"
      :data="modelCast.mezhveds"
      :columns="mezhvedsColumns"
      :source="source"
    />
    <div v-else class="full-width text-center">
      {{ $t('MezhvedsCard.noChecksResult') }}
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import ExpandingTable from '@components/statements/components/cross-expanding-table.vue';
import { BaseCardCommon } from '@/interfaces';
import QColumn from '@/types/QColumn';
import get from 'lodash/get';
import { STATUSES } from '@/constants/InterRequestStatuses';

@Component({
  components: {
    ExpandingTable,
  },
  methods: {
    get,
  },
})
export default class InterDepartmentReqTable extends Vue {
  @Prop() common: BaseCardCommon;
  @Prop() model: any;
  @Prop({ default: 'interDepartmentReq' }) source!: string;

  private get icons() {
    Object.keys(STATUSES).forEach((keyStatus: string) => {
      STATUSES[keyStatus].tooltip = this.$t(`mzStatus.${keyStatus}`).toString();
    });

    const data = {
      icons: STATUSES,
    };
    Object.assign(data.icons, {
      done: data.icons.ok,
      failed: data.icons.error,
      request: data.icons.pending,
      draft: data.icons.draft,
    });
    return data.icons;
  }

  private get modelCast() {
    if (!this.model)
      return {
        mezhveds: [],
      };

    const mzLinks: Record<string, any> = {};

    const mvz = (this.model[this.source] || []).reduce((o: any, item: any) => {
      // if(!o[item.name]) o[item.name] = Object.create(null);
      const obj = Object.create(null);
      const subName = (item.description as string) || 'Все';
      const name = item.requestName as string;
      // if(!o[item.name][subName]) o[item.name][subName] = [];
      obj.name = name;
      obj.subname = Object.create(null);
      obj.subname.name = subName;
      obj.subname.items = [];
      obj.subname.items.push(item);
      const mzObject = mzLinks[`${name}-${subName}`]; // тут хранится ссылка на объект межведа

      if (mzObject) {
        // если ссылка на межвед есть, то считаем, что этот тип уже есть и доплняем только items
        mzObject.subname.items.push(item);
      } else {
        mzLinks[`${name}-${subName}`] = obj;
        o.push(obj);
      }
      return o;
    }, []);

    const rows = [];
    for (let i = 0; i < mvz.length; i++) {
      const sub = [];
      let status = 'ok';

      const list = mvz[i].subname.items;
      if (!list.length) continue;

      const parent : {
        name: string,
        key: string,
        expand: boolean,
        children: null | Array<any>
      } = {
        name: mvz[i].subname.name,
        key: mvz[i].subname.name,
        expand: true,
        children: null,
      };

      parent.children = list.reduce((acc: any, item: any) => {
        status = item.status || 'pending';

        const row = Object.assign({}, item, {
          name:
            item.fio &&
            item.fio.replace(/\(.*?\)/g, (e: string) =>
              e.replace(/\s+/g, '\u00A0')
            ),
          status: this.icons[String(status)] || this.icons.pending,
          subject: item.subject,
        });
        this.mezhvedsColumns.forEach(({ name, format }) => {
          if (format && name && name in row) {
            row[name] = format(row[name]);
          }
        });

        const showDraft =
          item.status === 'draft' &&
          list.every((listItem: any) => {
            const itemId = get(item, 'id');
            const listItemId = get(listItem, 'id');

            // same mz
            if (itemId === listItemId) return true;
            if (listItem.status === 'draft') return true;

            const listItemObjCode = get(listItem, 'subject');
            const itemObjCode = get(item, 'subject');

            return listItemObjCode !== itemObjCode;
          });

        if (showDraft) {
          acc.push(row);
        } else if (item.status !== 'draft') {
          acc.push(row);
        }
        return acc;
      }, []);

      sub.push(parent);
      rows.push({
        name: mvz[i].name || '',
        key: `${mvz[i].name}${i}`,
        outdated: mvz[i].outdated || false,
        children: sub,
      });
    }
    return Object.assign({}, this.model, {
      mezhveds: rows.sort((a: any, b: any) => a.name.localeCompare(b.name)),
    });
  }

  private get mezhvedsColumns(): Array<QColumn> {
    return [
      {
        align: 'left',
        field: 'expand',
        label: '',
        name: 'expand',
        sortable: false,
      },
      {
        align: 'left',
        field: 'name',
        label: this.$t('MezhvedsCard.mezhvedName'),
        name: 'name',
        style: 'padding-left: 0',
        headerStyle: 'padding-left: 0',
        sortable: true,
      },
      {
        align: 'center',
        field: 'status',
        label: this.$t('MezhvedsCard.mezhvedStatus'),
        name: 'status',
        sortable: false,
      },
      {
        align: 'center',
        field: 'request',
        label: this.$t('MezhvedsCard.mezhvedRequestData'),
        name: 'request',
        sortable: false,
      },
      {
        align: 'center',
        field: 'sendDate',
        label: this.$t('MezhvedsCard.mezhvedDateRequest'),
        name: 'sendDate',
        sortable: true,
      },
      {
        align: 'center',
        field: 'receiveDate',
        label: this.$t('MezhvedsCard.mezhvedDateReply'),
        name: 'receiveDate',
        sortable: false,
      },
    ];
  }
}
</script>