<template>
  <div class="row mb-3">
    <h5>{{ trans(EVALUATION_DOCUMENTS) }} :</h5>
    <div class="flex-table">
      <div
        class="item-bloc"
        v-for="(d, i) in documents"
        :key="d.id"
        :class="[parseInt(docAnchorId) === d.id ? 'bg-blink' : 'nothing']"
      >
        <div :id="'document_' + d.id" class="item-row">
          <div class="input-group input-group-lg mb-3 row">
            <label class="col-sm-3 col-form-label">Titre du document:</label>
            <div class="col-sm-9">
              <input
                class="form-control document-title"
                type="text"
                :value="d.title"
                :id="d.id"
                :data-key="i"
                @input="$emit('inputDocumentTitle', $event)"
              />
            </div>
          </div>
        </div>
        <div class="item-row">
          <div class="item-col item-meta">
            <p v-if="d.createdBy" class="createdBy">
              Créé par {{ d.createdBy.text }}<br />
              Le
              {{ $d(ISOToDatetime(d.createdAt.datetime), "long") }}
            </p>
          </div>
        </div>
        <div class="item-row">
          <div class="item-col">
            <ul class="record_actions">
              <li
                v-if="
                  d.workflows_availables.length > 0 || d.workflows.length > 0
                "
              >
                <list-workflow-modal
                  :workflows="d.workflows"
                  :allowCreate="true"
                  relatedEntityClass="Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluationDocument"
                  :relatedEntityId="d.id"
                  :workflowsAvailables="d.workflows_availables"
                  :preventDefaultMoveToGenerate="true"
                  :goToGenerateWorkflowPayload="{ doc: d }"
                  @go-to-generate-workflow="
                    goToGenerateWorkflowEvaluationDocument
                  "
                ></list-workflow-modal>
              </li>
              <li>
                <button
                  v-if="AmIRefferer"
                  class="btn btn-notify"
                  @click="$emit('goToGenerateNotification', d, false)"
                ></button>
                <template v-else>
                  <button
                    id="btnGroupNotifyButtons"
                    type="button"
                    class="btn btn-notify dropdown-toggle"
                    :title="trans(EVALUATION_NOTIFICATION_SEND)"
                    data-bs-toggle="dropdown"
                    aria-expanded="false"
                  >
                    &nbsp;
                  </button>
                  <ul
                    class="dropdown-menu"
                    aria-labelledby="btnGroupNotifyButtons"
                  >
                    <li>
                      <a
                        class="dropdown-item"
                        @click="goToGenerateDocumentNotification(d, true)"
                      >
                        {{ trans(EVALUATION_NOTIFICATION_NOTIFY_REFERRER) }}
                      </a>
                    </li>
                    <li>
                      <a
                        class="dropdown-item"
                        @click="goToGenerateDocumentNotification(d, false)"
                      >
                        {{ trans(EVALUATION_NOTIFICATION_NOTIFY_ANY) }}
                      </a>
                    </li>
                  </ul>
                </template>
              </li>
              <li>
                <document-action-buttons-group
                  :stored-object="d.storedObject"
                  :filename="d.title"
                  :can-edit="true"
                  :execute-before-leave="submitBeforeLeaveToEditor"
                  :davLink="d.storedObject._links?.dav_link.href"
                  :davLinkExpiration="
                    d.storedObject._links?.dav_link.expiration
                  "
                  @on-stored-object-status-change="
                    $emit('statusDocumentChanged', $event)
                  "
                ></document-action-buttons-group>
              </li>
              <!--replace document-->
              <li
                v-if="
                  Number.isInteger(d.id) && d.storedObject._permissions.canEdit
                "
              >
                <drop-file-modal
                  :existing-doc="d.storedObject"
                  :allow-remove="false"
                  @add-document="
                    (arg) =>
                      replaceDocument(
                        d,
                        arg.stored_object,
                        arg.stored_object_version,
                      )
                  "
                ></drop-file-modal>
              </li>
              <li v-if="Number.isInteger(d.id)">
                <div class="duplicate-dropdown">
                  <button
                    class="btn btn-outline-primary dropdown-toggle"
                    type="button"
                    data-bs-toggle="dropdown"
                    aria-expanded="false"
                  >
                    <i class="bi bi-lightning-fill"></i>
                  </button>
                  <ul class="dropdown-menu">
                    <!--delete-->
                    <li v-if="d.workflows.length === 0">
                      <a
                        class="dropdown-item"
                        @click="$emit('removeDocument', d)"
                      >
                        <i class="fa fa-trash-o" aria-hidden="true"></i>
                        {{ trans(EVALUATION_DOCUMENT_DELETE) }}
                      </a>
                    </li>
                    <!--duplicate document-->
                    <li>
                      <a
                        class="dropdown-item"
                        @click="$emit('duplicateDocument', d)"
                      >
                        <i class="fa fa-copy" aria-hidden="true"></i>
                        {{ trans(EVALUATION_DOCUMENT_DUPLICATE_HERE) }}
                      </a>
                    </li>
                    <li>
                      <a
                        class="dropdown-item"
                        @click="prepareDocumentDuplicationToWork(d)"
                      >
                        <i class="fa fa-copy" aria-hidden="true"></i>
                        {{
                          trans(
                            EVALUATION_DOCUMENT_DUPLICATE_TO_OTHER_EVALUATION,
                          )
                        }}</a
                      >
                    </li>
                    <!--move document-->
                    <li v-if="d.storedObject._permissions.canEdit">
                      <a
                        class="dropdown-item"
                        @click="prepareDocumentMoveToWork(d)"
                      >
                        <i class="fa fa-arrows" aria-hidden="true"></i>
                        {{ trans(EVALUATION_DOCUMENT_MOVE) }}</a
                      >
                    </li>
                  </ul>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>

  <AccompanyingPeriodWorkSelectorModal
    v-if="showAccompanyingPeriodSelector"
    v-model:selectedAcpw="selectedAcpw"
    :accompanying-period-id="accompanyingPeriodId"
    :is-evaluation-selector="true"
    :ignore-accompanying-period-work-ids="[]"
    @close-modal="showAccompanyingPeriodSelector = false"
    @update:selectedEvaluation="selectedEvaluation = $event"
  />
