import AdmVue from "@assets/js/adm-vue";
import initVue from "@assets/js/initVue";
import getNumbersFromStringWithMask from "@assets/js/getNumbersFromStringWithMask";
import { brazilCurrency, number } from "@assets/js/filters";
import TextWithVar from "@assets/js/valid-text-with-vars";
import dinamicPriceModels from "@assets/js/dinamicPriceModels";
import axiosApi from "@assets/js/axios-api";

const vm = new AdmVue({
  components: {
    BaseCard: () =>
      import(/* webpackChunkName: "BaseCard" */ "@elements/BaseCard/index.vue"),
    BaseTabs: () =>
      import(
        /* webpackChunkName: "BaseTabs" */ "@components/BaseTabs/index.vue"
      ),
    HighlightEditor: () =>
      import(
        /* webpackChunkName: "HighlightEditor" */ "@components/HighlightEditor/index.vue"
      ),
    BasePopover: () =>
      import(
        /* webpackChunkName: "BasePopover" */ "@elements/BasePopover/index.vue"
      ),
    BaseInfo: () =>
      import(/* webpackChunkName: "BaseInfo" */ "@elements/BaseInfo/index.vue")
  },
  data() {
    return {
      configurations: {},
      customerGroups: {},
      table_parcels: {},
      updateComponent: 0,
      updateMinimumParcel: 0,
      disableForm: false,
      increaseinput: true,
      priceMinimal: null,
      disableInputNumberParcel: false,
      parcelWithMinimalValue: null,
      tabs: [
        { text: "Configurações", active: true },
        { text: "Tabelas de preços", active: false }
      ],
      modelOptions: [
        { name: "Completo", selected: true, flag: "complete" },
        { name: "Boleto", selected: false, flag: "billet" },
        { name: "Parcelado", selected: false, flag: "parcel" },
        { name: "Personalizado", selected: false, flag: "custom" }
      ],
      //infoDiscount: 'A quantidade máxima de parcelas sem juros consiste em somar o número de parcelas sem juros com o número de parcelas com desconto, assim trazendo a quantidade máxima de parcelas sem juros, pois, as parcelas com desconto também são parcelas sem juros.',
      //infoIncrease: 'A quantidade máxima de parcelas com juros sempre será a quantidade total de parcelas, pois, os juros só irão se aplicar desde que as parcelas com desconto e sem juros não estiverem sendo usadas.',
      infoIncreaseImg:
        "No exemplo acima temos a primeira e a segunda parcela sem juros, e por último a terceira parcela com juros aplicado. Caso o pedido seja finalizado utilizando o parcelamento em 1 ou 2 parcelas ambas serão sem juros, mas a partir da terceira parcela, os juros serão aplicados em todas elas, sendo assim teremos a quantidade máxima de parcelas com juros."
    };
  },
  filters: {
    brazilCurrency
  },
  watch: {},
  computed: {
    sendData() {
      return { ...this.configurations };
    },
    selectAll: {
      get() {
        const selectAll = this.customerGroups.filter(group => group.selected);
        return selectAll.length === this.customerGroups.length;
      },
      set(newValue) {
        const customerGroup = this.customerGroups.map(group => {
          group.selected = newValue;
          return group;
        });

        for (var customerGroupId in [...customerGroup]) {
          this.handleCheckBoxInput(
            customerGroup[customerGroupId]["customer_group_id"]
          );
        }

        this.customerGroup = [...customerGroup];
      }
    },
    discountMask() {
      const percentage = Type_Desconto.Tp_Porcentagem;

      return this.configurations.discount_type == percentage
        ? "percentage"
        : "brazilCurrency";
    },
    selectedModel() {
      const { flag } = this.modelOptions.find(
        modelsItem => modelsItem.selected
      );

      this.updateMinimumParcel += 1;

      this.handleTypeDiscount();

      return flag;
    },
    dinamicPrice() {
      if (
        !this.configurations.preco_dinamico_personalized ||
        this.configurations.advanced_config == 1
      ) {
        return;
      }

      this.changeInputVisibility();

      let minimum_parcel = this.configurations.minimum_parcel;
      let parcel_number = this.configurations.parcel_number;
      let parcel_with_no_fees = this.configurations.parcel_with_no_fees;
      let parcel_with_discounts = this.configurations.parcel_with_discounts;
      let increase_value = String(this.configurations.increase_value).includes(
        "%"
      )
        ? String(this.configurations.increase_value).replace("%", "")
        : this.configurations.increase_value;
      let discount_parcels = String(
        this.configurations.discount_parcels_value
      ).includes("%")
        ? String(this.configurations.discount_parcels_value).replace("%", "")
        : this.configurations.discount_parcels_value;
      let total_parcels =
        Number(parcel_with_no_fees) + Number(parcel_with_discounts);
      let minimal_parcels = this.parcelWithMinimalValue;

      const dataPreview = {
        discountPrice:
          this.discountPrice != 0
            ? brazilCurrency(this.discountPrice)
            : new Intl.NumberFormat("pt-BR", {
                style: "currency",
                currency: "BRL"
              }).format(0),
        parcelNumber: this.parcelWithMinimalValue
          ? minimal_parcels
          : total_parcels,
        parcelPrice: brazilCurrency(this.parcelPrice),
        discountValue: getNumbersFromStringWithMask(
          String(this.configurations.discount_value)
        )
      };

      const parcelNumber = parcel_number,
        discountValue = getNumbersFromStringWithMask(
          String(this.configurations.discount_value)
        ),
        discountParcelValue = getNumbersFromStringWithMask(
          String(this.configurations.discount_parcels_value)
        ),
        increaseParcelvalue = getNumbersFromStringWithMask(
          String(this.configurations.increase_value)
        ),
        discountType = this.configurations.discount_type,
        priceColor = this.price_color;

      const custom = this.replaceCustom(
        this.configurations.preco_dinamico_personalized,
        {
          discountPrice: `' . $preco_discount . '`,
          parcelNumber: parcelNumber,
          discountValue: discountValue
            ? this.configurations.discount_value
            : "0%",
          parcelWithNoFees: parcel_with_no_fees,
          parcelWithDiscount: parcel_with_discounts,
          discountParcelValue: discountParcelValue
            ? this.configurations.discount_parcels_value
            : "0%",
          increaseParcelvalue: increaseParcelvalue
            ? this.configurations.increase_value
            : "0%",
          parcel_with_increase: this.parcelIncrease(
            parcelNumber,
            parcel_with_no_fees,
            parcel_with_discounts
          ),
          price_parcel_with_no_fees: brazilCurrency(this.parcelNoFees),
          price_parcel_with_discount: brazilCurrency(this.parcelWithDiscount),
          price_parcel_with_increase: brazilCurrency(this.parcelWitIncrease),
          total_parcel_with_no_fees:
            Number(parcel_with_no_fees) + Number(parcel_with_discounts),
          total_parcel_with_fees:
            Number(parcel_with_no_fees) + Number(parcel_with_discounts) ===
            Number(parcelNumber)
              ? 0
              : parcelNumber
        }
      );

      const customView = this.replaceCustomView(
        this.configurations.preco_dinamico_personalized,
        {
          discountPrice: `' . $preco_discount . '`,
          parcelNumber: parcelNumber,
          discountValue: discountValue
            ? this.configurations.discount_value
            : "0%",
          parcelWithNoFees: parcel_with_no_fees,
          parcelWithDiscount: parcel_with_discounts,
          discountParcelValue: discountParcelValue
            ? this.configurations.discount_parcels_value
            : "0%",
          increaseParcelvalue: increaseParcelvalue
            ? this.configurations.increase_value
            : "0%",
          parcel_with_increase: this.parcelIncrease(
            parcelNumber,
            parcel_with_no_fees,
            parcel_with_discounts
          ),
          price_parcel_with_no_fees: brazilCurrency(this.parcelNoFees),
          price_parcel_with_discount: brazilCurrency(this.parcelWithDiscount),
          price_parcel_with_increase: brazilCurrency(this.parcelWitIncrease),
          total_parcel_with_no_fees:
            Number(parcel_with_no_fees) + Number(parcel_with_discounts),
          total_parcel_with_fees:
            Number(parcel_with_no_fees) + Number(parcel_with_discounts) ===
            Number(parcelNumber)
              ? 0
              : parcelNumber
        }
      );

      const customPromotion = this.replaceCustom(
        this.configurations.preco_dinamico_personalized,
        {
          discountPrice: `' . $preco_promo_discount . '`,
          parcelNumber: parcelNumber,
          parcelPrice: `' . $preco_parcelado_promo . '`,
          discountValue: discountValue
            ? this.configurations.discount_value
            : "0%",
          parcelWithNoFees: parcel_with_no_fees,
          parcelWithDiscount: parcel_with_discounts,
          discountParcelValue: discountParcelValue
            ? this.configurations.discount_parcels_value
            : "0%",
          increaseParcelvalue: increaseParcelvalue
            ? this.configurations.increase_value
            : "0%",
          parcel_with_increase: this.parcelIncrease(
            parcelNumber,
            parcel_with_no_fees,
            parcel_with_discounts
          ),
          price_parcel_with_no_fees: brazilCurrency(this.parcelNoFees),
          price_parcel_with_discount: brazilCurrency(this.parcelWithDiscount),
          price_parcel_with_increase: brazilCurrency(this.parcelWitIncrease),
          total_parcel_with_no_fees:
            Number(parcel_with_no_fees) + Number(parcel_with_discounts),
          total_parcel_with_fees:
            Number(parcel_with_no_fees) + Number(parcel_with_discounts) ===
            Number(parcelNumber)
              ? 0
              : parcelNumber
        }
      );

      const customPreview = this.replaceCustom(
        this.configurations.preco_dinamico_personalized,
        {
          discountPrice: dataPreview.discountPrice,
          parcelNumber: parcelNumber,
          discountValue: dataPreview.discountValue
            ? this.configurations.discount_value
            : "0%",
          parcelWithNoFees: parcel_with_no_fees,
          parcelWithDiscount: parcel_with_discounts,
          discountParcelValue: discountParcelValue
            ? this.configurations.discount_parcels_value
            : "0%",
          increaseParcelvalue: increaseParcelvalue
            ? this.configurations.increase_value
            : "0%",
          parcel_with_increase: this.parcelIncrease(
            parcelNumber,
            parcel_with_no_fees,
            parcel_with_discounts
          ),
          price_parcel_with_no_fees: brazilCurrency(this.parcelNoFees),
          price_parcel_with_discount: brazilCurrency(this.parcelWithDiscount),
          price_parcel_with_increase: brazilCurrency(this.parcelWitIncrease),
          total_parcel_with_no_fees:
            Number(parcel_with_no_fees) + Number(parcel_with_discounts),
          total_parcel_with_fees:
            Number(parcel_with_no_fees) + Number(parcel_with_discounts) ===
            Number(parcelNumber)
              ? 0
              : parcelNumber
        }
      );

      const models = dinamicPriceModels({
        discountPrice: dataPreview.discountPrice,
        parcelNumber: dataPreview.parcelNumber,
        parcelPrice: dataPreview.parcelPrice,
        totalParcels: parcel_number,
        increaseValue: increase_value,
        parcel_with_discounts,
        parcel_with_no_fees,
        discount_parcels,
        priceColor,
        custom,
        customPromotion,
        customPreview,
        discountType,
        discountValue,
        customView,
        minimumParcel: minimum_parcel
      });

      const { preview, product, exibition } = models[this.selectedModel];

      this.configurations.futura_preco_dinamico_produto = product;
      this.configurations.futura_preco_dinamico_exibicoes = exibition;

      return preview;
    },
    parcelPrice() {
      this.setTableParcels();

      let parcel_with_no_fees = this.configurations.parcel_with_no_fees;
      let parcel_with_discounts = this.configurations.parcel_with_discounts;
      let total_parcels =
        Number(parcel_with_no_fees) + Number(parcel_with_discounts);

      let parcelPrice;

      if (parcel_with_no_fees != 0) {
        parcelPrice = 100 / total_parcels;
      } else {
        let numberParcels = this.configurations.parcel_number;
        let increaseValue = String(this.configurations.increase_value).includes(
          "%"
        )
          ? String(this.configurations.increase_value).replace("%", "")
          : String(this.configurations.increase_value);
        let discontParcelsValue = String(
          this.configurations.discount_parcels_value
        ).includes("%")
          ? String(this.configurations.discount_parcels_value).replace("%", "")
          : String(this.configurations.discount_parcels_value);

        let total;

        if (parcel_with_discounts != 0) {
          total = 100 - 100 * (discontParcelsValue / 100);
          parcelPrice = total / parcel_with_discounts;
        } else {
          total = (
            100 * Math.pow(1 + increaseValue / 100, numberParcels)
          ).toFixed(2);
          parcelPrice = total / numberParcels;
        }
      }

      if (this.priceMinimal) {
        return parseFloat(String(this.priceMinimal).replace(",", "."));
      }

      return parcelPrice;
    },
    //PRICE PARCEL WITH NO FEES
    parcelNoFees() {
      let parcel_with_no_fees = Number(this.configurations.parcel_with_no_fees);
      let parcel_with_discounts = Number(
        this.configurations.parcel_with_discounts
      );
      let price = 100;

      if (parcel_with_no_fees || parcel_with_discounts) {
        let parcel_value =
          price / (parcel_with_no_fees + parcel_with_discounts);
        return parcel_value.toFixed(2);
      } else {
        let parcel_value = "0";
        return parcel_value;
      }
    },
    //PRICE PARCEL WITH DISCOUNT
    parcelWithDiscount() {
      let parcel_with_discounts = Number(
        this.configurations.parcel_with_discounts
      );

      if (parcel_with_discounts) {
        let discount_value = String(
          this.configurations.discount_parcels_value
        ).includes("%")
          ? String(this.configurations.discount_parcels_value)
              .replace("%", "")
              .replace(",", ".")
          : String(this.configurations.discount_parcels_value);
        discount_value = parseFloat(discount_value);
        let price = 100;
        let total = price - 100 * (discount_value / 100);
        let parcel_value = total / parcel_with_discounts;
        return parcel_value.toFixed(2);
      } else {
        let parcel_value = "0";
        return parcel_value;
      }
    },
    //PRICE PARCEL WITH INCREASE
    parcelWitIncrease() {
      let number_parcels = Number(this.configurations.parcel_number);
      let parcel_with_discounts = Number(
        this.configurations.parcel_with_discounts
      );
      let parcel_with_no_fees = Number(this.configurations.parcel_with_no_fees);
      let total_parcel =
        number_parcels - (parcel_with_discounts + parcel_with_no_fees);

      if (total_parcel) {
        let increase_value = String(
          this.configurations.increase_value
        ).includes("%")
          ? String(this.configurations.increase_value)
              .replace("%", "")
              .replace(",", ".")
          : String(this.configurations.increase_value);
        increase_value = parseFloat(increase_value);
        let price = 100;
        let total = price * Math.pow(1 + increase_value / 100, number_parcels);
        let parcel_value = total / number_parcels;
        return parcel_value.toFixed(2);
      } else {
        let parcel_value = "0";
        return parcel_value;
      }
    },
    discountPrice() {
      let discount = this.configurations.discount_value;

      if (typeof this.configurations.discount_value === "string") {
        discount = getNumbersFromStringWithMask(
          this.configurations.discount_value
        );
      }

      let discountPrice;
      if (this.discountMask === "brazilCurrency") {
        discountPrice = 100 - discount;
      } else {
        discountPrice = 100 - (100 * discount) / 100;
      }

      return discountPrice;
    },
    // TOTAl PRICE
    stringContainsTotalPrice() {
      const priceDinamicPersonalized = this.configurations
        .preco_dinamico_personalized;
      const personalizedInfo = [
        {
          name: "Preço com desconto (á vista)",
          text: " preco_desconto ",
          disabled: false
        },
        {
          name: "Preço parcela sem juros",
          text: " preco_parcela_sem_juros ",
          disabled: false
        },
        {
          name: "Preço parcela com descontos",
          text: " preco_parcela_com_desconto ",
          disabled: false
        },
        {
          name: "Preço parcela com juros",
          text: " preco_parcela_com_juros ",
          disabled: false
        }
      ];
      personalizedInfo.map(item => {
        item.disabled = priceDinamicPersonalized.includes(item.text);
      });
      return personalizedInfo;
    },
    //PARCEL NUMBER
    stringContainsParcelNumber() {
      const priceDinamicPersonalized2 = this.configurations
        .preco_dinamico_personalized;

      const personalizedInfo2 = [
        {
          name: "Número total de parcelas",
          text: " numero_total_parcelas ",
          disabled: false
        },
        {
          name: "Número de parcelas sem juros",
          text: " numero_parcelas_sem_juros ",
          disabled: false
        },
        {
          name: "Número de parcelas com descontos",
          text: " numero_parcelas_com_desconto ",
          disabled: false
        },
        {
          name: "Número de parcelas com juros",
          text: " numero_parcelas_com_juros ",
          disabled: false
        },
        {
          name: "Quantidade máxima de parcelas sem juros",
          text: " total_parcelas_sem_juros ",
          disabled: false
        },
        {
          name: "Quantidade máxima de parcelas com juros",
          text: " total_parcelas_com_juros ",
          disabled: false
        }
      ];
      personalizedInfo2.map(item => {
        item.disabled = priceDinamicPersonalized2.includes(item.text);
      });
      return personalizedInfo2;
    },
    //DESCOUNT AND INCREASE
    stringContainsDiscAndInc() {
      const priceDinamicPersonalized3 = this.configurations
        .preco_dinamico_personalized;
      const personalizedInfo3 = [
        {
          name: "Desconto em R$ ou % (á vista)",
          text: " desconto_dinheiro ",
          disabled: false
        },
        {
          name: "Desconto em % de parcelas",
          text: " desconto_em_parcelas ",
          disabled: false
        },
        {
          name: "Juros em % de parcelas",
          text: " juros_em_parcelas ",
          disabled: false
        }
      ];
      personalizedInfo3.map(item => {
        item.disabled = priceDinamicPersonalized3.includes(item.text);
      });
      return personalizedInfo3;
    }
  },
  mounted() {
    this.isLoading = false;
    this.configurations.preco_dinamico_personalized = this.configurations
      .preco_dinamico_personalized
      ? this.configurations.preco_dinamico_personalized
      : "{{ preco_desconto }} boleto à vista ou até {{ total_parcelas_sem_juros }}x sem juros de {{ preco_parcela_sem_juros }}";

    this.configurations = { ...this.configurations };
    setTimeout(() => {
      this.textWithVar = new TextWithVar(
        this.$refs.personalizedText.$refs.textarea
      );
    }, 400);

    this.modelOptions.map(item => {
      item.selected = item.flag == this.configurations.model;
      return item;
    });
  },
  methods: {
    handleSelectModel(index) {
      const models = this.modelOptions.map(modelsItem => {
        modelsItem.selected = false;
        return modelsItem;
      });

      models[index].selected = true;
      this.configurations.model = models[index].flag;

      this.modelOptions = [...models];
    },
    handleMinimumParcel(value) {
      this.configurations.minimum_parcel = value;
    },
    async setTableParcels() {
      const url = this.configurations.url_get_table_price;
      const parcel_number = this.configurations.parcel_number;
      const parcel_with_no_fees = this.configurations.parcel_with_no_fees;
      const parcel_with_discounts = this.configurations.parcel_with_discounts;

      const total_parcels =
        Number(parcel_with_no_fees) + Number(parcel_with_discounts);

      const increase_value = String(
        this.configurations.increase_value
      ).includes("%")
        ? String(this.configurations.increase_value).replace("%", "")
        : this.configurations.increase_value;

      const discount_parcels_value = String(
        this.configurations.discount_parcels_value
      ).includes("%")
        ? String(this.configurations.discount_parcels_value).replace("%", "")
        : this.configurations.discount_parcels_value;

      if (
        this.configurations.model == "parcel" &&
        this.configurations.minimum_parcel
      ) {
        const url = this.configurations.url_get_table_price;
        const minimum_parcel = this.configurations.minimum_parcel
          ? parseFloat(
              this.configurations.minimum_parcel
                .replace("R$ ", "")
                .replace(",", ".")
            )
          : null;

        await axiosApi({
          method: "post",
          url,
          data: param({
            productPrice: 100,
            parcel_number,
            parcel_with_discounts,
            discount_parcels_value,
            parcel_with_no_fees,
            increase_value,
            minimum_parcel
          })
        })
          .then(({ data }) => {
            if (data) {
              this.table_parcels.parcels = data.values;
              this.parcelWithMinimalValue = data.total_minimal_parcels;
              this.priceMinimal = data.price;

              this.table_parcels.amount_parcels = String(
                data.total_minimal_parcels
              );
              this.table_parcels.parcel_with_no_fees = String(
                data.total_parcel_no_fees
              );
              this.table_parcels.parcel_with_discounts = String(
                data.total_discount_parcels
              );
              this.table_parcels.discount_parcels_value = this.configurations.discount_parcels_value;
              this.table_parcels.increase_value = this.configurations.increase_value;
            }

            this.updateComponent += 1;
          })
          .catch(err => {
            console.log(err);
          });

        return;
      }

      if (
        this.configurations.model == "parcel" &&
        !this.configurations.minimum_parcel
      ) {
        await axiosApi({
          method: "post",
          url,
          data: param({
            productPrice: 100,
            parcel_number,
            parcel_with_discounts,
            discount_parcels_value,
            parcel_with_no_fees,
            increase_value,
            minimum_parcel: null
          })
        })
          .then(({ data }) => {
            if (data) {
              this.priceMinimal = null;
              this.table_parcels.parcels = data.values;
              this.parcelWithMinimalValue = null;

              this.table_parcels.amount_parcels = String(
                data.total_minimal_parcels
              );
              this.table_parcels.parcel_with_no_fees = String(
                data.total_parcel_no_fees
              );
              this.table_parcels.parcel_with_discounts = String(
                data.total_discount_parcels
              );
              this.table_parcels.discount_parcels_value = this.configurations.discount_parcels_value;
              this.table_parcels.increase_value = this.configurations.increase_value;
            }

            this.updateComponent += 1;
          })
          .catch(err => {
            console.log(err);
          });

        return;
      }

      if (
        (this.configurations.model == "complete" &&
          parcel_with_discounts &&
          parcel_with_no_fees &&
          increase_value &&
          discount_parcels_value &&
          total_parcels <= parcel_number) ||
        (this.configurations.model == "custom" &&
          parcel_with_discounts &&
          parcel_with_no_fees &&
          increase_value &&
          discount_parcels_value &&
          total_parcels <= parcel_number)
      ) {
        await axiosApi({
          method: "post",
          url,
          data: param({
            productPrice: 100,
            parcel_number,
            parcel_with_discounts,
            discount_parcels_value,
            parcel_with_no_fees,
            increase_value,
            minimum_parcel: null
          })
        })
          .then(({ data }) => {
            if (data) {
              this.priceMinimal = null;
              this.table_parcels.parcels = data.values;
              this.parcelWithMinimalValue = null;
              this.table_parcels.parcel_with_no_fees = this.configurations.parcel_with_no_fees;
              this.table_parcels.amount_parcels = this.configurations.parcel_number;
              this.table_parcels.parcel_with_discounts = this.configurations.parcel_with_discounts;
              this.table_parcels.discount_parcels_value = this.configurations.discount_parcels_value;
              this.table_parcels.increase_value = this.configurations.increase_value;
            }
            this.updateComponent += 1;
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        this.priceMinimal = null;
        this.parcelWithMinimalValue = null;
        this.table_parcels.parcels = [];
        this.table_parcels.parcel_with_no_fees = this.configurations.parcel_with_no_fees;
        this.table_parcels.amount_parcels = this.configurations.parcel_number;
        this.updateComponent += 1;
      }
    },
    changeInputVisibility() {
      this.$nextTick(() => {
        if (this.configurations.model == "billet") {
          this.$refs.cash_discount &&
            this.$refs.cash_discount.classList.remove("hidden");
          this.$refs.discount_parcels &&
            this.$refs.discount_parcels.classList.remove("hidden");
        } else {
          if (
            (this.$refs.increase &&
              Number(this.configurations.parcel_with_no_fees) ==
                Number(this.configurations.parcel_number)) ||
            Number(this.configurations.parcel_with_no_fees) >
              Number(this.configurations.parcel_number)
          ) {
            this.$refs.increase.classList.add("hidden");
          }

          if (
            this.$refs.increase &&
            Number(this.configurations.parcel_with_no_fees) <
              Number(this.configurations.parcel_number)
          ) {
            this.$refs.increase.classList.remove("hidden");
          }

          if (
            this.$refs.discount_parcels &&
            Number(this.configurations.parcel_with_discounts) == 0
          ) {
            this.$refs.discount_parcels.classList.add("hidden");
            this.configurations.discount_parcels_value = "0%";
          }

          if (
            this.$refs.discount_parcels &&
            Number(this.configurations.parcel_with_discounts) > 0
          ) {
            this.$refs.discount_parcels.classList.remove("hidden");
          }

          if (!this.increaseinput) this.configurations.increase_value = "0%";
        }
      });
    },
    replaceCustom(value, variable) {
      let replacedValue = value;

      replacedValue = replacedValue.replace(
        "{{ preco_desconto }}",
        variable.discountPrice
      );
      replacedValue = replacedValue.replace(
        "{{ preco_parcela_sem_juros }}",
        variable.price_parcel_with_no_fees
      );
      replacedValue = replacedValue.replace(
        "{{ preco_parcela_com_desconto }}",
        variable.price_parcel_with_discount
      );
      replacedValue = replacedValue.replace(
        "{{ preco_parcela_com_juros }}",
        variable.price_parcel_with_increase
      );
      replacedValue = replacedValue.replace(
        "{{ numero_total_parcelas }}",
        variable.parcelNumber
      );
      replacedValue = replacedValue.replace(
        "{{ numero_parcelas_sem_juros }}",
        variable.parcelWithNoFees
      );
      replacedValue = replacedValue.replace(
        "{{ numero_parcelas_com_desconto }}",
        variable.parcelWithDiscount
      );
      replacedValue = replacedValue.replace(
        "{{ numero_parcelas_com_juros }}",
        variable.parcel_with_increase
      );
      replacedValue = replacedValue.replace(
        "{{ total_parcelas_sem_juros }}",
        variable.total_parcel_with_no_fees
      );
      replacedValue = replacedValue.replace(
        "{{ total_parcelas_com_juros }}",
        variable.total_parcel_with_fees
      );
      replacedValue = replacedValue.replace(
        "{{ desconto_dinheiro }}",
        variable.discountValue
      );
      replacedValue = replacedValue.replace(
        "{{ desconto_em_parcelas }}",
        variable.discountParcelValue
      );
      replacedValue = replacedValue.replace(
        "{{ juros_em_parcelas }}",
        variable.increaseParcelvalue
      );

      return replacedValue;
    },
    replaceCustomView(value, variable) {
      let replacedValue = value;

      replacedValue = replacedValue.replace(
        "{{ preco_desconto }}",
        variable.discountPrice
      );
      replacedValue = replacedValue.replace(
        "{{ preco_parcela_sem_juros }}",
        "parcela_sem_juros"
      );
      replacedValue = replacedValue.replace(
        "{{ preco_parcela_com_desconto }}",
        "parcela_com_desconto"
      );
      replacedValue = replacedValue.replace(
        "{{ preco_parcela_com_juros }}",
        "parcela_com_juros"
      );
      replacedValue = replacedValue.replace(
        "{{ numero_total_parcelas }}",
        variable.parcelNumber
      );
      replacedValue = replacedValue.replace(
        "{{ numero_parcelas_sem_juros }}",
        variable.parcelWithNoFees
      );
      replacedValue = replacedValue.replace(
        "{{ numero_parcelas_com_desconto }}",
        variable.parcelWithDiscount
      );
      replacedValue = replacedValue.replace(
        "{{ numero_parcelas_com_juros }}",
        variable.parcel_with_increase
      );
      replacedValue = replacedValue.replace(
        "{{ total_parcelas_sem_juros }}",
        variable.total_parcel_with_no_fees
      );
      replacedValue = replacedValue.replace(
        "{{ total_parcelas_com_juros }}",
        variable.total_parcel_with_fees
      );
      replacedValue = replacedValue.replace(
        "{{ desconto_dinheiro }}",
        variable.discountValue
      );
      replacedValue = replacedValue.replace(
        "{{ desconto_em_parcelas }}",
        variable.discountParcelValue
      );
      replacedValue = replacedValue.replace(
        "{{ juros_em_parcelas }}",
        variable.increaseParcelvalue
      );

      return replacedValue;
    },
    addElement(element) {
      this.textWithVar.insertVarNameInText(element);
    },
    removeElement(info) {
      if (
        this.configurations.preco_dinamico_personalized.includes(`{{${info}}}`)
      ) {
        this.configurations.preco_dinamico_personalized = this.configurations.preco_dinamico_personalized.replace(
          `{{${info}}}`,
          ""
        );
      }
    },
    handleTypeDiscount() {
      const model = this.configurations.model;

      if (model != "custom") {
        this.configurations.discount_type = String(
          Type_Desconto.Tp_Porcentagem
        );
      }
    },
    handleCheckBoxInput(customer_group_id) {
      const apelidoId = this.configurations.preco_dinamico_tabelapreco; // checkbox

      if (!apelidoId[customer_group_id]) {
        apelidoId[customer_group_id] = customer_group_id;
      }
      this.configurations.preco_dinamico_tabelapreco = { ...apelidoId };

      for (var customerGroup in this.customerGroups) {
        if (!this.customerGroups[customerGroup].selected) {
          this.configurations.preco_dinamico_tabelapreco_apelido[
            this.customerGroups[customerGroup].customer_group_id
          ] = "";
          delete this.configurations.preco_dinamico_tabelapreco[
            this.customerGroups[customerGroup].customer_group_id
          ];
          this.customerGroups[customerGroup].selected = false;
        }
      }
    },
    parcelIncrease(parcelNumber, parcelDiscount, parcelFees) {
      var parcelIncrease =
        parseInt(parcelNumber) -
        (parseInt(parcelDiscount) + parseInt(parcelFees));
      if (parcelIncrease === 0) this.increaseinput = false;
      if (parcelIncrease != 0) this.increaseinput = true;
      if (parcelIncrease < 0) return "0";
      else return (parcelIncrease = parcelIncrease.toString());
    }
  }
});

initVue(vm);
