var VPEditor = (function () {
  return {
    name: "editor-soal",
    props: ["tinymcekey", "bankid"],
    template: "#main-template",
    data() {
      return {
        fabs: false,
        autoSave: false,
        jenis: "pg",
        errMsg: "",
        coupleColors: ["primary", "success", "info", "warning", "danger"],
        soals: {
          limit: 5,
          data: [],
          loading: false,
          loaded: false,
          onsave: false,
          saveque: false,
          xhr: null,
          lastFetch: 0,
        },
        videoMime: [
          'video/x-flv', 'video/mp4', 'application/x-mpegURL',
          'video/MP2T', 'video/3gpp', 'video/quicktime',
          'video/x-msvideo', 'video/x-ms-wmv', 'audio/mpeg'],
        audioMime: ['audio/mpeg'],
        imageMime: ['image/png', 'image/jpeg', 'image/webp'],
        files: {},
        storageListener: null,
        soalActive: null,
        editorID: {},
        banksSoal: {
          soals: {
            query: "",
            data: [],
          },
          listSoals: {
            query: "",
            data: [],
          },
          bankId: null,
          loading: false,
        },
        tinymce: {
          external_plugins: {
            formula: `${this.$store.state.config.base_url}/vendors/tinymce-formula/plugin.min.js`,
          },
          formula: {
            mlang: "mml",
          },
          inline: true,
          // Necessary
          htmlAllowedTags: [".*"],
          htmlAllowedAttrs: [".*"],

          // We recommend to set 'draggable_modal' to true to avoid overlapping issues
          // with the different UI modal dialog windows implementations between core and third-party plugins on TinyMCE.
          draggable_modal: true,

          // You could set a different language for MathType editor:
          // language: 'fr_FR',
          // mathTypeParameters: {
          //   editorParameters: { language: 'fr' },
          // },
          images_upload_handler: this.images_upload_handler,
          plugins: [
            "advlist autolink lists link image charmap print preview anchor",
            "searchreplace visualblocks code fullscreen formula directionality",
            "insertdatetime media table powerpaste hr help wordcount",
          ],
          contextmenu: "paste pastetext copy cut",
          // paste_as_text: true,
          powerpaste_allow_local_images: true,
          powerpaste_word_import: "prompt",
          powerpaste_html_import: "prompt",
          paste_data_images: true,

          toolbar:
            "paste bold italic strikethrough link numlist bullist blockquote ltr rtl | image media attachment formula",
          setup: (editor) => {
            editor.on("keydown", this.shortcut);
            editor.ui.registry.addButton("attachment", {
              icon: "browse",
              onAction: (_) => {
                // SOAL
                // editor.dom.settings.root_element.offsetParent
                this.$refs.fileInput.click();
              },
            });
          },
        },
        cancelToken: axios.CancelToken,
      };
    },
    mounted() {
      document.querySelector("body").onkeydown = this.shortcut;
      this.initListener();
      this.loadSoals();
      setInterval(() => {
        if (this.soals.saveque) {
          this.soals.saveque = false;
          if (!this.autoSave) return;
          this.saveSoals();
        }
      }, 5000);
      window.onbeforeunload = () => {
        if (this.soals.saveque || this.soals.onsave) return "Soal belum tersimpan, yakin untuk meninggalkan halaman?";
      }
      toastr.options.preventDuplicates = false;
    },
    computed: {
      fileMime() {
        return [].concat(this.audioMime, this.videoMime, this.imageMime)
      },
      soalsParsed: {
        get() {
          return this.soals.data;
        },
        set(v) {
          this.soals.data = v;
        },
      },
      banksSoalParsed: {
        get() {
          let data = this.banksSoal.soals.data;
          if (this.banksSoal.soals.query.length > 0) {
            let query = this.banksSoal.soals.query.toLowerCase();
            data = data.filter((v) => {

              if (v.kode.toLowerCase().includes(query)) return true;
              if (v.created_by.toLowerCase().includes(query)) return true;
              if ((v.deskripsi || '').toLowerCase().includes(query)) return true;
              return false;
            });
          }
          return data;
        },
        set(v) {
          this.banksSoal.soals.data = v;
        },
      },
      banksSoalListParsed: {
        get() {
          let data = this.banksSoal.listSoals.data;
          if (this.banksSoal.listSoals.query.length > 0) {
            let query = this.banksSoal.listSoals.query.toLowerCase();
            data = data.filter((v) => {
              if (v.question.toLowerCase().includes(query)) return true;
              if ((v.shortentry || '').toLowerCase().includes(query)) return true;
              for (let opt in data.options) {
                if ((opt.body || '').toLowerCase().includes(query)) return true;
              }
              return false;
            });
          }
          return data;
        },
        set(v) {
          this.banksSoal.listSoals.data = v;
        },
      },
    },
    watch: {
      storageListener(v) {
        if (this.soals.loaded && this.autoSave) this.saveSoals();
      },
      soalsParsed(v) {
        this.saveToLocal();
      },
    },
    methods: {
      initListener() {
        window.onscroll = () => {
          if ((window.innerHeight + window.scrollY + 200) >= document.body.offsetHeight) {
            // you're at the bottom of the page
            this.loadSoals();
          }
        }
        $(document).on('change.select2', (e) => {
          let result = $(e.target).val();
          if (result.constructor !== Array) return;
          id = $(e.target).data('id');
          let soal = this.soals.data.find(s => s.id == id);
          if (!soal) return;
          soal.updated_at = this.timestamp();
          this.saveToLocal();
        });
      },
      timestamp() {
        return moment().unix();
      },
      setLocalStorage(index, value) {
        window.localStorage.setItem(index, value);
        this.storageListener = this.timestamp() + Math.floor(Math.random() * 1000);
      },
      loadSoals(successCallback = null, errorCallback = null) {
        if (this.soals.loading || this.soals.lastFetch >= moment().unix()) return;
        let localSoals = window.localStorage.getItem("bank-soal/" + this.bankid);
        if (localSoals) localSoals = JSON.parse(localSoals);
        else localSoals = [];
        this.soals.loading = true;
        let url = this.$store.state.config.base_url + "/panel/bank-soal/editor/" + this.bankid + "/soals";
        url += "?limit=" + this.soals.limit;
        url += "&notIds=" + this.soalsParsed.map(s => s.id).join(",");
        axios({
          method: "get",
          url: url,
        })
          .then(
            (response) => {
              if (!isObject(response.data))
                return toastr.error(gaem({ response }, response.data), "Gagal memuat soal dari server");
              if (!response.data)
                return toastr.error("Data tidak ditemukan", "Gagal memuat soal dari server");
              response.data.forEach(v => {
                let ls = localSoals.find(s => s.id == v.id);
                if (!ls) return this.soalsParsed.push(v);
                if (ls.updated_at < parseInt(v.updated_at)) return this.soalsParsed.push(v);
                return this.soalsParsed.push(ls);
              });
              window.localStorage.setItem("bank-soal/" + this.bankid, JSON.stringify(this.soalsParsed));
              this.soals.loaded = true;
              this.soals.lastFetch = response.data.length == 0 ? moment().add('5', 'minutes').unix() : moment().unix();
              if (successCallback) successCallback(response);
            },
            (error) => {
              toastr.error(gaem(error), "Gagal memuat soal dari server");
              setTimeout(() => this.loadSoals(), 1000);
              if (errorCallback) errorCallback(error);
            }
          )
          .finally(() => (this.soals.loading = false));
      },
      swalConfirm(onConfirm) {
        SwalDelete({
          params: { confirmButtonText: 'Ya, hapus soal!' },
          confirmed: onConfirm,
        });
      },
      hapus(id) {
        setTimeout(() => {
          toastr.info("Menghapus soal...");
          axios({
            method: "delete",
            data: { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value },
            url: this.$store.state.config.base_url + "/panel/bank-soal/editor/" + this.bankid + '/' + id,
          })
            .then(
              (response) => {
                toastr.success("Berhasil menghapus soal");
              },
              (error) => {
                toastr.error(gaem(error), "Gagal menghapus soal");
                this.hapus(id);
              }
            );
        }, 1000)
      },
      saveSoals(direct = false) {
        if (this.soals.onsave || !this.soals.loaded) return this.soals.saveque = true;
        this.soals.onsave = true;
        setTimeout(() => {
          toastr.info("Menyimpan soal...");
          let data = { [this.$store.state.config.csrf.name]: this.$store.state.config.csrf.value, };
          data.soals = [];
          let sp = this.soalsParsed;
          $('.card-soal').each(function (i) {
            let id = $(this).data('id');
            let s = sp.find(v => v.id == id);
            if (s) data.soals.push(s);
          });
          data.soals = JSON.stringify(data.soals);
          axios({
            method: "post",
            data: data,
            url: this.$store.state.config.base_url + "/panel/bank-soal/editor/" + this.bankid,
          })
            .then(
              (response) => {
                toastr.success("Berhasil menyimpan soal");
                if (response.data.newID.soal) {
                  for (let [oldID, newID] of Object.entries(response.data.newID.soal)) {
                    let soal = this.soalsParsed.filter(v => v.isnew).find(e => e.id == oldID);
                    if (!soal) return;
                    $('#soal-' + oldID).attr('data-id', newID);
                    $('#soal-' + oldID).data('id', newID);
                    soal.id = newID;
                    if (this.soalActive == oldID) this.soalActive = newID;
                    delete soal.isnew;
                  }
                }
                if (response.data.newID.couple) {
                  for (let [oldID, newID] of Object.entries(response.data.newID.couple)) {
                    let soal = this.soalsParsed
                      .filter(v => v.couples.length > 0)
                      .find(e => e.couples.find(c => c.id == oldID));
                    if (!soal) return;
                    soal.couples.map((c, ci) => {
                      if (c.id == oldID) {
                        c.id = newID;
                        delete c.isnew;
                        soal.options.map((o, oi) => {
                          if (o.soal_couple_id == oldID) o.soal_couple_id = newID;
                          return o;
                        })
                      }
                      return c;
                    });
                  }
                }
                if (response.data.newID.opsi) {
                  for (let [oldID, newID] of Object.entries(response.data.newID.opsi)) {
                    let soal = this.soalsParsed
                      .filter(v => v.options.length > 0)
                      .find(e => e.options.find(o => o.id == oldID));
                    if (!soal) return;
                    soal.options.map((o, oi) => {
                      if (o.id == oldID) {
                        o.id = newID;
                        delete o.isnew;
                      }
                      return o;
                    });
                  }
                }
                for (let k in response.data.images) {
                  let item = response.data.images[k];
                  let soal = this.soalsParsed.find(v => v.id == k);
                  if (!soal) continue;
                  if (soal.id == this.soalActive) continue;
                  item.q.forEach(v => {
                    soal.question = soal.question.replace(v[0], v[1]);
                  });
                  for (let ko in item.o) {
                    opt = soal.options.find(vo => vo.id == ko);
                    if (!opt) continue;
                    item.o[ko].forEach(o => {
                      opt.body = opt.body.replace(o[0], o[1]);
                    });
                  };
                  for (let kc in item.c) {
                    cpl = soal.couples.find(vc => vc.id == kc);
                    if (!cpl) continue;
                    item.c[kc].forEach(c => {
                      cpl.body = cpl.body.replace(c[0], c[1]);
                    });
                  };
                }
                window.localStorage.setItem("bank-soal/" + this.bankid, JSON.stringify(this.soalsParsed));
              },
              (error) => {
                toastr.error(gaem(error), "Gagal menyimpan soal");
              }
            ).finally(() => this.soals.onsave = false);
        }, direct ? 0 : 5000);
      },
      addSoal(jenis_soal) {
        let soal = {
          id: this.randomID(),
          editmode: false,
          isnew: true,
          options: [],
          couples: [],
          true_default_point: 1,
          false_default_point: 0,
          shortentry: "",
          question: "",
          updated_at: this.timestamp(),
          jenis_soal: jenis_soal,
        };
        switch (jenis_soal) {
          case "1":
            soal.options.push(this.opsiPG(soal.id));
            break;
          case "3":
            soal.options.push(this.opsiPG(soal.id));
            break;
          case "4":
            soal.option_selected = null;
            soal.couple_selected = null;
            soal.options.push({
              id: this.randomID(),
              soal_id: soal.id,
              isnew: true,
              soal_couple_id: null,
              body: "",
            });
            soal.couples.push({
              id: this.randomID(),
              soal_id: soal.id,
              isnew: true,
              body: "",
            });

            break;
          case "5":
            break;
          case "6":
            soal.options.push(this.opsiPG(soal.id));
            break;
        }
        let index = this.soalsParsed.findIndex(s => s.id == this.soalActive);
        if (index != -1) {
          this.soalsParsed.splice(index + 1, 0, soal);
          this.saveToLocal();
          setTimeout(() => {
            this.soalActive = soal.id;
            document.getElementById("soal-" + soal.id).scrollIntoView();
          }, 50);
        } else {
          this.soalsParsed.push(soal);
          this.saveToLocal();
          this.scrollToBottom();
        }
      },

      shortcut(e) {
        switch (true) {
          //   case e.ctrlKey && (e.key == 'F5' || e.key.toLowerCase() == 'r'):
          //     //Control + F5 . Refresh Soal
          //     e.preventDefault();
          //     this.currentSoal = this.currentSoal;
          //     break;
          case e.ctrlKey && e.key.toLowerCase() == 'i':
            //Control + i . Info Pintasan
            e.preventDefault();
            // $('.card-soal').each(function () {
            //   console.log($(this).data('id'));
            // });
            // console.log(this.soalsParsed);
            break;
          //   case e.ctrlKey && e.key.toLowerCase() == 's':
          //     //Control + s . Simpan soal
          //     e.preventDefault();
          //     this.simpanSoal();
          //     break;
          //   case e.ctrlKey && e.key.toLowerCase() == 'p':
          //     //Control + p . Tinjau semua soal
          //     e.preventDefault();
          //     document.getElementById('show-preview').click()
          //     break;
          //   case e.ctrlKey && e.key == 'ArrowLeft':
          //     e.preventDefault();
          //     //Control + Arrow Left . Soal sebelumnya
          //     let prev = document.getElementById('prev-soal');
          //     if (prev) prev.click();
          //     break;
          //   case e.ctrlKey && e.key == 'ArrowRight':
          //     e.preventDefault();
          //     //Control + Arrow Right . Soal selanjutnya
          //     let next = document.getElementById('next-soal');
          //     if (next) next.click();
          //     break;
          case e.ctrlKey &&
            e.altKey &&
            e.shiftKey &&
            e.key.toLowerCase() == "f":
            //Control + ALT + SHIFT + f . Lompat ke soal tertentu
            e.preventDefault();
            let index = parseInt(prompt("Menuju Soal Nomor?"));
            if (typeof index !== "number") return alert("Nomor tidak valid");
            if (typeof this.soalsParsed[index - 1] !== "undefined") {
              setTimeout(() => {
                this.soalActive = this.soalsParsed[index - 1].id;
                document
                  .getElementById("soal-" + this.soalsParsed[index - 1].id)
                  .scrollIntoView()
              }, 50);
              return;
            }
            if (this.soalsParsed.length < index) this.soals.limit = index;
            toastr.info("Memuat data soal");
            this.loadSoals((res) => {
              this.soals.limit = 5;
              if (typeof this.soalsParsed[index - 1] === "undefined") return Swal.fire('error', `Soal nomor ${index} tidak ada`, 'error');
              setTimeout(() => {
                this.soalActive = this.soalsParsed[index - 1].id;
                document
                  .getElementById("soal-" + this.soalsParsed[index - 1].id)
                  .scrollIntoView()
              }, 50);
            });
            break;
          case e.ctrlKey && e.key.toLowerCase() == 'p':
            //Control + ALT + SHIFT + plus . Tambah soal
            e.preventDefault();
            this.showPreview();
            break;
          //   case e.ctrlKey && e.shiftKey && e.key.toLowerCase() == 'a':
          //     //Control + SHIFT + a . Tambah jawaban
          //     e.preventDefault();
          //     let btnTJ = document.getElementById('btn-tambah-jawaban');
          //     if (!btnTJ) return;
          //     btnTJ.click();
          //     break;
          //   case e.ctrlKey && e.shiftKey && e.key.toLowerCase() == 'c':
          //     //Control + SHIFT + c . Tambah pertanyaan
          //     e.preventDefault();
          //     let btnTP = document.getElementById('btn-tambah-pertanyaan');
          //     if (!btnTP) return;
          //     btnTP.click();
          //     break;
          //   case e.ctrlKey && e.altKey && (e.code.includes('Digit') || e.code.includes('Numpad')):
          //     //Control + ALT + Digit . Menuju opsi
          //     e.preventDefault();
          //     let opsi = document.getElementById("panelsStayOpen-heading" + (parseInt(e.code.replace(/^\D+/g, '')) - 1));
          //     if (opsi) opsi.scrollIntoView();
          //     break;
          //   case e.ctrlKey:
          //     //Control + number . Menuju soal
          //     if (typeof this.compiledSoal[e.key] != 'undefined') {
          //       e.preventDefault();
          //       return this.currentSoal = this.compiledSoal[e.key].id;
          //     }
          //     break;
        }
      },
      optionPGCClick(sid, oid) {
        this.saveToLocal();
        let soal = this.soalsParsed.find((soal) => soal.id === sid);
        if (!soal) return;
        if (!soal.couple_selected && !soal.option_selected)
          return (soal.option_selected = oid);
        if (soal.option_selected) return (soal.option_selected = null);
        let opsi = soal.options.find((op) => op.id === oid);
        if (!opsi) return;
        if (opsi.soal_couple_id == soal.couple_selected) {
          soal.couple_selected = null;
          opsi.soal_couple_id = null;
          return;
        }
        soal.options.map((v) => {
          if (v.id != opsi.id && v.soal_couple_id == soal.couple_selected)
            v.soal_couple_id = null;
          return v;
        });
        opsi.soal_couple_id = soal.couple_selected;
        soal.couple_selected = null;
        soal.option_selected = null;
        soal.updated_at = this.timestamp();
      },

      couplePGCClick(sid, cid) {
        this.saveToLocal();
        let soal = this.soalsParsed.find((soal) => soal.id === sid);
        if (!soal) return;
        if (!soal.couple_selected && !soal.option_selected)
          return (soal.couple_selected = cid);
        if (soal.couple_selected) return (soal.couple_selected = null);
        if (!soal.option_selected) return (soal.couple_selected = null);
        let opsi = soal.options.find((op) => op.id === soal.option_selected);
        if (!opsi) return (soal.couple_selected = null);
        if (opsi.soal_couple_id == cid) {
          soal.option_selected = null;
          soal.couple_selected = null;
          opsi.soal_couple_id = null;
          return;
        }
        soal.options.map((v) => {
          if (v.id != opsi.id && v.soal_couple_id == cid) v.soal_couple_id = null;
          return v;
        });
        opsi.soal_couple_id = cid;
        soal.couple_selected = null;
        soal.option_selected = null;
        soal.updated_at = this.timestamp();
      },

      questionPGC(id) {
        return {
          id: this.randomID(),
          soal_id: id,
          isnew: true,
          soal_couple_id: null,
          body: "",
        };
      },
      answerPGC(id) {
        return {
          id: this.randomID(),
          soal_id: id,
          isnew: true,
          body: "",
        };
      },
      opsiPG(id) {
        return {
          id: this.randomID(),
          soal_id: id,
          isnew: true,
          body: "",
          is_key: 0,
        };
      },
      duplikat(soal) {
        let s = JSON.parse(JSON.stringify(soal));
        s.id = this.randomID();
        s.isnew = true;
        let soalsParsed = [];
        let sp = this.soalsParsed;
        $('.card-soal').each(function (i) {
          let id = $(this).data('id');
          let soal = sp.find(v => v.id == id);
          if (soal) soalsParsed.push(soal);
        });
        let index = soalsParsed.findIndex(s => s.id === soal.id);
        let soals = JSON.parse(JSON.stringify(soalsParsed));
        let couples = {};
        if (s.couples) {
          s.couples = s.couples.map(c => {
            let nid = this.randomID();
            couples[c.id] = nid;
            c.id = nid;
            c.soal_id = s.id;
            c.isnew = true;
            return c;
          });
        }
        if (s.options) {
          s.options = s.options.map(o => {
            o.isnew = true;
            o.soal_id = s.id;
            o.id = this.randomID();
            if (s.jenis_soal == '4') for (let [oid, nid] of Object.entries(couples)) if (oid == o.soal_couple_id) o.soal_couple_id = nid;
            return o;
          })
        }
        soals.splice(index + 1, 0, s);
        this.soalsParsed = soals;
        setTimeout(() => {
          this.soalActive = s.id;
          document.getElementById("soal-" + s.id).scrollIntoView();
        }, 50);
      },
      duplikatBank(listSoal) {
        if (listSoal.length == 0) return;
        listSoal.forEach((soal, si) => {
          let s = JSON.parse(JSON.stringify(soal));
          s.id = this.randomID();
          s.isnew = true;
          let couples = {};
          if (s.couples) {
            s.couples = s.couples.map(c => {
              let nid = this.randomID();
              couples[c.id] = nid;
              c.id = nid;
              c.soal_id = s.id;
              c.isnew = true;
              return c;
            });
          }
          if (s.options) {
            s.options = s.options.map(o => {
              o.isnew = true;
              o.soal_id = s.id;
              o.id = this.randomID();
              if (s.jenis_soal == '4') for (let [oid, nid] of Object.entries(couples)) if (oid == o.soal_couple_id) o.soal_couple_id = nid;
              return o;
            })
          }
          this.soalsParsed.push(s);
          if (si == listSoal.length - 1) {
            setTimeout(() => {
              this.soalActive = s.id;
              document.getElementById("soal-" + s.id).scrollIntoView();
            }, 50);
          }
        });
      },
      cariBankSoal() {
        let mdl = new bootstrap.Modal(this.$refs['mdl-bank-soal']);
        mdl.toggle();
        this.loadBankSoal();
      },
      loadBankSoal() {
        if (this.banksSoal.loading) return;
        this.banksSoal.loading = true;
        let url = this.$store.state.config.base_url + "/panel/bank-soal/all";
        this.banksSoal.soals.data = [];
        axios({
          method: "get",
          url: url,
        })
          .then(
            (response) => {
              if (!isObject(response.data))
                return toastr.error(gaem({ response }, response.data), "Gagal memuat soal dari server");
              if (!response.data)
                return toastr.error("Data tidak ditemukan", "Gagal memuat soal dari server");
              this.banksSoal.soals.data = response.data.data.filter(v => v.id != this.bankid);
            },
            (error) => {
              toastr.error(gaem(error), "Gagal memuat soal dari server");
            }
          )
          .finally(() => (this.banksSoal.loading = false));
      },
      cariBankSoalList(bankId) {
        this.$refs['mdl-btn-close-banksoal'].click();

        let mdl = new bootstrap.Modal(this.$refs['mdl-bank-soal-list']);
        mdl.toggle();
        if (bankId == null) bankId = this.banksSoal.bankId;
        else this.banksSoal.bankId = bankId;
        this.loadBankSoalList(bankId);
      },
      loadBankSoalList(bankId = null) {
        if (this.banksSoal.loading) return;
        this.banksSoal.loading = true;
        if (bankId == null) bankId = this.banksSoal.bankId;
        else this.banksSoal.bankId = bankId;
        this.banksSoal.listSoals.data = [];
        this.$refs['mdl-btn-close-banksoal'].click();
        let url = this.$store.state.config.base_url + "/panel/bank-soal/editor/" + bankId + "/soals";
        axios({
          method: "get",
          url: url,
        })
          .then(
            (response) => {
              if (!isObject(response.data))
                return toastr.error(gaem({ response }, response.data), "Gagal memuat soal dari server");
              if (!response.data)
                return toastr.error("Data tidak ditemukan", "Gagal memuat soal dari server");
              this.banksSoal.listSoals.data = response.data;
            },
            (error) => {
              toastr.error(gaem(error), "Gagal memuat soal dari server");
            }
          )
          .finally(() => (this.banksSoal.loading = false));
      },
      scrollToBottom(timeout = 80) {
        setTimeout(() => {
          document
            .getElementById(
              "soal-" + this.soalsParsed[this.soalsParsed.length - 1].id
            )
            .scrollIntoView();
        }, timeout);
      },
      setFocus(id) {
        let soal = null;
        this.soalsParsed.map((s) => {
          s.editmode = s.id == id;
          if (s.editmode) soal = s;
        });
        if (!soal) return;
        document
          .getElementById("soal-" + id)
          .scrollIntoView();
      },
      saveToLocal() {
        let soals = JSON.stringify(this.soals.data);
        this.setLocalStorage("bank-soal/" + this.bankid, soals)
      },
      addSoalTemp() {
        let soals = this.soalsParsed.reverse();
        soals.push({
          id: Math.round(Math.random()),
          editmode: true,
          isnew: true,
        });
        soals.reverse();
      },
      randomID() {
        return "00" + Math.floor(Math.random() * 100);
      },
      showPreview() {
        let iframe = document.createElement("iframe");
        iframe.setAttribute('src', this.$store.state.config.base_url + '/panel/bank-soal/print/' + this.bankid);
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
        // window.open(this.$store.state.config.base_url + '/panel/bank-soal/print/' + this.bankid);
      },
      addAttachment(e) {
        let [file] = e.target.files || e.dataTransfer.files;
        if (!file) return this.$refs.fileInput.value = null;
        if (!this.fileMime.includes(file.type)) return toastr.error('Format tidak diizinkan');
        let taskId = Math.random().toString(36).substring(2, 10);
        this.files[taskId] = {};
        let task = this.files[taskId];
        task.editor = JSON.parse(JSON.stringify(this.editorID));
        task.status = 0;
        task.soal_id = `${this.soalActive}`;
        task.msg = '';
        task.name = file.name;
        task.type = file.type;
        task.source = this.cancelToken.source();
        let pattern = `{ATCM` + taskId + `}`;
        let onUploadProgress = event => {
          const percentCompleted = Math.round((event.loaded * 100) / event.total);
          task.percent = percentCompleted;
        }
        const formData = new FormData();
        formData.append([this.$store.state.config.csrf.name], this.$store.state.config.csrf.value);
        let url = this.$store.state.config.base_url + '/panel/bank-soal/files';
        formData.append('file', file);
        // if (task.type == 'audio/mpeg') {
        //   url = window.location.href + '/audioUploader';
        // } else {
        //   url = window.location.href + '/videoUploader';
        //   formData.append('video', file);
        // }
        let soal = this.soalsParsed.find(s => s.id == task.soal_id);
        this.$refs.fileInput.value = null;
        switch (task.editor.type) {
          case 1:
            soal.question += pattern;
            break;
          case 2:
            let opsi = soal.options.find(o => o.id == task.editor.id);
            if (!opsi) return delete this.files[taskId];
            opsi.body += pattern;
            break;
          case 3:
            let couple = soal.couples.find(o => o.id == task.editor.id);
            if (!couple) return delete this.files[taskId];
            couple.body += pattern;
            break;
        }
        axios({
          method: 'POST',
          data: formData,
          url,
          cancelToken: task.source.token,
          onUploadProgress
        }).then((response) => {
          if (!isObject(response.data)) {
            task.status = 2;
            return task.msg = gaem({ response }, response.data);
          }
          task.status = 1;
          soal = this.soalsParsed.find(s => s.id == task.soal_id);
          if (!soal) return delete this.files[taskId];
          switch (task.editor.type) {
            case 1:
              soal.question = soal.question.replace(pattern, response.data.html);
              break;
            case 2:
              let opsi = soal.options.find(o => o.id == task.editor.id);
              if (!opsi) return delete this.files[taskId];
              opsi.body = opsi.body.replace(pattern, response.data.html);
              break;
            case 3:
              let couple = soal.couples.find(o => o.id == task.editor.id);
              if (!couple) return delete this.files[taskId];
              couple.body = couple.body.replace(pattern, response.data.html);
              break;
          }
          this.saveToLocal();
        }, (error) => {
          soal = this.soalsParsed.find(s => s.id == task.soal_id);
          switch (task.editor.type) {
            case 1:
              soal.question = soal.question.replace(pattern, '');
              break;
            case 2:
              let opsi = soal.options.find(o => o.id == task.editor.id);
              if (!opsi) return delete this.files[taskId];
              opsi.body = opsi.body.replace(pattern, '');
              break;
            case 3:
              let couple = soal.couples.find(o => o.id == task.editor.id);
              if (!couple) return delete this.files[taskId];
              couple.body = couple.body.replace(pattern, '');
              break;
          }
          this.files[taskId].status = 2;
          if (!error.response) return this.files[taskId].msg = "Dibatalkan";
          return this.files[taskId].msg = gaem(error);
        })
      },
    },
  };
})();
