import AdmVue from "@assets/js/adm-vue";
import axiosApi from "@assets/js/axios-api";
import initVue from "@assets/js/initVue";
import param from "@assets/js/param";
import html2pdf from 'html2pdf.js';

const vm = new AdmVue({
  components: {
    BaseCard: () => import(/* webpackChunkName: "BaseCard" */ "@elements/BaseCard/index.vue"),
    BaseInputFile: () => import(/* webpackChunkName: "BaseInputFile" */ '@elements/BaseInputFile/index.vue'),
    BaseTabs: () => import(/* webpackChunkName: "BaseTabs" */ '@components/BaseTabs/index.vue'),
    BaseTextarea: () => import(/* webpackChunkName: "BaseTextarea" */ '@elements/BaseTextarea/index.vue'),
    GroupInput: () => import(/* webpackChunkName: "BaseTabs" */ '@components/GroupInput/index.vue'),
    BaseSelect: () => import(/* webpackChunkName: "BaseTabs" */ '@elements/BaseSelect/index.vue'),
    BaseButton: () => import(/* webpackChunkName: "Basebutton" */ '@elements/BaseButton/index.vue'),
  },
  data() {
    return {
      list: {

      },
      filters: {
        filterCart: '0',
        greaterthan: '',
        search: '',
      },
      btnSubmitLoading: false,
      btnSubmitLoading2: false,
      disableForm: false,

    };
  },
  computed: {
    sendData() {

      return {
        ...this.list, ...this.filters

      };

    },
  },
  methods: {
    setErrors(errors) {
      this.$refs.validationObserver.setErrors(errors);
    },
    formError(data) {
      const { errors } = data;
      this.$refs.validationObserver.setErrors(errors);
      if (errors.warning) {
        this.alert = {
          type: 'warning',
          message: errors.warning,
        };
      }
    },
    filter() {
      this.btnSubmitLoading = true;
      this.disableForm = true;

      axiosApi({
        method: 'POST',
        url: this.actionFilter,
        data: param({ filters: this.filters }),

      })
        .then(({ data }) => {
          if (data.list) {
            this.list = data.list;

          }
          this.btnSubmitLoading = false;
          this.disableForm = false;
        })
        .catch((err) => console.log(err, err.response))
    },

    generatePdf() {

      if (Object.keys(this.list).length === 0) {
        alert("Por favor, carregue os dados antes de gerar o PDF.");
        return;
      }

      this.btnSubmitLoading2 = true;

      const element = document.getElementById('relatorio_pdf');

      const allAreOneToOne = Object.keys(this.list).every(key => {
        const item = this.list[key];
        return item.total_quantity === 1 && item.total_carts === 1
      })

      if (allAreOneToOne) {
        alert("Não é possível gerar o PDF se existirem apenas produtos e carrinhos com quantidade 1 em ambos.")
        this.btnSubmitLoading2 = false;
        return
      } else {
        alert("Serão impressos apenas produtos com mais de 1 carrinho e 1 quantidade, pressione OK para continuar.")
      }
      //clona tabela
      const cloneElement = element.cloneNode(true);
      const rows = Array.from(cloneElement.querySelectorAll('.content-box.background-white.padding-medium.bottom-border-gray'));

      //remove 1 pra 1
      rows.forEach((row) => {

        const quantityElement = row.querySelector('.col-xs-2:nth-child(4) span');
        const cartsElement = row.querySelector('.col-xs-2:nth-child(5) span');
        const totalQuantity = quantityElement ? parseInt(quantityElement.textContent, 10) : null;
        const totalCarts = cartsElement ? parseInt(cartsElement.textContent, 10) : null;

        if (totalQuantity !== null && totalCarts !== null) {
          if (totalQuantity === 1 && totalCarts === 1) {
            row.remove()
          }
        }
      });

      const options = {
        margin: [10, 10, 10, 10],
        filename: "Relatorio.pdf",
        html2pdf: { scale: 2 },
        jsPDF: { unit: "mm", format: "a4", orientation: "portrait" },
        pagebreak: { mode: ['auto', 'css'] }
      };

      // gera o PDF com o conteúdo do clone  
      html2pdf().from(cloneElement).set(options).outputPdf().then(() => {
        this.btnSubmitLoading2 = false;
      }).save();
    }

  },
});

initVue(vm);