</template>

<script setup>
import { ISOToDatetime } from "ChillMainAssets/chill/js/date";
import ListWorkflowModal from "ChillMainAssets/vuejs/_components/EntityWorkflow/ListWorkflowModal.vue";
import DocumentActionButtonsGroup from "ChillDocStoreAssets/vuejs/DocumentActionButtonsGroup.vue";
import DropFileModal from "ChillDocStoreAssets/vuejs/DropFileWidget/DropFileModal.vue";
import {
  EVALUATION_NOTIFICATION_NOTIFY_REFERRER,
  EVALUATION_NOTIFICATION_NOTIFY_ANY,
  EVALUATION_NOTIFICATION_SEND,
  EVALUATION_DOCUMENTS,
  EVALUATION_DOCUMENT_MOVE,
  EVALUATION_DOCUMENT_DELETE,
  EVALUATION_DOCUMENT_DUPLICATE_HERE,
  EVALUATION_DOCUMENT_DUPLICATE_TO_OTHER_EVALUATION,
  trans,
} from "translator";
import { computed, ref, watch } from "vue";
import AccompanyingPeriodWorkSelectorModal from "ChillPersonAssets/vuejs/_components/AccompanyingPeriodWorkSelector/AccompanyingPeriodWorkSelectorModal.vue";
import { buildLinkCreate } from "ChillMainAssets/lib/entity-workflow/api";
import { buildLinkCreate as buildLinkCreateNotification } from "ChillMainAssets/lib/entity-notification/api";
import { useStore } from "vuex";

