<template>
  <div class="container">
    <the-content-loading v-if="fetchingData"></the-content-loading>
    <div v-else>
      <form class="section-form" role="section" @submit.prevent="save()">
        <div class="form-group">
          <label for="title">عنوان</label>
          <input
            type="text"
            class="form-control"
            id="title"
            name="title"
            v-model="form._source.title"
          />
        </div>

        <div class="form-group">
          <label for="title">عکس</label>
          <div class="form-group">
            <div
              class="image-uploader-container"
              :class="{ 'hide-preview': hasImage }"
            >
              <image-uploader
                ref="file-uploader"
                :preview="true"
                :debug="1"
                :maxWidth="300"
                :maxHeight="300"
                :maxSize="2"
                :quality="1"
                :autoRotate="true"
                outputFormat="file"
                accept="image/*"
                :className="['fileinput', { 'fileinput--loaded': hasImage }]"
                :capture="false"
                @input="setImage"
              >
                <label class="upload-label" for="fileInput" slot="upload-label">
                  <img
                    v-if="
                      form?._source.attachment &&
                      form?._source.attachment[0].link?.length &&
                      (getFileExtension(form?._source.attachment[0].link) ==
                        'png' ||
                        getFileExtension(form?._source.attachment[0].link) ==
                          'jpg' ||
                        getFileExtension(form?._source.attachment[0].link) ==
                          'jpeg')
                    "
                    :src="imageBaseUrl + form?._source.attachment[0].link"
                    class="img-fluid"
                    :alt="form?._source.attachment[0].link"
                  />

                  <span
                    v-else-if="
                      form?._source.attachment &&
                      form?._source.attachment[0].link?.length
                    "
                    class="tavasi"
                    :class="`tavasi-${getFileExtension(
                      form?._source.attachment[0].link
                    )}-file`"
                  ></span>

                  <!-- replace image src with incoming src -->

                  <span v-else class="tavasi tavasi-cloud-upload"></span>
                </label>
              </image-uploader>
            </div>
          </div>
        </div>

        <div class="form-group">
          <label for="title">متن</label>
          <!-- <my-quill
            ref="quill-editor"
            :parentButtonLoading="buttonLoading"
            :tinyText="form?._source.description"
            :showSaveButton="false"
          ></my-quill> -->
          <quill-editor
            ref="quill-editor"
            v-model="form._source.description"
            content-type="html"
            :options="editorOptions"
          ></quill-editor>
        </div>

        <div class="form-group d-flex">
          <div>
            <button
              v-if="form?._id"
              @click="onDeleteItem(form)"
              title="حذف"
              class="btn delete-btn btn-danger"
              type="button"
            >
              <svg class="icon icon-Component-295--1">
                <use xlink:href="#icon-Component-295--1"></use>
              </svg>

              حذف
            </button>
          </div>

          <div class="me-auto">
            <button
              :disabled="buttonLoading"
              @click.prevent="$emit('close-modal')"
              type="button"
              class="btn btn-default"
              data-dismiss="modal"
            >
              لغو
            </button>
            <button
              type="submit"
              class="btn btn-primary"
              :disabled="buttonLoading"
              @click.prevent="save()"
            >
              <the-button-loading
                v-if="buttonLoading"
                :style="{ transform: 'scale(0.5)' }"
              ></the-button-loading>
              ثبت
            </button>
          </div>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import adminApi from "~/apis/adminApi";
import repoApi from "~/apis/repoApi";
import notificationMixin from "~/mixins/notifications/notificationMixin";

export default {
  extends: notificationMixin,
  props: {
    formData: undefined,
  },
  mounted() {
    if (this.formData) this.form = this.formData;
  },
  created() {
    this.httpService = useNuxtApp()["$http"];
  },
  computed: {
    imageBaseUrl() {
      return import.meta.env.VITE_BASE_URL;
    },
  },

  // watch: {
  // $route: {
  //   handler: function () {
  //     this.$store.state.collapsed = false;
  //   },
  //   deep: true,
  //   immediate: true,
  // },
  // },
  data() {
    return {
      form: {
        _index: "",
        _type: "",
        _id: "",
        _score: 0,
        _source: {
          title: "",
          description: "",
          attachment: [
            {
              type: "",
              link: "",
              decription: "",
            },
          ],
          user_id: -1,
          username: "",
          entity_type: "",
          data_type: "",
          time_edit: 1111111111,
        },
      },
      httpService: {},
      hasImage: false,
      imageUrl: undefined,
      uploading: false,
      editorOptions: {
        theme: "snow", // تم ویرایشگر: 'snow' یا 'bubble'
        placeholder: "متن خود را بنویسید...",
        modules: {
          toolbar: [
            [{ header: [1, 2, 3, false] }], // سطح هدینگ‌ها
            ["bold", "italic", "underline", "strike"], // دکمه‌های استایل متن
            [{ color: [] }, { background: [] }], // رنگ متن و پس‌زمینه
            [{ list: "ordered" }, { list: "bullet" }], // لیست‌های شماره‌دار و نقطه‌ای
            ["blockquote", "code-block"], // نقل‌قول و کد
            [{ align: [] }], // تراز بندی متن
            ["link", "image", "video"], // افزودن لینک، تصویر، و ویدیو
            ["clean"], // حذف فرمت‌ها
          ],
        },
      },
    };
  },
  computed: {
    imageBaseUrl() {
      return import.meta.env.VITE_BASE_URL;
    },
  },
  methods: {
    setImage: function (file) {
      this.hasImage = true;
      this.imageUrl = file;
      this.saveFile(file);
    },
    getFileExtension(filename) {
      const validtypes = [
        "xlsx",
        "xls",
        "doc",
        "docx",
        "ppt",
        "pptx",
        "txt",
        "pdf",
        "jpg",
        "png",
        "jpeg",
      ];
      const fileExtension = filename?.split(".").pop();
      return validtypes.includes(fileExtension) ? fileExtension : "other";
    },
    saveFile(file) {
      if (this.uploading) return;
      this.uploading = true;

      let url = "public/entity/" + repoApi.entity.upload;
      const formData = new FormData();
      // formData.append('file', files)
      formData.append("file", file);

      this.httpService
        .postRequest(url, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((response) => {
          this.form._source.attachment[0].type = this.getFileExtension(
            file.name
          );
          this.form._source.attachment[0].link = response.file;
          this.form._source.attachment[0].decription = "";
        })

        .finally(() => {
          this.uploading = false;
        });
    },

    save() {
      if (this.buttonLoading) return;
      this.buttonLoading = true;

      this.form._source.description = this.$refs["quill-editor"].editorData;
      var url = adminApi.notification.add;

      if (this.form._id.length) {
        url = adminApi.notification.edit;
        url = url.replace("{{id}}", this.form._id);
      }

      const payload = {
        title: this.form._source.title,
        description: this.form._source.description,
        attachment: this.form._source.attachment,
      };

      this.httpService
        .postRequest(url, payload)
        .then((res) => {
          this.$emit("close-modal", true);

          mySwalToast({
            title: "تبریک",
            html: res.message,
            icon: "success",
          });
        })

        .finally(() => {
          this.buttonLoading = false;
        });
    },
    onDeleteItem(item) {
      mySwalConfirm({
        title: "هشدار!!!",
        html: "از حذف این مورد مطمئن هستید؟",
      }).then((result) => {
        if (result.isConfirmed) {
          this.deleteItem(item).then(() => {
            this.$emit("close-modal");
          });
        }
      });
    },
  },
};
</script>
<style lang="scss">
.picture-input input[type="file"],
#fileInput {
  display: none !important;
}

.image-uploader-container {
  position: relative;
  border: 2px dashed #eee;
  padding: 0.2em;

  &.hide-preview {
    .upload-label {
      position: absolute;
      right: 0;
      left: 0;
      top: 0;
      bottom: 0;
      width: auto !important;
      overflow: hidden;
    }

    .upload-label img {
      visibility: hidden;
    }
  }
  .img-preview {
    width: 300px;
    max-width: 100%;
    height: auto;
    max-height: 200px;
    object-fit: contain;
  }
}
</style>