<i18n>
{
  "en": {
    "StagesCard": {
      "number": "number",
      "statusTrigger": "Status trigger",
      "statusScope": "Status scope",
      "name": "Name",
      "executionPeriodInDays": "Еxecution period",
      "notifyInHours": "mock link",
      "tableTitle": "Stages",
      "create": "New stage",
      "noProcessesResult": "No Processes result",
      "confirmationMessage": "Are you sure you want to delete the stage?"
    },
    "suspense": {
      "label": {
        "create": "New Suspense"
      },
      "table": {
        "title": "Suspenses",
        "noItems": "Suspensions not found",
        "cols": {
          "period": "Period",
          "cause": "Cause suspension",
          "goal": "Target"
        }
      },
      "confirmationMessage": "Are you sure you want to remove the suspension?"
    }
  },
  "ru": {
    "StagesCard": {
      "number": "Номер",
      "statusTrigger": "Триггер",
      "statusScope": "Возможные статусы",
      "name": "Наименование",
      "executionPeriodInDays": "Период предоставления",
      "notifyInHours": "Время уведомления",
      "tableTitle": "Административные процедуры",
      "create": "Новый этап",
      "noProcessesResult": "Административные процедуры не найдены",
      "confirmationMessage": "Вы уверены, что хотите удалить aдминистративную процедуру?"
    },
    "suspense": {
      "label": {
        "create": "Добавить приостановку"
      },
      "table": {
        "title": "Приостановки",
        "noItems": "Приостановки не найдены",
        "cols": {
          "period": "Срок",
          "cause": "Количество причин",
          "goal": "Цель"
        }
      },
      "confirmationMessage": "Вы уверены, что хотите удалить приостановку?"
    }
  }
}
</i18n>

