import Paginations from "@/components/Paginations";
import { Printd } from "printd";
import { baseURL } from "@/helpers/utils.js";
export const tableMixin = {
  components: {
    Paginations,
  },
  data: () => ({
    dataUrl: null,
    dataFilter: {
      from: new Date().toLocaleString("fr-CA", {}).slice(0, 10),
      to: new Date().toLocaleString("fr-CA", {}).slice(0, 10),
    },
    rows: [],
    PaymentMethodUsed: [],
    selectedRow: {},
    currentPage: 0,
    rowCountPage: 45,
    totalRows: 0,
    pageRange: 10,
    recordsFrom: 0,
    recordsTo: 0,
    displayMode: true,
    checkAll: false,
    checkedRows: [],
    bulkAction: null,
    filterKey: null,
  }),
  created() {
    if (this.dataUrl) {
      this.handleFetch(this.dataUrl);
    }
  },
  watch: {
    checkedRows() {
      var rows = this.$el.querySelectorAll(
        "input[type='checkbox'][id^='checkbox-']"
      );
      var checked = this.$el.querySelectorAll(
        "input[type='checkbox'][id^='checkbox-']:checked"
      );
      let checkAll = this.$el.querySelector("#checkAll");
      // console.log(checked.length != rows.length);
      if (checked.length != rows.length) {
        checkAll.setAttribute("checked", false);
      } else {
        checkAll.setAttribute("checked", true);
      }
    },
  },
  computed: {
    hasKeyword() {
      return this.filterKey != null && this.filterKey.trim().length >= 2;
    },
  },
  methods: {
    handleFetch(url) {
      // this.$store.commit("SET_AJAX_TASK", "GETTING_COMPONENT_DATA");
      this.$http.get(url).then((response) => {
        this.rows = response.data.rows.data;
        this.currentPage = response.data.rows.current_page;
        this.totalRows = response.data.rows.total;
        this.recordsFrom = response.data.rows.from;
        this.recordsTo = response.data.rows.to;
        this.PaymentMethodUsed = response.data.payments_methods;
      });
    },
    handlePagination(obj) {
      this.rowCountPage = Number(obj.per_page);
      let url = `${this.dataUrl}?page=${obj.page_number}&per_page=${obj.per_page}`;
      this.handleFetch(url);
    },
    limitCharacters(text, limit) {
      // Check if the text length is less than or equal to the limit
      if (text.length <= limit) {
        return text;
      }

      // Truncate the text and append an ellipsis
      return text.slice(0, limit) + "...";
    },
    NumInWords(number) {
      const first = [
        "",
        "one ",
        "two ",
        "three ",
        "four ",
        "five ",
        "six ",
        "seven ",
        "eight ",
        "nine ",
        "ten ",
        "eleven ",
        "twelve ",
        "thirteen ",
        "fourteen ",
        "fifteen ",
        "sixteen ",
        "seventeen ",
        "eighteen ",
        "nineteen ",
      ];
      const tens = [
        "",
        "",
        "twenty",
        "thirty",
        "forty",
        "fifty",
        "sixty",
        "seventy",
        "eighty",
        "ninety",
      ];
      const mad = ["", "thousand", "million", "billion", "trillion"];
      let word = "";

      for (let i = 0; i < mad.length; i++) {
        let tempNumber = number % (100 * Math.pow(1000, i));
        if (Math.floor(tempNumber / Math.pow(1000, i)) !== 0) {
          if (Math.floor(tempNumber / Math.pow(1000, i)) < 20) {
            word =
              first[Math.floor(tempNumber / Math.pow(1000, i))] +
              mad[i] +
              " " +
              word;
          } else {
            word =
              tens[Math.floor(tempNumber / (10 * Math.pow(1000, i)))] +
              "-" +
              first[Math.floor(tempNumber / Math.pow(1000, i)) % 10] +
              mad[i] +
              " " +
              word;
          }
        }

        tempNumber = number % Math.pow(1000, i + 1);
        if (Math.floor(tempNumber / (100 * Math.pow(1000, i))) !== 0)
          word =
            first[Math.floor(tempNumber / (100 * Math.pow(1000, i)))] +
            "hundred " +
            word;
      }

      return word + "FBU ONLY";
    },
    encodeQuery(url, data) {
      let query = "";
      for (let d in data) {
        if (
          !this.$helper.empty(data[d]) &&
          url.indexOf(`?${d}`) < 0 &&
          url.indexOf(`&${d}`) < 0
        )
          query +=
            encodeURIComponent(d) + "=" + encodeURIComponent(data[d]) + "&";
      }
      return url.indexOf("?") > -1
        ? `${url}&${query.slice(0, -1)}`
        : `${url}?${query.slice(0, -1)}`;
    },
    handleDataFilter() {
      let fetchUrl = this.encodeQuery(this.dataUrl, this.dataFilter);
      this.$store.commit("SET_AJAX_TASK", "PAGINATION_SEARCH");
      this.handleFetch(fetchUrl);
    },
    resetFilters() {
      this.dataFilter = {
        from: new Date().toLocaleString("fr-CA", {}).slice(0, 10),
        to: new Date().toLocaleString("fr-CA", {}).slice(0, 10),
      };
      this.handleFetch(this.dataUrl);
    },
    toggleCrudMode() {
      this.displayMode = !this.displayMode;
    },
    handleCheckAll() {
      var rows = this.$el.querySelectorAll(
        "input[type='checkbox'][id^='checkbox-']"
      );
      let checkAll = this.$el.querySelector("#checkAll");
      if (checkAll.checked)
        rows.forEach((elt) => {
          let value = elt.value;
          if (!this.checkedRows.includes(value)) {
            this.checkedRows.push(value);
          }
        });
      else this.checkedRows = [];
    },
    displayPicker(e) {
      e.target.showPicker();
    },
    printWithoutHeader(elementId, css = []) {
      const styles = [
        `${location.origin}/css/custom.css`,
        `${location.origin}/css/bootstrap.min.css`,
      ];
      const d = new Printd();
      const printEl = document.querySelector(elementId);
      d.print(printEl, [...styles, ...css]);
    },
    handlePrint(elementId, css = [], title = null, subtitle = "") {
      const pageTitle = title ? title : document.title;
      const styles = [
        `${location.origin}/css/custom.css`,
        `${location.origin}/css/bootstrap.min.css`,
      ];
      const d = new Printd();
      const header = `<style>
      #header,
      #footer {
        padding: 0 !important;
      }
    </style>
    <br>
    <table style="width: 100%; padding-left: 0px; padding-right: 0px; padding-top: 5px;margin: 0px!important;font-size: 15px; ">
      <tr>
        <td style="text-align:left; width:50%!important;">
          <div style="padding-left:10px;">
            <img src="/img/company.png" style="height:70px" />
          </div>
        </td>
        <td style="text-align:right; width:50%!important;font-size: 28px">
          <div style="padding-right: 18px;font-family:nunito">
            ${pageTitle}
            <br>
           ${subtitle}
          </div>
        </td>
      </tr>
    </table>
    <hr>
    `;
      const printEl = document.querySelector(elementId);
      var div = document.createElement("div");
      div.innerHTML = header.trim();
      printEl.parentElement.prepend(div);
      d.print(printEl.parentElement, [...styles, ...css]);
      setTimeout(() => {
        div.remove();
      }, 250);
    },
    handleExcelExport(tableId = null, excelFilename) {
      if (!tableId) {
        tableId = "table.table";
      } else {
        tableId = "#" + tableId;
      }
      let container = document.querySelector(tableId);
      let head = container.querySelector("thead");
      let headers = [
        ...head.querySelectorAll("th:not(.action):not(.check)"),
      ].map((item) => item.textContent);
      let dataset = [];
      [...container.querySelectorAll("tbody tr")].forEach((row) => {
        let arr = [...row.querySelectorAll("td:not(.action):not(.check)")].map(
          (item) => item.textContent
        );
        dataset.push(arr);
      });
      /**
       * Creating a temporary form
       */
      let dataForm = document.createElement("form");
      dataForm.target = "_blank";
      dataForm.method = "POST";
      dataForm.action = `${baseURL}shared/export/excel`;
      let records = document.createElement("input");
      let file_name = document.createElement("input");
      let headings = document.createElement("input");
      records.type = "hidden";
      file_name.type = "hidden";
      headings.type = "hidden";
      records.name = "dataset";
      records.value = JSON.stringify(dataset);
      file_name.name = "filename";
      file_name.value = excelFilename || document.title.replaceAll(" ", "-");
      headings.name = "columns";
      headings.value = JSON.stringify(headers);
      dataForm.appendChild(records);
      dataForm.appendChild(file_name);
      dataForm.appendChild(headings);
      dataForm.style.display = "none";
      document.body.appendChild(dataForm);
      dataForm.submit();
    },
  },
};
