<template>
  <div class="manual">
    <a ref="downloadBpmn" />
    <div
      class="flex justify-start items-center bg-white q-pa-md q-mt-md q-mx-md rounded-borders"
    >
      <q-btn
        padding="xs"
        class="text-grey-7 q-mr-md"
        color="grey-3"
        icon="arrow_back"
        @click="returnToParentView('/criteria-directory')"
      />
      <span class="text-h5">{{ $t('criteriaDirectory.readCriterion') }}</span>
    </div>
    <div
      class="q-gutter-y-md row bg-white q-px-lg q-pb-md q-pt-sm q-mt-md q-mx-md rounded-borders"
    >
      <div
        class="col text-primary q-pa-sm"
        v-if="
          $AC.haveOneOfScope([
            USER_SCOPES.SOCIAL_DICTIONARY_ADMIN,
            USER_SCOPES.SOCIAL_DICTIONARY_OPERATOR,
          ])
        "
      >
        <div class="q-gutter-y-md">
          <q-card class="full-width no-shadow">
            <q-card-section>
              <div class="q-mt-sm q-mb-sm">
                <base-label-value class="base-label q-gutter-x-md">
                  <template #label>
                    {{ $t('criteriaDirectory.name') }}
                  </template>
                  <template #value> {{ model.name }} </template>
                </base-label-value>
              </div>

              <div class="q-mt-sm">
                <base-label-value class="base-label q-gutter-x-md">
                  <template #label>
                    {{ $t('criteriaDirectory.description') }}
                  </template>
                  <template #value> {{ model.description || '-' }} </template>
                </base-label-value>
              </div>

              <div class="q-mt-sm q-mb-sm">
                <base-label-value class="base-label q-gutter-x-md">
                  <template #label>
                    {{ $t('criteriaDirectory.type') }}
                  </template>
                  <template #value>
                    {{ getCriteriaType(model.type) }}
                  </template>
                </base-label-value>
              </div>

              <div class="q-mt-sm" v-if="model.values">
                <base-label-value class="base-label q-gutter-x-md">
                  <template #label>
                    {{ $t('criteriaDirectory.value') }}
                  </template>
                  <template #value class="row">
                    {{ model.values.join(', ') }}
                  </template>
                </base-label-value>
              </div>

              <div class="q-mt-sm q-mb-sm">
                <base-label-value class="base-label q-gutter-x-md">
                  <template #label>
                    {{ $t('criteriaDirectory.activity') }}
                  </template>
                  <template #value>
                    {{ getStatusLabel(model.status) }}
                  </template>
                </base-label-value>
              </div>

              <div v-if="model.processName" class="q-mt-sm q-mb-sm">
                <base-label-value class="base-label q-gutter-x-md">
                  <template #label>
                    {{ $t('task.process') }}
                  </template>
                  <template #value>
                    <div class="row items-center">
                      <span>{{ model.processName }}</span>
                      <div>
                        <q-btn
                          dense
                          color="white"
                          text-color="primary"
                          icon="arrow_downward"
                          @click="downloadBpmnSchema"
                        >
                          <q-tooltip> Скачать </q-tooltip>
                        </q-btn>
                        <q-btn
                          dense
                          color="white"
                          text-color="primary"
                          @click="goToBpmnSchema()"
                          icon="search"
                        >
                          <q-tooltip :delay="500">
                            Открыть в редакторе BPMN
                          </q-tooltip>
                        </q-btn>
                      </div>
                    </div>
                  </template>
                </base-label-value>
              </div>

              <filters
                :value.sync="model.filters"
                :readOnly="true"
                class="q-mb-lg"
              />

              <changed-fields
                :value.sync="model.changedFields"
                :readOnly="true"
                class="q-mb-lg"
              />
            </q-card-section>
          </q-card>
        </div>
      </div>
      <q-card v-else>
        <q-card-section>
          <div class="text-h6 q-mb-md">У вас нет прав на раздел</div>
          <p>Обратитесь к администратору</p>
        </q-card-section>
      </q-card>
    </div>
    <DownloadDialog :openFormDialog.sync="startDownloadDialog" />
  </div>