<template>
  <div v-if="common.active === 'stages' && !loadingCard" class="q-pb-md">
    <q-card class="no-shadow q-gutter-y-md q-mx-md no-border-radius">
      <div
        class="q-gutter-y-md bg-white q-px-lg q-pb-md q-pt-sm q-mt-md q-mx-md rounded-borders"
      >
        <div
          class="flex justify-between q-my-md row"
          style="width: 100%"
          v-if="canEdit"
        >
          <div class="text-h6">{{ $t('StagesCard.tableTitle') }}</div>
          <div>
            <q-btn
              v-if="state === 'inProgress'"
              class="q-mr-sm"
              color="primary"
              icon="add_box"
              :label="$t('StagesCard.create')"
              @click="addStage"
            />

            <q-btn
              v-if="state === 'inProgress'"
              color="primary"
              icon="add_box"
              :label="$t('suspense.label.create')"
              @click="addSuspense"
            />
          </div>
        </div>

        <q-table
          v-if="stages.length"
          :columns="columns"
          :data="stages"
          :pagination.sync="pagination"
          hide-bottom
        >
          <template #header="props">
            <q-tr :props="props">
              <q-th v-if="!kcrImport" style="font-size: 16px; font-weight: 600">
                {{ $t('StagesCard.number') }}
              </q-th>
              <q-th v-for="col in props.cols" :key="col.name" :props="props">
                {{ col.label }}
              </q-th>
              <q-th style="font-size: 16px; font-weight: 600">
                {{ $t('StagesCard.statusScope') }}
              </q-th>
              <q-th style="font-size: 16px; font-weight: 600">
                {{ $t('StagesCard.statusTrigger') }}
              </q-th>
              <q-th v-if="state === 'inProgress'" />
            </q-tr>
          </template>
          <template #body="props">
            <q-tr :props="props">
              <q-td v-if="!kcrImport" auto-width>
                {{ props.row.number }}
              </q-td>
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                {{ col.value }}
              </q-td>
              <q-td style="white-space: pre-wrap">
                <span
                  v-for="(item, index) in props.row.statusScope"
                  :key="index"
                  style="display: inline-block; margin: 0 5px"
                >
                  <q-badge :label="item" />
                </span>
              </q-td>
              <q-td>
                <q-badge
                  v-if="props.row.statusTrigger"
                  :label="props.row.statusTrigger"
                />
              </q-td>
              <q-td v-if="state === 'inProgress'" auto-width>
                <q-btn
                  v-if="canEdit"
                  text-color="primary"
                  icon="edit"
                  flat
                  @click="editStageItem(props.row)"
                />
                <q-btn
                  v-if="canEdit"
                  text-color="negative"
                  icon="delete"
                  flat
                  @click="toggleDeleteConfim(props.row)"
                />
              </q-td>
            </q-tr>

            <q-tr v-if="props.row.actions">
              <q-td colspan="100%">
                <div
                  v-for="(item, index) in props.row.actions"
                  :key="`actions_${index}`"
                  class="q-ma-sm"
                  style="padding-left: 73px"
                >
                  - {{ item.name }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </q-table>
        <div v-else class="full-width text-center">
          {{ $t('StagesCard.noProcessesResult') }}
        </div>

        <div class="text-h6 q-mt-lg">{{ $t('suspense.table.title') }}</div>

        <div class="row items-center" v-if="extendDueDate.length">
          <q-input
            :disable="extendNumberFlag"
            v-model="maxExtendNumber"
            class="col-10"
            outlined
            type="text"
            label="Количество приостановок"
          />
          <q-checkbox
            v-model="extendNumberFlag"
            class="col-2"
            label="Не ограничено"
          />
        </div>

        <q-table
          v-if="extendDueDate.length"
          :columns="suspense.columns"
          :data="extendDueDate"
          :pagination.sync="suspense.pagination"
          hide-bottom
        >
          <template #header="props">
            <q-tr :props="props">
              <q-th v-for="col in props.cols" :key="col.name" :props="props">
                {{ col.label }}
              </q-th>
              <q-th v-if="state === 'inProgress'" />
            </q-tr>
          </template>
          <template #body="props">
            <q-tr :props="props">
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                <template v-if="col.name === 'goal'">
                  <span
                    v-for="(goal, index) in col.value"
                    :key="index"
                    style="display: inline-block; margin: 0 5px"
                  >
                    <q-badge :label="goal" />
                  </span>
                </template>
                <template v-if="col.name === 'inCalendarDays'">
                  <span v-if="col.value">календарные дни</span>
                  <span v-else>рабочие дни</span>
                </template>
                <template v-if="col.name === 'cause'">
                  {{ col.value.length }}
                </template>
                <template v-if="col.name === 'numberTerm'">
                  {{ col.value }}
                </template>
              </q-td>

              <q-td v-if="state === 'inProgress'" auto-width>
                <q-btn
                  v-if="canEdit"
                  text-color="primary"
                  icon="edit"
                  flat
                  @click="editSuspenseItem(props.row)"
                />
                <q-btn
                  v-if="canEdit"
                  text-color="negative"
                  icon="delete"
                  flat
                  @click="toggleDeleteSuspenseConfim(props.row)"
                />
              </q-td>
            </q-tr>
          </template>
        </q-table>

        <div v-else class="full-width text-center">
          {{ $t('suspense.table.noItems') }}
        </div>
      </div>
    </q-card>

    <q-dialog v-model="deleteConfim" class="full-width">
      <q-card class="no-shadow full-width">
        <q-card-section>
          <div class="text-h6">
            {{ $t('StagesCard.confirmationMessage') }}
          </div>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            color="primary"
            :label="$t('base.delete')"
            @click="deleteStage"
          />

          <q-btn
            color="white"
            text-color="primary"
            outline
            :label="$t('base.undo')"
            @click="toggleDeleteConfim"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <q-dialog v-model="suspense.deleteConfim" class="full-width">
      <q-card class="no-shadow full-width">
        <q-card-section>
          <div class="text-h6">
            {{ $t('suspense.confirmationMessage') }}
          </div>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            color="primary"
            :label="$t('base.delete')"
            @click="deleteSuspense"
          />

          <q-btn
            color="white"
            text-color="primary"
            outline
            :label="$t('base.undo')"
            @click="toggleDeleteSuspenseConfim"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <StageDialog
      :common="common"
      :model="model"
      :dialog-data="formModel"
      @commonModels="commonModels"
    />

    <SuspenseDialog :common="common" @commonModels="commonModels" />
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import get from 'lodash/get';
import cloneDeep from 'lodash/cloneDeep';
import { notifyError } from '@utils/notify';
import { v4 } from 'uuid';
import StageDialog from '@components/cards/services/StageDialog.vue';
import SuspenseDialog from '@components/cards/services/SuspenseDialog.vue';
import log from '@components/services/emulation/components/log.vue';

export default {
  props: ['common', 'model'],
  components: { StageDialog, SuspenseDialog },
  data() {
    return {
      deleteConfim: false,
      deleteItem: null,
      openEditModal: false,
      formModel: {},
      pagination: {
        rowsPerPage: 0,
      },
      suspense: {
        deleteConfim: false,
        deleteItem: null,
        columns: [
          {
            align: 'left',
            field: 'numberTerm',
            label: this.$t('suspense.table.cols.period'),
            name: 'numberTerm',
            sortable: true,
            style: 'white-space: normal;',
            headerStyle: 'font-size: 16px; font-weight: 600; max-width: 80px',
          },
          {
            align: 'left',
            field: 'inCalendarDays',
            label: 'Дни',
            name: 'inCalendarDays',
            sortable: false,
            style: 'white-space: normal;',
            headerStyle: 'font-size: 16px; font-weight: 600; max-width: 80px',
          },
          {
            align: 'left',
            field: 'causeList',
            label: this.$t('suspense.table.cols.cause'),
            name: 'cause',
            sortable: false,
            style: 'white-space: normal;',
            headerStyle: 'font-size: 16px; font-weight: 600; min-width: 400px',
          },
          {
            align: 'left',
            field: 'goal',
            label: this.$t('suspense.table.cols.goal'),
            name: 'goal',
            sortable: false,
            style: 'white-space: normal;',
            headerStyle: 'font-size: 16px; font-weight: 600; width: 200px',
          },
        ],
        pagination: {
          rowsPerPage: 0,
        },
      },
      extendNumber: '',
    };
  },
  computed: {
    loadingCard() {
      return (
        this.$store.getters['registryService/services/servicesLoading'] || false
      );
    },
    kcrImport() {
      return this.$store.getters['registryService/services/servicesCard']
        .kcrImport;
    },
    columns() {
      const headerStyle = 'font-size: 16px; font-weight: 600';
      return [
        {
          align: 'left',
          field: 'name',
          label: this.$t('StagesCard.name'),
          name: 'name',
          sortable: true,
          style: 'white-space: normal;',
          headerStyle,
        },
        {
          align: 'left',
          field: 'executionPeriodInDays',
          label: this.$t('StagesCard.executionPeriodInDays'),
          name: 'executionPeriodInDays',
          sortable: false,
          style: 'white-space: pre-wrap',
          format: (val) => (val ? `${val} дн.` : ''),
          headerStyle,
        },
        {
          align: 'left',
          field: 'notifyInHours',
          label: this.$t('StagesCard.notifyInHours'),
          format: (_, row) => {
            return row?.notifyInHours
              ? `${row?.notifyInHours} ч.`
              : row?.notifyInMinutes
              ? `${row?.notifyInMinutes} мин.`
              : '';
          },
          name: 'notifyInHours',
          sortable: false,
          headerStyle,
        },
      ];
    },
    card: {
      get: function () {
        return cloneDeep(
          this.$store.getters['registryService/services/servicesCard']
        );
      },
      set: function (val) {
        this.$store.commit('registryService/services/servicesCard', val);
      },
    },
    maxExtendNumber: {
      get: function () {
        return (
          this.$store.getters['registryService/services/servicesCard']
            .maxExtendNumber || 0
        );
      },
      set: function (val: string): void {
        const value = parseInt(val);
        this.$store.commit(
          'registryService/services/setMaxExtendNumber',
          isNaN(value) ? 0 : Math.abs(value)
        );
      },
    },
    extendNumberFlag: {
      get: function (): boolean {
        const maxExtendNumberFlag = this.$store.getters['registryService/services/servicesCard'].maxExtendNumberFlag;
        return maxExtendNumberFlag == null ? true : maxExtendNumberFlag;
      },
      set: function (val: boolean): void {
        this.$store.commit('registryService/services/setExtendNumberFlag', val);
      },
    },
    stages() {
      const card = this.$store.getters['registryService/services/servicesCard'];
      return (card.stages || [])
        .map((i) => {
          i.uuid = `f${(~~(Math.random() * 1e8)).toString(16)}`;
          return i;
        })
        .sort((a, b) => a.number - b.number);
    },
    extendDueDate: {
      get: function () {
        const card = this.$store.getters[
          'registryService/services/servicesCard'
        ];
        return (card.extendDueDate || []).sort(
          (a, b) => a.numberTerm - b.numberTerm
        );
      },
    },

    state() {
      return get(this.card, 'state', 'inProgress');
    },
    canEdit(): boolean {
      return this.$store.getters['registryService/services/canEdit'];
    },
  },

  methods: {
    toggleDeleteConfim(item = null) {
      this.deleteConfim = !this.deleteConfim;
      this.deleteItem = item;
    },
    deleteStage() {
      try {
        this.card.stages = this.stages.filter(
          (i) => i.uuid !== this.deleteItem.uuid
        );
        this.$store.dispatch(
          'registryService/services/setCardForJson',
          this.card
        );
      } catch (e) {
        notifyError(e.message.toString());
      } finally {
        this.toggleDeleteConfim();
      }
    },
    editStageItem(row) {
      this.commonModels({
        StageDialog: {
          data: row,
        },
      });
    },
    addStage() {
      this.commonModels({
        StageDialog: {
          data: 'createMode',
        },
      });
    },

    toggleDeleteSuspenseConfim(item = null) {
      this.suspense.deleteConfim = !this.suspense.deleteConfim;
      this.suspense.deleteItem = item;
    },
    deleteSuspense() {
      try {
        this.card.extendDueDate = this.extendDueDate.filter(
          (i) => i.uuid !== this.suspense.deleteItem.uuid
        );

        this.$store.dispatch(
          'registryService/services/setCardForJson',
          this.card
        );
      } catch (e) {
        notifyError(e.message.toString());
      } finally {
        this.toggleDeleteSuspenseConfim();
      }
    },
    editSuspenseItem(row) {
      this.commonModels({
        SuspenseDialog: {
          data: row,
        },
      });
    },
    addSuspense() {
      this.commonModels({
        SuspenseDialog: { data: 'createMode' },
      });
    },

    commonModels(val) {
      this.$emit('commonModels', val);
    },
  },
  watch: {
    extendNumberFlag: function () {
      this.maxExtendNumber = 0;
    },
    card: {
      handler () {
        console.log('asdasdasd');
      },
      deep: true,
    },
  },
};
</script>
