<i18n>
{
  "en": {
    "statements": {
      "SystemCard": {
        "info": "Service information",
        "archive": "Download archive",
        "processTitle": "Information about processes",
        "instance": "Process instance",
        "businessKey": "Business-key",
        "incidents": "Incidents",
        "mzId": "Interagency id",
        "mzRequest": "Request",
        "mzResponse": "Response",
        "noInfo": "No information",
        "camundaCockpit": "Camunda Cockpit link",
        "killProcess": "Kill process",
        "restore": "Restore"
      }
    }
  },
  "ru": {
    "statements": {
      "SystemCard": {
        "info": "Информация об услуге",
        "archive": "Скачать архив",
        "processTitle": "Системные процессы",
        "instance": "Инстанс процесса",
        "businessKey": "Бизнес-ключ",
        "incidents": "Инциденты",
        "mzId": "Идентификатор межвед. запроса",
        "mzRequest": "Запрос",
        "mzResponse": "Ответ",
        "noInfo": "Нет информации",
        "camundaCockpit": "Ссылка на Camunda Cockpit",
        "killProcess": "Убить процесс",
        "restore": "Восстановить"
      }
    }
  }
}
</i18n>

<template>
  <div class="row q-pa-md justify-center" v-if="common.active === 'system' && $AC.haveScope(USER_SCOPES.CLOUD_ADMIN)">
    <div class="col-12 max-1280-width">
      <a target="_blank" ref="camundaLink"></a>
      <div
        class="row no-wrap q-col-gutter-md"
        v-if="!loading"
      >
        <div
          class="col-3 column q-gutter-sm"
        >
          <span class="System-Header">
            {{ $t('statements.SystemCard.processTitle') }}
          </span>
          <q-btn
            class="System-GoButton"
            outline
            color=""
            icon="pgs-info"
            :label="$t('statements.SystemCard.info')"
            @click="goToConstructor"
          />
          <q-btn
            outline
            v-if="false"
            :label="$t('statements.SystemCard.archive')"
          />
          <div class="flex items-center">
            <q-btn
              outline
              color="primary"
              padding="sm"
              class="q-mr-sm"
              @click="restore"
              v-if="$AC.haveScope(USER_SCOPES.CLOUD_ADMIN)"
            >
              {{ $t('statements.SystemCard.restore') }}
            </q-btn>
            <q-btn
              color="negative"
              icon="cancel_presentation"
              padding="sm"
              @click="killProcess"
            >
              <q-tooltip>
                {{ $t('statements.SystemCard.killProcess') }}
              </q-tooltip>
            </q-btn>
          </div>
        </div>
        <div
          class="col-9 column"
        >
          <div v-for="(process) in processes" class="System-Table">
            <div class="System-Cell">
              {{ getInstanceName(process) }}
            </div>
            <div class="System-Cell">
              <span style="color: rgba(2, 12, 18, 0.58);">
                {{ $t('statements.SystemCard.businessKey') }}:&nbsp
              </span>
              <span>{{ process.traceId }}</span>
            </div>
            <div class="System-Cell">
              <q-btn
                class="System-CamundaButton"
                :label="$t('statements.SystemCard.camundaCockpit')"
                @click="goToCamunda($event, process.id)"
              />
            </div>
          </div>
        </div>
      </div>
      <div style="padding: 100px" v-if="loading">
        <q-inner-loading :showing="loading">
          <q-spinner-gears color="primary" size="50px" />
        </q-inner-loading>
      </div>
      <q-dialog v-model="dialog">
        <q-card class="full-width no-shadow" style="max-width: 800px">
          <q-card-section>
            <div class="flex justify-end">
              <q-btn
                :label="$t('base.preview.dialog.close')"
                color="primary"
                @click="dialog = false"
              />
            </div>
            <pre>
              {{ dialogData }}
            </pre>
          </q-card-section>
        </q-card>
      </q-dialog>
    </div>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import { CardNeedToUpdateType } from '@constants/models/Card';
import get from 'lodash/get';
import { WorkflowServiceApi } from '@openapi/wf';
import { BaseCardCommon } from '@/interfaces';
import { Model } from '@devsun/eva-models';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import { USER_SCOPES } from '@constants/entities/Scope';
import { notifyError } from '@utils/notify';

const wfApi = new WorkflowServiceApi();

@Component({})
export default class StatementsSystem extends Vue {
  @Prop() common: BaseCardCommon;
  @Prop() model: Model.Base;
  @Prop() userTask: any;
  private processes: Array<any> = [];
  private mzInfos: Array<any> = [];
  private loading = false;
  private dialog = false;
  private dialogData = '';

