<template lang="pug">
  medical-form-wrapper(
    :title="`${moment(value?.date).format('YYYY')} год`",
    :is-edit="isEdit",
    :open-edit="openEdit",
    :cancel="cancelEdit",
    :delete-item="deleteCard",
    :save="saveСhanges",
    :is-check-change="isCheckChange"
    )
    .flex.w-full.gap-x-4
      base-modal-showing-picture(
        v-model="isShowsPicture",
        :init-picture="value.pictures.find((el) => el.id === pictureId)",
        :list-pictures="value.pictures"
        )
      .flex.flex-col.gap-y-2.p-2.rounded.h-fit(
        v-if="value.pictures.length || isEdit",
        :style="{backgroundColor: 'var(--bg-light-grey)'}",
        )
        .pictures.gap-2(
          v-if="value.pictures.length"
          :class="{'edit': isEdit, 'no-edit': !isEdit, 'one-picture': value.pictures.length === 1}"
          )
          .photo.flex.relative(
            v-for="(picture, index) in value.pictures",
            )
            .photo-viewing.flex.absolute.rounded.cursor-pointer.w-full.h-full.items-center.justify-center(
              v-if="!isEdit",
              @click="() => showPicture(picture.id)"
              )
              img(src="@/assets/icons/whiteEye.svg" alt="eye")
            img.h-full.w-full.rounded.object-cover(:src="picture.photo")
            q-btn.absolute(
              v-if="isEdit",
              @click="() => deletePicture(picture.id)",
              round,
              dense,
              size="16px",
              padding="4px 4px 4px 4.5px",
              :style="{backgroundColor: 'var(--border-red-color)', top: '-8px', right: '-8px'}"
            )
              q-icon(
                name="app:cancel",
                size="8px",
                :style="{color: 'var(--default-white)'}"
                )
        label.download.flex.cursor-pointer.relative.items-center.justify-center.rounded(
          v-if="isEdit",
          )
          q-icon.absolute(
            name="app:download",
            size="24px"
            )
          base-input(
            @change="(e) => addNewFiles(e)",
            doc,
            type="file",
            accept="image/*",
            id="download",
            :style="{zIndex: '-1'}",
            borderless,
          )
      .flex.w-full.flex-col.gap-y-2
        .flex.font-semibold.text-sm(:style="{color: 'var(--font-grey-color)'}") Комментарий врача
        .flex.flex-col.rounded.h-full(
          :class="{'comments': isEdit}",
          :style="{padding: isEdit ? '12px 8px 12px 16px' : '0 0 0 12px'}"
          )
          .flex.flex-col.w-full
            .flex.items-center.gap-x-2(v-for="(comment, index) in value.comments")
              .flex.w-1.h-1.rounded-full(
                v-if="!isEdit",
                :style="{backgroundColor: 'var(--font-dark-blue-color)'}")
              q-input.comment.w-full(
                :ref="`comment-${index}`",
                :readonly="!isEdit",
                v-model="comment.text",
                borderless,
                autofocus,
                dense,
                :input-style="{'height': '18px', 'font-weight': '500'}"
                @keyup="(el) => switchСomment(el, index, comment.text)"
                )
</template>

<script>
import MedicalFormWrapper from "@/pages/newMedicalCard/components/MedicalFormWrapper.vue";
import BaseInput from "@/components/base/BaseInput";
import BaseModalShowingPicture from "@/components/base/BaseModalShowingPicture.vue";
import moment from "moment";
import { mapActions, mapGetters } from "vuex";
import { v_model } from "@/shared/mixins/v-model";

export default {
  name: "HealthStateForm",
  components: { MedicalFormWrapper, BaseModalShowingPicture, BaseInput },
  data() {
    return {
      moment,
      isEdit: false,
      isCheckChange: true,
      isShowsPicture: false,
      pictureId: "",
    };
  },
  mixins: [v_model],
  computed: {
    ...mapGetters({
      getHealthStateData: "getHealthStateData",
    }),
  },
  methods: {
    ...mapActions({
      deleteItemData: "deleteItemData",
    }),
    showPicture(id) {
      this.pictureId = id;
      this.isShowsPicture = true;
    },
    deleteCard() {
      this.deleteItemData({ stateKey: "healthState", itemId: this.value.id });
    },
    deletePicture(id) {
      this.value.pictures = this.value.pictures.filter((el) => el.id !== id);
    },
    addNewFiles(e) {
      Object.values(e.target.files).forEach((file) => {
        let reader = new FileReader();
        reader.onload = (e) => {
          this.value.pictures.push({
            photo: e.target.result,
            file: file,
            id: Math.random(),
          });
        };
        reader.readAsDataURL(file);
      });
      e.target.value = null;
    },
    openEdit() {
      this.isEdit = true;
    },
    cancelEdit() {
      this.value = this.getHealthStateData.find(
        (el) => el.id === this.value.id
      );
      this.isEdit = false;
    },
    saveСhanges() {
      this.value.comments = this.value.comments.filter((el) => el.text);
      this.isEdit = false;
    },
    switchСomment(event, index, comment) {
      if (event.code === "Enter") {
        event.target.blur();
        if (index + 1 === this.value.comments.length) {
          this.value.comments.push({ text: "" });
        }
      }
      if (event.code === "Backspace") {
        if (!comment && this.value.comments.length > 1) {
          this.value.comments = this.value.comments.filter(
            (_, i) => index !== i
          );
          this.$refs[`comment-${index - 1}`][0].focus();
        }
      }
    },
  },
};
</script>

<style lang="sass" scoped>
.pictures
  display: grid
  &.no-edit
    grid-template-columns: repeat(2, 104px)
    grid-auto-rows: 104px
    &.one-picture
      grid-template-columns: repeat(1, 104px)
  &.edit
    grid-template-columns: repeat(4, 40px)
    grid-auto-rows: 40px
.photo-viewing
  display: none
  background-color: var(--font-dark-blue-color-1)
  color: var(--default-white)
.photo
  &:hover .photo-viewing
    display: flex
.download
  min-height: 93px
  width: 216px
  border: 1px dashed var(--font-grey-color)
  background-color: var(--default-white)
  &:hover .q-icon
    opacity: 0.6
  & .q-icon
    color: var(--btn-blue-color)
.comments
  border: 1px solid var(--border-light-grey-color)
</style>

<style lang="sass">
.comment .q-field__inner .q-field__control
  height: 20px
</style>
