<i18n>
{
  "en": {
    "statements": {
      "CrossUpdatingDialog": {
        "tableTitle": "Information name",
        "redirect": "Submit",
        "name": "Name",
        "subject": "Subject",
        "status": "Status",
        "buttonLabel": "View",
        "reinitialization": "Reinitialize all interdepartmental queries"
      }
    }
  },
  "ru": {
    "statements": {
      "CrossUpdatingDialog": {
        "tableTitle": "Наименование сведений",
        "redirect": "Отправить",
        "name": "Наименование",
        "subject": "Субъект",
        "status": "Статус",
        "buttonLabel": "Просмотр",
        "reinitialization": "Переинициализация всех МВ запросов"
      }
    }
  }
}
</i18n>

<template>
  <div>
    <div
      v-if="$slots.button"
      class="cursor-pointer"
      v-bind="button.props"
      @click="doAction"
    >
      <slot name="button"></slot>
    </div>
    <q-btn
      v-else
      :disable="disableAllButtons || get(buttonSettings, 'props.disable')"
      class="q-ml-sm"
      outline
      :label="get(buttonSettings, 'props.label')"
      :color="get(buttonSettings, 'props.color')"
      v-bind="button.props"
      @click="doAction"
    />
    <q-dialog v-model="value">
      <q-card class="no-shadow" style="max-width: 80vw; width: 1000px">
        <q-card-section>
          <div class="text-h6">
            {{ get(buttonSettings, 'props.label') }}
          </div>
        </q-card-section>
        <q-card-section class="q-p">
          <div class="q-pa-md">
            <q-table
              :title="$t('statements.CrossUpdatingDialog.tableTitle')"
              :data="[...interDepartmentData, ...gpzuDocs]"
              :columns="columns"
              row-key="id"
              :selection="interDepartmentReinitialization ? 'none' : 'multiple'"
              :selected.sync="selected"
            >
              <template v-slot:body-cell-status="props">
                <q-td :props="props">
                  <q-icon
                    :name="statuses[props.value].name"
                    :color="statuses[props.value].color"
                    size="sm"
                  >
                    <q-tooltip>{{ statuses[props.value].tooltip }}</q-tooltip>
                  </q-icon>
                </q-td>
              </template>
            </q-table>
            <div class="flex justify-between flex-wrap">
              <q-btn
                :label="$t('statements.CrossUpdatingDialog.redirect')"
                :disable="buttonDisable"
                unelevated
                color="primary"
                @click="submit"
              />
              <q-checkbox
                :label="$t('statements.CrossUpdatingDialog.reinitialization')"
                :value="interDepartmentReinitialization"
                @input="interDepartmentReinitializationChange"
              />
            </div>
          </div>
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import { STATUSES as statuses } from '@/constants/InterRequestStatuses';
import get from 'lodash/get';
import isArray from 'lodash/isArray';

export default {
  props: ['model', 'disable-all-buttons', 'user-task', 'button-settings'],
  data() {
    return {
      interDepartmentReinitialization: false,
      value: false,
      selected: [],
      savedSelected: [],
      button: {
        props: {
          color: 'primary',
          label: this.$t('statements.CrossUpdatingDialog.buttonLabel'),
          loading: false,
        },
      },
      statuses,
    };
  },

  computed: {
    buttonDisable() {
      return !(this.selected.length || this.interDepartmentReinitialization);
    },
    columns() {
      const cellStyle = 'white-space: pre-wrap; word-break: break-all;';
      const headerStyle = 'font-size: 16px; font-weight: 600;';
      return [
        {
          name: 'name',
          align: 'left',
          label: this.$t('statements.CrossUpdatingDialog.name'),
          field: 'name',
          sortable: true,
          style: cellStyle,
          headerStyle,
        },
        {
          name: 'subject',
          align: 'left',
          label: this.$t('statements.CrossUpdatingDialog.subject'),
          field: 'subject',
          sortable: true,
          style: cellStyle,
          headerStyle,
        },
        {
          name: 'status',
          align: 'left',
          label: this.$t('statements.CrossUpdatingDialog.status'),
          field: 'status',
          sortable: true,
          style: cellStyle,
          headerStyle,
        },
      ];
    },

    interDepartmentData() {
      const interDepartmentReqArray =
        get(this.model, 'interDepartmentReq') || [];

      if (isArray(interDepartmentReqArray)) {
        const departmentReq = interDepartmentReqArray.map((el) => ({
          id: get(el, 'id'),
          name: get(el, 'requestName'),
          subject: get(el, 'subject'),
          status: get(el, 'status'),
        }));

        const statusesSort = ['draft', 'fail', 'skipped'];

        return departmentReq.sort((a) => {
          return statusesSort.includes(a.status) ? -1 : 0;
        });
      }
      return [];
    },

    serviceCard() {
      return this.$store.getters['registryService/services/servicesCard'];
    },

    gpzuDocs() {
      const findInteragencyEgrnByCadNumber = (cadNumber) =>
        this.model.interDepartmentReq.find(
          (i) =>
            i.class === 'egrn' &&
            i.request?.object?.fs3RREGRNRequestObject?.cadastralNumber ===
              cadNumber
        );
      return (
        this.model?.documents
          ?.filter(
            (d) =>
              d?.type?.code === 'DecisionDocumentsBlock' &&
              d.source === 'MVZ' &&
              this.serviceCard.name === 'GPZU' &&
              !findInteragencyEgrnByCadNumber(d.cadastralNumber)
          )
          ?.map((d) => ({
            id: `egrnЗемельный участок  ${d.cadastralNumber}`,
            isGpzuDoc: true,
            contextWithSubjects: `egrnЗемельный участок  ${d.cadastralNumber}`,
            subject: `Земельный участок  ${d.cadastralNumber}`,
            name: 'Прием обращений в ФГИС ЕГРН',
            status: 'draft',
          })) || []
      );
    },
  },

  methods: {
    get,
    interDepartmentReinitializationChange(value: boolean): void {
      this.interDepartmentReinitialization = value;
      if (value) {
        this.savedSelected = this.selected;
        this.selected = [];
      } else {
        this.selected = this.savedSelected;
        this.savedSelected = [];
      }
    },
    doAction() {
      this.value = true;
    },
    submit() {
      if (this.interDepartmentReinitialization) {
        this.$emit('submit', {
          buttonId: 'updateMZ',
          force: true,
        });
        this.value = false;
        return;
      }
      const resendRequestIds = this.selected
        .filter((el) => !el.isGpzuDoc)
        .map((el) => el.id);

      const contextsWithSubjects = this.selected
        .filter((el) => el.isGpzuDoc)
        .map((el) => el.contextWithSubjects);

      if (contextsWithSubjects.length) {
        this.$emit('submit', {
          buttonId: 'updateMZ',
          data: {
            resendRequestIds,
            contextsWithSubjects,
          },
          force: true,
        });
      } else {
        this.$emit('submit', {
          buttonId: 'updateMZ',
          data: {
            resendRequestIds,
          },
          force: true,
        });
      }
      this.value = false;
    },
  },
};
</script>