  USER_SCOPES = USER_SCOPES;

  private get camundaLink(): string {
    return `${location.origin}/service/wf/admin/orgstaff/camunda/app/cockpit/default/#/process-instance/`;
  }

  private goToConstructor(): void {
    this.$router.push({
      name: 'cards',
      params: {
        id: get(this.model, 'system.serviceId', ''),
        path: 'services',
      },
      query: {
        active: 'basic',
        components: this.$store.getters['cardComponents/services/components'],
      },
    });
  }

  private goToCamunda($event: any, value: string): void {
    const link = this.$refs.camundaLink;
    link.href = `${this.camundaLink}${value}/runtime`;
    link.click();
  }

  private getInstanceName(process: any): string {
    return process.definitionName ?? process.definitionId.split(':')[0];
  }

  private initProcesses(): void {
    console.log(
      '[statements][System][initProcesses] UT & MODEL',
      this.userTask,
      this.model
    );
    console.log(get(this.userTask, 'process.traceId', ''));
    console.log(get(this.model, 'system.processId', ''));
    this.loading = true;
    wfApi
      .getProcInfo(get(this.model, 'system.processId'))
      .then(({ data }) => {
        this.loading = false;
        this.processes = get(data, 'processes', []);
      })
      .catch(() => {
        this.loading = false;
      });
  }

  private async killProcess(): Promise<void> {
    await wfApi.killProcInstaces({
      ids: [`${this.model.system.processId}`],
      skipSubProcesses: false,
    });
    this.$store.commit(`utils/cards/needToUpdate`, CardNeedToUpdateType.TRUE);
  }

  private async restore(): void {
    this.loading = true;
    try {
      await wfApi.start({
        processKey: 'applicationRestore',
        syncMode: false,
        utStepMode: false,
        userId: this.$store.state.oidcClient.currentUser.sub,
        data: {
          redirectUrl: '',
          readonlyFields: [],
          userId: this.$store.state.oidcClient.currentUser.sub,
          applicationId: this.model.id,
        },
      });
      this.loading = false;
    } catch (e) {
      this.loading = false;
      notifyError(e.message.toString());
    }
  }

  @Watch('userTask')
  updateUserTaskHandler(value: any) {
    if (value && this.common.active === 'system') {
      this.initProcesses();
    }
  }

  @Watch('common.active')
  updateModelHandler(value: any) {
    if (value && !this.mzInfos.length && !this.processes.length) {
      this.initProcesses();
    }
  }
}
</script>

<style lang="scss">
.System {
  &-Header {
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 500;
    font-size: 20px;
    line-height: 24px;
    letter-spacing: -0.015em;
    color: rgba(2, 12, 18, 0.9);
  }
  &-GoButton {
    background: rgba(25, 164, 233, 0.1) !important;
    border: 1px solid rgba(1, 72, 116, 0.11) !important;
    color: #107ABC !important;
    font-family: 'Golos UI', serif !important;
    font-style: normal !important;
    font-weight: 500 !important;
    font-size: 14px !important;
    line-height: 16px !important;
    border-radius: 24px !important;
  }

  &-CancelButton {
    background-color: #D1151E !important;
    color: rgba(255, 255, 255, 0.92) !important;
    font-family: 'Golos UI', serif !important;
    font-style: normal !important;
    font-weight: 500 !important;
    font-size: 14px !important;
    line-height: 16px !important;
    border-radius: 24px !important;
  }
  &-Table {
    display: grid;
    grid-template-columns: 1fr 2fr 1fr;
    background: rgba(53, 126, 172, 0.05);
    border: 1px solid rgba(1, 72, 116, 0.11);
    border-radius: 8px;
    width: 100%;
    &:not(:last-child) {
      margin-bottom: 4px;
    }
  }
  &-Cell {
    display: flex;
    align-items: center;
    &:first-child {
      padding: 4px 0 4px 4px;
      font-family: 'Golos UI', sans-serif;
      font-style: normal;
      font-weight: 500;
      font-size: 14px;
      line-height: 16px;
      color: rgba(2, 12, 18, 0.9);
    }
    &:nth-child(2) {
      justify-content: flex-end;
      font-family: 'Golos UI', sans-serif;
      font-style: normal;
      font-weight: 400;
      font-size: 12px;
      line-height: 14px;
      color: rgba(2, 12, 18, 0.9);
    }
    &:last-child {
      justify-content: flex-end;
      padding: 4px 4px 4px 0;
    }
  }
  &-CamundaButton {
    font-family: 'Golos UI', sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 16px;
    color: #107ABC;
  }
}
</style>