</template>

<script lang="ts">
import ReturnToParentView from '@mixins/ReturnToParentView';
import { mixins } from 'vue-class-component';
import { Component, Vue, Prop, PropSync } from 'vue-property-decorator';
import {
  CriteriaApi,
  CriteriaTypeEnum,
  Criteria,
  CriteriaStatusEnum,
} from '@/openapi/personal-accounts';
import { fetchAttachment } from '@services/registry-service';
import { saveFileViaLink } from '@utils/files';
import { notifyError, notifySuccess } from '@/utils/notify';
import { noEmptyValueRule } from '@utils/field-validation/basic';
import { USER_SCOPES } from '@/constants/entities/Scope';
import DownloadDialog from '@components/criteria-directory/download_dialog.vue';
import Filters from './components/Filters.vue';
import ChangedFields from '@components/criteria-directory/components/ChangedFields.vue';

const criteriaApi = new CriteriaApi();

@Component({
  components: {
    DownloadDialog,
    Filters,
    ChangedFields,
  },
  methods: {
    noEmptyValueRule,
  },
})
export default class createCriteriaCategoryDialog extends mixins(
  ReturnToParentView
) {
  @PropSync('openEditFormDialog') open: boolean;
  USER_SCOPES = USER_SCOPES;
  startDownloadDialog = false;
  loading = false;
  statusList = true;
  statusFilter = true;
  model: Criteria = {
    schema: 'Criteria',
    name: '',
    description: '',
    type: CriteriaTypeEnum.List,
    values: [],
    status: CriteriaStatusEnum.Draft,
    changedFields: [],
  };

  criteriaTypes: Record<string, string> = {
    BOOLEAN: 'Флаг',
    NUMBER: 'Числовой',
    TEXT: 'Текстовый',
    LIST: 'Список значений',
  };

  statusLabels: Record<string, string> = {
    DRAFT: 'Черновик',
    ACTIVATED: 'Активен',
    DEACTIVATED: 'Деактивирован',
  };

  getStatusLabel(status: string): string {
    return this.statusLabels[status];
  }

  getCriteriaType(type: string): string {
    return this.criteriaTypes[type] || type;
  }

  created(): void {
    this.getCriteria(this.$route.params.id);
  }

  async getCriteria(id: string): Promise<void> {
    if (!id) return;
    try {
      const { data: criteria } = await criteriaApi.getCriteria(id);
      this.model = criteria;
      (this.model.filters || []).sort(
        (prev, next) => Number(prev?.filterId) - Number(next?.filterId)
      );
    } catch (error) {
      if (error instanceof Error) notifyError(error.message);
    }
  }

  openDownloadDialog(): void {
    this.startDownloadDialog = true;
  }

  async downloadBpmnSchema(): Promise<void> {
    if (!this.model.processId) {
      console.warn('[Servise][Processes][goToBpmnSchema] Missing schema name');
      return;
    }
    try {
      const xml = await fetchAttachment(
        'Process',
        this.model.processId,
        `${this.model.processName}.bpmn`,
        false
      );
      saveFileViaLink({
        anchor: this.$refs.downloadBpmn as HTMLAnchorElement,
        hrefData:
          'data:application/bpmn20-xml;charset=UTF-8,' +
          encodeURIComponent(xml),
        fileName: `${this.model.processName}.bpmn`,
      });
    } catch (e) {
      if (e instanceof Error) notifyError(e.message.toString());
    }
  }

  goToBpmnSchema(): void {
    if (!this.model.processId) {
      console.warn('[Servise][Processes][goToBpmnSchema] Missing schema name');
      return;
    }
    this.$router.push({
      name: 'cards',
      params: {
        id: this.model.processId,
        path: 'processes',
      },
      query: {
        active: 'IndexCriteriaProcess',
        components: 'IndexCriteriaProcess',
        criteria: this.model?.id || '',
      },
    });
  }
}
</script>

<style lang="scss">
.file-cell {
  white-space: pre-line;
}
.document-card {
  width: 100%;
  max-width: 350px;
}

.grid-item-value {
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
