<template>
  <div v-if="common.active === 'processes'">
    <a ref="downloadBpmn" />
    <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-end q-px-md q-my-md row" style="width: 100%">
          <div>
            <q-btn
              color="primary"
              text-color="white"
              v-if="
                card.state === 'IN_PROCESS' &&
                $AC.haveOneOfScope([
                  USER_SCOPES.SOCIAL_SETTINGS_GENERAL_ADMIN,
                  USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_ADMIN,
                  USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN,
                ])
              "
              @click="addProcess()"
              icon="add_box"
              label="Новый процесс"
              class="q-mr-md"
            >
            </q-btn>
          </div>
        </div>

        <q-table
          :data="processes"
          :columns="columns"
          class="no-shadow text-grey-9"
          row-key="id"
          title-class="text-subtitle1"
          :rows-per-page-options="[10, 20, 50]"
          wrap-cells
        >
          <template #body-cell-file="props">
            <q-td :props="props">
              <div class="row no-wrap text-no-wrap float-right">
                <q-btn
                  text-color="primary"
                  icon="arrow_downward"
                  unelevated
                  @click="downloadBpmnSchema(props.row)"
                >
                  <q-tooltip>
                    {{ $t('documents.download') }}
                  </q-tooltip>
                </q-btn>
                <q-btn
                  color="white"
                  text-color="primary"
                  @click="goToBpmnSchema(props.row.processId, 'processes')"
                  unelevated
                  icon="search"
                >
                  <q-tooltip :delay="500"> Открыть в редакторе BPMN </q-tooltip>
                </q-btn>
                <q-btn
                  v-if="
                    $AC.haveOneOfScope([
                      USER_SCOPES.SOCIAL_SETTINGS_GENERAL_ADMIN,
                      USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_ADMIN,
                      USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN,
                    ])
                  "
                  icon="attach_file"
                  text-color="primary"
                  @click="addDocumentAttachment(props.row)"
                >
                  <q-tooltip :delay="500">Загрузить</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="
                    card.state === 'IN_PROCESS' &&
                    $AC.haveOneOfScope([
                      USER_SCOPES.SOCIAL_SETTINGS_GENERAL_ADMIN,
                      USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_ADMIN,
                      USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN,
                    ])
                  "
                  @click="editProcessItem(props.row)"
                  icon="edit"
                  text-color="primary"
                >
                  <q-tooltip :delay="500"> Редактировать</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="
                    $AC.haveOneOfScope([
                      USER_SCOPES.SOCIAL_SETTINGS_GENERAL_ADMIN,
                      USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_ADMIN,
                      USER_SCOPES.SOCIAL_SETTINGS_PRO_ACTIVE_ADMIN,
                    ])
                  "
                  text-color="negative"
                  @click="toggleDeleteConfim(props.row)"
                  icon="delete"
                  flat
                >
                  <q-tooltip :delay="500"> Удалить</q-tooltip>
                </q-btn>
              </div>
            </q-td>
          </template>
        </q-table>
      </div>

      <q-dialog class="full-width" v-model="deleteConfim">
        <q-card class="no-shadow full-width">
          <q-card-section>
            <div class="text-h6">Вы уверены, что хотите удалить процесс?</div>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              @click="deleteProcess"
              color="primary"
              :label="$t('base.delete')"
            />
            <q-btn
              color="white"
              text-color="primary"
              outline
              @click="toggleDeleteConfim"
              :label="$t('base.undo')"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </q-card>

    <process-edit-dialog
      v-if="openModal"
      :value.sync="openModal"
      :file.sync="attachFile"
      :schema-name="schemaName"
      :sub-title="documentForAttachment.processName"
      :loading="attachmentLoading"
      @updateDocumentAttachment="updateDocumentAttachment"
      @hide="clearModel"
    />
    <process-dialog ref="processDialog" :cardModel="card" :common="common" />
  </div>
</template>

<script lang="js">
import { fetchAttachment } from '@services/registry-service';
import { saveFileViaLink } from '@utils/files';
import { notifyError } from '@utils/notify';
import ProcessDialog from './ProcessDialog.vue';
import ProcessEditDialog from './ProcessesEditDialog.vue';
import cloneDeep from 'lodash/cloneDeep';
import { SettingsForServiceProcessApi, AttachmentApi } from '@openapi/registry-service';
import { WorkflowServiceApi } from '@openapi/wf';
import { USER_SCOPES } from '@constants/entities/Scope';
import axios from 'axios';

const settingsForServiceProcessApi = new SettingsForServiceProcessApi();
const attachmentApi = new AttachmentApi();
const wfApi = new WorkflowServiceApi();

