<template>
  <div>
    <!--h2>
      {{ $t('evaluation_title') }}
   </h2-->

    <div class="m-md-3">
      <!--div class="row mb-3">
         <label class="col-sm-4 col-form-label">{{ $t('evaluation_status') }}</label>
         <div class="col-sm-8">
            <select class="form-select form-select-sm" v-model="status">
               <option disabled value="">{{ $t('evaluation_choose_a_status') }}</option>
               <option v-for="s in listAllStatus" :value="s.id">
                  {{ s.id }}
               </option>
            </select>
         </div>
      </div-->

      <div class="row mb-3">
        <label class="col-4 col-sm-2 col-md-4 col-lg-2 col-form-label">
          {{ $t("evaluation_startdate") }}
        </label>
        <div class="col-8 col-sm-4 col-md-8 col-lg-4">
          <input
            class="form-control form-control-sm"
            type="date"
            v-model="startDate"
          />
        </div>

        <label class="col-4 col-sm-2 col-md-4 col-lg-2 col-form-label">
          {{ $t("evaluation_enddate") }}
        </label>
        <div class="col-8 col-sm-4 col-md-8 col-lg-4">
          <input
            class="form-control form-control-sm"
            type="date"
            v-model="endDate"
          />
        </div>
      </div>

      <div class="row mb-3">
        <label class="col-4 col-sm-2 col-md-4 col-lg-2 col-form-label">
          {{ $t("evaluation_maxdate") }}
        </label>
        <div class="col-8 col-sm-4 col-md-8 col-lg-4">
          <input
            class="form-control form-control-sm"
            type="date"
            v-model="maxDate"
          />
        </div>

        <label class="col-4 col-sm-2 col-md-4 col-lg-2 col-form-label">
          {{ $t("evaluation_warning_interval") }}
        </label>
        <div class="col-8 col-sm-4 col-md-8 col-lg-4">
          <input
            class="form-control form-control-sm"
            type="number"
            v-model.number="warningInterval"
          />
        </div>
      </div>

      <div class="row mb-3">
        <label class="col-4 col-sm-2 col-md-4 col-lg-2 col-form-label">
          {{ $t("evaluation_time_spent") }}
        </label>
        <div class="col-8 col-sm-4 col-md-8 col-lg-4">
          <select
            class="form-control form-control-sm"
            type="time"
            v-model="timeSpent"
          >
            <option disabled value="">{{ $t("select_time_spent") }}</option>
            <option v-for="time in timeSpentChoices" :value="time.value">
              {{ time.text }}
            </option>
          </select>
        </div>
      </div>

      <div class="row mb-3">
        <label class="col-sm-4 col-form-label visually-hidden">{{
          $t("evaluation_public_comment")
        }}</label>
        <div class="col-sm-12">
          <ckeditor
            :editor="classicEditor"
            :config="editorConfig"
            :placeholder="$t('evaluation_comment_placeholder')"
            v-model="comment"
            tag-name="textarea"
          ></ckeditor>
        </div>
      </div>

      <div v-if="evaluation.documents.length > 0" class="row mb-3">
        <h5>{{ $t("Documents") }} :</h5>

        <div class="flex-table">
          <div
            class="item-bloc"
            v-for="(d, i) in evaluation.documents"
            :key="d.id"
            :class="[
              parseInt(this.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="onInputDocumentTitle"
                  />
                </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="goToGenerateDocumentNotification(d, false)"
                    ></button>
                    <template v-else>
                      <button
                        id="btnGroupNotifyButtons"
                        type="button"
                        class="btn btn-notify dropdown-toggle"
                        :title="$t('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)"
                            >{{ $t("notification_notify_referrer") }}</a
                          >
                        </li>
                        <li>
                          <a
                            class="dropdown-item"
                            @click="goToGenerateDocumentNotification(d, false)"
                            >{{ $t("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="onStatusDocumentChanged"
                    ></document-action-buttons-group>
                  </li>
                  <li v-if="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="d.workflows.length === 0">
                    <a class="btn btn-delete" @click="removeDocument(d)"> </a>
                  </li>
                  <li v-if="Number.isInteger(d.id)">
                    <button
                      type="button"
                      @click="duplicateDocument(d)"
                      class="btn btn-duplicate"
                      title="Dupliquer"
                    ></button>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="row mb-3">
        <h6>{{ $t("document_add") }} :</h6>
        <pick-template
          entityClass="Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluation"
          :id="evaluation.id"
          :templates="getTemplatesAvailables"
          :preventDefaultMoveToGenerate="true"
          @go-to-generate-document="submitBeforeGenerate"
        >
          <template v-slot:title>
            <label class="col-form-label">{{
              $t("evaluation_generate_a_document")
            }}</label>
          </template>
        </pick-template>
        <div>
          <label class="col-form-label">{{ $t("document_upload") }}</label>
          <ul class="record_actions document-upload">
            <li>
              <drop-file-modal
                :allow-remove="false"
                @add-document="addDocument"
              ></drop-file-modal>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ISOToDatetime } from "ChillMainAssets/chill/js/date";
import { Ckeditor } from "@ckeditor/ckeditor5-vue";
import { ClassicEditor } from "ckeditor5";
import classicEditorConfig from "ChillMainAssets/module/ckeditor5/editor_config";
import { mapState } from "vuex";
import PickTemplate from "ChillDocGeneratorAssets/vuejs/_components/PickTemplate.vue";
import { buildLink } from "ChillDocGeneratorAssets/lib/document-generator";
import ListWorkflowModal from "ChillMainAssets/vuejs/_components/EntityWorkflow/ListWorkflowModal.vue";
import { buildLinkCreate } from "ChillMainAssets/lib/entity-workflow/api";
import { buildLinkCreate as buildLinkCreateNotification } from "ChillMainAssets/lib/entity-notification/api";
import DocumentActionButtonsGroup from "ChillDocStoreAssets/vuejs/DocumentActionButtonsGroup.vue";
import DropFileModal from "ChillDocStoreAssets/vuejs/DropFileWidget/DropFileModal.vue";

const i18n = {
  messages: {
    fr: {
      evaluation_title: "Ecrire une évaluation",
      evaluation_status: "Statut",
      evaluation_choose_a_status: "Choisir un statut",
      evaluation_startdate: "Date d'ouverture",
      evaluation_enddate: "Date de fin",
      evaluation_maxdate: "Date d'échéance",
      evaluation_warning_interval: "Rappel (jours)",
      evaluation_public_comment: "Note publique",
      evaluation_comment_placeholder: "Commencez à écrire ...",
      evaluation_generate_a_document: "Générer un document",
      evaluation_choose_a_template: "Choisir un modèle",
      evaluation_add_a_document: "Ajouter un document",
      evaluation_add: "Ajouter une évaluation",
      evaluation_time_spent: "Temps de rédaction",
      select_time_spent: "Indiquez le temps de rédaction",
      Documents: "Documents",
      document_add: "Générer ou téléverser un document",
      document_upload: "Téléverser un document",
      document_title: "Titre du document",
      template_title: "Nom du template",
      browse: "Ajouter un document",
      replace: "Remplacer",
      download: "Télécharger le fichier existant",
      notification_notify_referrer: "Notifier le référent",
      notification_notify_any: "Notifier d'autres utilisateurs",
      notification_send: "Envoyer une notification",
    },
  },
};

export default {
  name: "FormEvaluation",
  props: ["evaluation", "docAnchorId"],
  components: {
    DropFileModal,
    ckeditor: Ckeditor,
    PickTemplate,
    ListWorkflowModal,
    DocumentActionButtonsGroup,
  },
  i18n,
  data() {
    return {
      template: null,
      asyncUploadOptions: {
        maxFiles: 1,
        maxPostSize: 15000000,
        required: false,
      },
      timeSpentChoices: [
        { text: "1 minute", value: 60 },
        { text: "2 minutes", value: 120 },
        { text: "3 minutes", value: 180 },
        { text: "4 minutes", value: 240 },
        { text: "5 minutes", value: 300 },
        { text: "10 minutes", value: 600 },
        { text: "15 minutes", value: 900 },
        { text: "20 minutes", value: 1200 },
        { text: "25 minutes", value: 1500 },
        { text: "30 minutes", value: 1800 },
        { text: "45 minutes", value: 2700 },
        { text: "1 hour", value: 3600 },
        { text: "1 hour 15 minutes", value: 4500 },
        { text: "1 hour 30 minutes", value: 5400 },
        { text: "1 hour 45 minutes", value: 6300 },
        { text: "2 hours", value: 7200 },
        { text: "2 hours 30 minutes", value: 9000 },
        { text: "3 hours", value: 10800 },
        { text: "3 hours 30 minutes", value: 12600 },
        { text: "4 hours", value: 14400 },
        { text: "4 hours 30 minutes", value: 16200 },
        { text: "5 hours", value: 18000 },
        { text: "5 hours 30 minutes", value: 19800 },
        { text: "6 hours", value: 21600 },
        { text: "6 hours 30 minutes", value: 23400 },
        { text: "7 hours", value: 25200 },
        { text: "7 hours 30 minutes", value: 27000 },
        { text: "8 hours", value: 28800 },
      ],
    };
  },
  computed: {
    ...mapState(["isPosting", "work", "me"]),
    classicEditor: () => ClassicEditor,
    editorConfig: () => classicEditorConfig,
    AmIRefferer() {
      return !(
        this.$store.state.work.accompanyingPeriod.user &&
        this.$store.state.me &&
        this.$store.state.work.accompanyingPeriod.user.id !==
          this.$store.state.me.id
      );
    },
    getTemplatesAvailables() {
      return this.$store.getters.getTemplatesAvailablesForEvaluation(
        this.evaluation.evaluation,
      );
    },
    canGenerate() {
      return !this.$store.state.isPosting && this.template !== null;
    },
    startDate: {
      get() {
        console.log("evaluation", this.evaluation);
        return this.evaluation.startDate;
      },
      set(v) {
        this.$store.commit("setEvaluationStartDate", {
          key: this.evaluation.key,
          date: v,
        });
      },
    },
    endDate: {
      get() {
        return this.evaluation.endDate;
      },
      set(v) {
        this.$store.commit("setEvaluationEndDate", {
          key: this.evaluation.key,
          date: v,
        });
      },
    },
    maxDate: {
      get() {
        return this.evaluation.maxDate;
      },
      set(v) {
        this.$store.commit("setEvaluationMaxDate", {
          key: this.evaluation.key,
          date: v,
        });
      },
    },
    warningInterval: {
      get() {
        return this.evaluation.warningInterval;
      },
      set(v) {
        this.$store.commit("setEvaluationWarningInterval", {
          key: this.evaluation.key,
          days: v,
        });
      },
    },
    timeSpent: {
      get() {
        return this.evaluation.timeSpent;
      },
      set(v) {
        this.$store.commit("setEvaluationTimeSpent", {
          key: this.evaluation.key,
          time: v,
        });
      },
    },
    comment: {
      get() {
        return this.evaluation.comment;
      },
      set(v) {
        this.$store.commit("setEvaluationComment", {
          key: this.evaluation.key,
          comment: v,
        });
      },
    },
  },
  methods: {
    ISOToDatetime,
    listAllStatus() {
      console.log("load all status");
      let url = `/api/`;
      fetch(url).then((response) => {
        if (response.ok) {
          return response.json();
        }
        throw { m: "yeeah", s: response.status, b: response.body };
      });
    },
    buildEditLink(document) {
      return (
        `/chill/wopi/edit/${document.storedObject.uuid}?returnPath=` +
        encodeURIComponent(
          window.location.pathname +
            window.location.search +
            window.location.hash,
        )
      );
    },
    submitBeforeLeaveToEditor() {
      console.log("submit beore edit 2");
      // empty callback
      const callback = () => null;
      return this.$store.dispatch("submit", callback).catch((e) => {
        console.log(e);
        throw e;
      });
    },
    submitBeforeEdit(storedObject) {
      const callback = (data) => {
        let evaluation = data.accompanyingPeriodWorkEvaluations.find(
          (e) => e.key === this.evaluation.key,
        );
        let document = evaluation.documents.find(
          (d) => d.storedObject.id === storedObject.id,
        );
        //console.log('=> document', document);
        window.location.assign(this.buildEditLink(document));
      };
      return this.$store.dispatch("submit", callback).catch((e) => {
        console.log(e);
        throw e;
      });
    },
    submitBeforeGenerate({ template }) {
      const callback = (data) => {
        let evaluationId = data.accompanyingPeriodWorkEvaluations.find(
          (e) => e.key === this.evaluation.key,
        ).id;

        window.location.assign(
          buildLink(
            template,
            evaluationId,
            "Chill\\PersonBundle\\Entity\\AccompanyingPeriod\\AccompanyingPeriodWorkEvaluation",
          ),
        );
      };

      return this.$store.dispatch("submit", callback).catch((e) => {
        console.log(e);
        throw e;
      });
    },
    onInputDocumentTitle(event) {
      const id = Number(event.target.id);
      const key = Number(event.target.dataset.key) + 1;
      const title = event.target.value;
      this.$store.commit("updateDocumentTitle", {
        id: id,
        key: key,
        evaluationKey: this.evaluation.key,
        title: title,
      });
    },
    addDocument({ stored_object, stored_object_version, file_name }) {
      let document = {
        type: "accompanying_period_work_evaluation_document",
        storedObject: stored_object,
        title: file_name,
      };
      this.$store.commit("addDocument", {
        key: this.evaluation.key,
        document,
        stored_object_version,
      });
    },
    /**
     * 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}
     */
    replaceDocument(oldDocument, storedObject, storedObjectVersion) {
      let document = {
        type: "accompanying_period_work_evaluation_document",
        storedObject: storedObject,
        title: oldDocument.title,
      };
      this.$store.commit("replaceDocument", {
        key: this.evaluation.key,
        document,
        oldDocument: oldDocument,
        stored_object_version: storedObjectVersion,
      });
    },
    removeDocument(document) {
      if (
        window.confirm(
          'Êtes-vous sûr·e de vouloir supprimer le document qui a pour titre "' +
            document.title +
            '" ?',
        )
      ) {
        this.$store.commit("removeDocument", {
          key: this.evaluation.key,
          document: document,
        });
      }
    },
    duplicateDocument(document) {
      this.$store.dispatch("duplicateDocument", {
        evaluation_key: this.evaluation.key,
        document: document,
      });
    },
    onStatusDocumentChanged(newStatus) {
      console.log("onStatusDocumentChanged", newStatus);
      this.$store.commit("statusDocumentChanged", {
        key: this.evaluation.key,
        newStatus: newStatus,
      });
    },
    goToGenerateWorkflowEvaluationDocument({ workflowName, payload }) {
      const callback = (data) => {
        let evaluation = data.accompanyingPeriodWorkEvaluations.find(
          (e) => e.key === this.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 this.$store.dispatch("submit", callback).catch((e) => {
        console.log(e);
        throw e;
      });
    },
    goToGenerateDocumentNotification(document, tos) {
      const callback = (data) => {
        let evaluation = data.accompanyingPeriodWorkEvaluations.find(
          (e) => e.key === this.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
              ? this.$store.state.work.accompanyingPeriod.user.id
              : null,
            window.location.pathname +
              window.location.search +
              window.location.hash,
          ),
        );
      };
      return this.$store.dispatch("submit", callback).catch((e) => {
        console.log(e);
        throw e;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
input.document-title {
  font-weight: bold;
  font-size: 1rem;
}
ul.document-upload {
  justify-content: flex-start;
}

.bg-blink {
  color: #050000;
  padding: 10px;
  display: inline-block;
  border-radius: 5px;
  animation: blinkingBackground 2.2s infinite;
  animation-iteration-count: 2;
}

@keyframes blinkingBackground {
  0% {
    background-color: #ed776d;
  }
  50% {
    background-color: #ffffff;
  }
  100% {
    background-color: #ed776d;
  }
}
</style>