const props = defineProps([
  "documents",
  "docAnchorId",
  "accompanyingPeriodId",
  "evaluation",
]);
const emit = defineEmits([
  "inputDocumentTitle",
  "removeDocument",
  "duplicateDocument",
  "statusDocumentChanged",
  "duplicateDocumentToWork",
]);

const store = useStore();

const showAccompanyingPeriodSelector = ref(false);
const selectedEvaluation = ref(null);
const selectedDocumentToDuplicate = ref(null);
const selectedDocumentToMove = ref(null);

const AmIRefferer = computed(() => {
  return !(
    store.state.work.accompanyingPeriod.user &&
    store.state.me &&
    store.state.work.accompanyingPeriod.user.id !== store.state.me.id
  );
});

const prepareDocumentDuplicationToWork = (d) => {
  selectedDocumentToDuplicate.value = d;
  /** ensure selectedDocumentToMove is null */
  selectedDocumentToMove.value = null;

  showAccompanyingPeriodSelector.value = true;
};

const prepareDocumentMoveToWork = (d) => {
  selectedDocumentToMove.value = d;
  /** ensure selectedDocumentToDuplicate is null */
  selectedDocumentToDuplicate.value = null;

  showAccompanyingPeriodSelector.value = true;
};

watch(selectedEvaluation, (val) => {
  if (selectedDocumentToDuplicate.value) {
    emit("duplicateDocumentToEvaluation", {
      evaluation: val,
      document: selectedDocumentToDuplicate.value,
    });
  } else {
    emit("moveDocumentToEvaluation", {
      evaluationDest: val,
      document: selectedDocumentToMove.value,
    });
  }
});

async function goToGenerateWorkflowEvaluationDocument({
  workflowName,
  payload,
}) {
  const callback = (data) => {
    let evaluation = data.accompanyingPeriodWorkEvaluations.find(
      (e) => e.key === props.evaluation.key,
    );
    let updatedDocument = evaluation.documents.find(
      (d) => d.key === payload.doc.key,
    );
    window.location.assign(
      buildLinkCreate(
        workflowName,
        "Chill\\PersonBundle\\Entity\\AccompanyingPeriod\\AccompanyingPeriodWorkEvaluationDocument",
        updatedDocument.id,
      ),
    );
  };

  return store.dispatch("submit", callback).catch((e) => {
    console.log(e);
    throw e;
  });
}

/**
 * Replaces a document in the store with a new document.
 *
 * @param {Object} oldDocument - The document to be replaced.
 * @param {StoredObject} storedObject - The stored object of the new document.
 * @param {StoredObjectVersion} storedObjectVersion - The new version of the document
 * @return {void}
 */
async function replaceDocument(oldDocument, storedObject, storedObjectVersion) {
  let document = {
    type: "accompanying_period_work_evaluation_document",
    storedObject: storedObject,
    title: oldDocument.title,
  };

  return store.commit("replaceDocument", {
    key: props.evaluation.key,
    document,
    oldDocument: oldDocument,
    stored_object_version: storedObjectVersion,
  });
}

async function goToGenerateDocumentNotification(document, tos) {
  const callback = (data) => {
    let evaluation = data.accompanyingPeriodWorkEvaluations.find(
      (e) => e.key === props.evaluation.key,
    );
    let updatedDocument = evaluation.documents.find(
      (d) => d.key === document.key,
    );
    window.location.assign(
      buildLinkCreateNotification(
        "Chill\\PersonBundle\\Entity\\AccompanyingPeriod\\AccompanyingPeriodWorkEvaluationDocument",
        updatedDocument.id,
        tos === true ? store.state.work.accompanyingPeriod.user?.id : null,
        window.location.pathname +
          window.location.search +
          window.location.hash,
      ),
    );
  };

  return store.dispatch("submit", callback).catch((e) => {
    console.log(e);
    throw e;
  });
}

async function submitBeforeLeaveToEditor() {
  console.log("submit beore edit 2");
  // empty callback
  const callback = () => null;
  return store.dispatch("submit", callback).catch((e) => {
    console.log(e);
    throw e;
  });
}
</script>