export default {
  components: {
    ProcessDialog,
    ProcessEditDialog,
  },
  props: ['common'],
  data() {
    return {
      USER_SCOPES: USER_SCOPES,
      file: null,
      deleteItem: null,
      deleteConfim: false,
      openModal: false,
      attachFile: null,
      documentForAttachment: null,
      attachedFileName: '',
      attachmentLoading: false,
      dictTypes: [],
    }
  },
  computed: {
    columns() {
      return [
        {
          align: 'left',
          field: 'processName',
          label: this.$t('additionalSettings.nameProc'),
          name: 'processName',
          sortable: true,
          style: 'width: 50%; font-size: 14px',
          headerStyle: 'width: 50%; font-size: 12px; padding-left: 15px;',
          classes: 'text-primary-9',
        },
        {
          align: 'left',
          field: ({ processType }) => this.dictTypes[processType] || processType,
          label: this.$t('additionalSettings.type'),
          name: 'processType',
          sortable: true,
          style: 'width: 50%;word-break: break-all; font-size: 14px',
          headerStyle: 'width: 50%; font-size: 12px;',
          classes: 'text-primary-9',
        },
        {
          align: 'right',
          field: 'file',
          label: this.$t('documents.documentAction'),
          name: 'file',
          sortable: false,
          headerStyle: 'font-size: 12px;',
          classes: 'text-primary-9',
        },
      ];
    },
    processes() {
      return (
        this.$store.getters['registryService/additionalSettings/settingsForServiceCard'].settingsforserviceprocess || []
      );
    },
    card() {
      return cloneDeep(
        this.$store.getters['registryService/additionalSettings/settingsForServiceCard']
      );
    },
    cardInitial() {
      return cloneDeep(
        this.$store.getters['registryService/additionalSettings/settingsForServiceCardInitial']
      );
    },
    unsavedChanges() {
      return (
        this.$store.getters['registryService/additionalSettings/unsavedChanges']
      );
    },
  },
  async created() {
    await this.$store.dispatch('registryService/additionalSettings/getSettingsDictionary', 'DictProcessTypeForSettingForService')
      .then(() => {
        this.dictTypes = (this.$store.getters[
          'registryService/additionalSettings/setSettingsDictionary'
        ].DictProcessTypeForSettingForService || []).reduce((target, key) => {
          target[key.code] = key.value;
          return target;
        }, {})
      })
  },
  methods: {
    toggleDeleteConfim(item) {
      this.deleteConfim = !this.deleteConfim;
      this.deleteItem = item;
    },
    async deleteProcess() {
      let processes = cloneDeep(this.processes);
      const findItem = (this.cardInitial?.settingsforserviceprocess || [])
        .find(e => e.id === this.deleteItem.id);

      if (findItem) {
        await axios.patch('/service/registry/service/settings-for-service', [{
          id: this.card.id, settingsforserviceprocess: [this.deleteItem.id]
        }])
      };
      await settingsForServiceProcessApi.deleteSettingsForServiceById(this.deleteItem.id);
      processes = processes.filter(e => e.id !== this.deleteItem.id);
      this.card.settingsforserviceprocess = processes;
      this.$store.dispatch(
        'registryService/additionalSettings/setCardForJson',
        this.card
      );
      this.toggleDeleteConfim();
    },

    async updateDocumentAttachment(file) {
      const formdata = new FormData();
      formdata.append("files", file);

      await wfApi.loadSchema(file)
      await attachmentApi.updateDocumentFile('Process', this.documentForAttachment.processId, undefined, [file])
      this.openModal = false;
    },

    addDocumentAttachment(document) {
      this.schemaName = document.schema;
      this.documentForAttachment = document;
      this.attachedFileName = `${document.processName}`;
      this.openModal = true;
    },

    clearModel() {
      this.openModal = false;
      this.attachedFileName = '';
      this.attachFile = null;
    },

    async downloadBpmnSchema(val) {
      if (!val) {
        console.warn('[Additional-settings][Processes][goToBpmnSchema] Missing schema name');
        return;
      }
      try {
        const extension = val.schema === 'SettingsForServiceProcess' ? 'bpmn' : 'dmn';
        const xml = await fetchAttachment(
          'Process',
          val.processId,
          `${val.processName}.${extension}`,
          false
        );

        saveFileViaLink({
          anchor: this.$refs.downloadBpmn,
          hrefData:
            'data:application/bpmn20-xml;charset=UTF-8,' +
            encodeURIComponent(xml),
          fileName: `${val.processName}.${extension}`,
        });
      } catch (e) {
        notifyError(e.message.toString());
      }
    },

    editProcessItem(row) {
      this.$refs.processDialog.open(row)
    },
    addProcess() {
      this.$refs.processDialog.open()
    },

    confirmGoToBpmn(id, editorType) {
      this.$router.push({
        name: 'cards',
        params: {
          id,
          path: editorType,
        },
        query: {
          active: 'index',
          components: 'indexAdditional',
          service: this.card.id,
        },
      });
    },

    goToBpmnSchema(id, editorType) {
      if(this.unsavedChanges) {
        this.$q.dialog({
          message: 'На странице есть несохраненные изменения. Продолжить?',
          cancel: {
            push: true,
            label: 'Отмена'
          },
          ok: 'ОК',
        })
        .onOk(() => {
          this.confirmGoToBpmn(id, editorType)
        });
      } else {
        this.confirmGoToBpmn(id, editorType)
      }
    },
  }
}
</script>
