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'),
  },
  data() {
    return {
      configurations: {},
      customerGroups: {},
      table_parcels: {},
      updateComponent: 0,
      disableForm: false,
      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' },
      ],
    };
  },
  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.handleTypeDiscount();

      return flag;
    },
    dinamicPrice() {
      if (!this.configurations.preco_dinamico_personalized || this.configurations.advanced_config == 1) {
        return;
      }
      
      this.$nextTick(() => {
        if(this.configurations.model == "billet" || this.configurations.model == "custom"){
         this.$refs.cash_discount.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');
          }
          
          if(this.$refs.discount_parcels && Number(this.configurations.parcel_with_discounts) > 0){
            this.$refs.discount_parcels.classList.remove('hidden');
          }
        }
      });

      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);

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

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

      const custom = this.replaceCustom(this.configurations.preco_dinamico_personalized, {
        discountPrice: `' . $preco_discount . '`,
        parcelNumber: parcelNumber,
        parcelPrice: `' . $preco_parcelado . '`,
        discountValue: discountValue,
      });

      const customPromotion = this.replaceCustom(this.configurations.preco_dinamico_personalized, {
        discountPrice: `' . $preco_promo_discount . '`,
        parcelNumber: parcelNumber,
        parcelPrice: `' . $preco_parcelado_promo . '`,
        discountValue: discountValue,
      });

      const customPreview = this.replaceCustom(this.configurations.preco_dinamico_personalized, {
        discountPrice: dataPreview.discountPrice,
        parcelNumber: parcelNumber,
        parcelPrice: dataPreview.parcelPrice,
        discountValue: dataPreview.discountValue,
      });

      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,
      });

      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;
        }
      }
      return parcelPrice;

    },
    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;
    },
    stringContains() {
      const priceDinamicPersonalized = this.configurations.preco_dinamico_personalized;
      const personalizedInfo = [
        { name: 'Preço desconto', text: ' preco_desconto ', disabled: false },
        { name: 'Preço parcela', text: ' preco_parcela ', disabled: false },
        { name: 'Número de parcelas', text: ' numero_parcelas ', disabled: false },
        { name: 'Desconto em R$ ou %', text: ' desconto ', disabled: false },
      ];

      personalizedInfo.map(item => {
        item.disabled = priceDinamicPersonalized.includes(item.text);
      });

      return personalizedInfo;
    },
  },
  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é {{ numero_parcelas }}x sem juros de {{ preco_parcela }}';

    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];
    },
    async setTableParcels() {
      if (this.configurations.model == 'parcel' || this.configurations.model == 'complete') {
        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 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;

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

        if (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,
            })
          })
            .then(({ data }) => {
              if (data) {
                this.table_parcels.parcels = data;
                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{
          await axiosApi({
            method: 'post',
            url,
            data: param({
              productPrice: 100,
              parcel_number: 0,
              parcel_with_discounts: 0,
              discount_parcels_value,
              parcel_with_no_fees: 0,
              increase_value,
            })
          })
            .then(({ data }) => {
              if (data) {
                this.table_parcels.parcels = data;
                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;
            })
            .catch(err => {
              console.log(err);
            })
        }
      }
    },
    replaceCustom(value, variable) {
      let replacedValue = value;
      replacedValue = replacedValue.replace('{{ preco_desconto }}', variable.discountPrice);
      replacedValue = replacedValue.replace('{{ numero_parcelas }}', variable.parcelNumber);
      replacedValue = replacedValue.replace('{{ preco_parcela }}', variable.parcelPrice);
      replacedValue = replacedValue.replace('{{ desconto }}', variable.discountValue);

      return replacedValue;
    },
    addElement(element) {
      this.textWithVar.insertVarNameInText(element);
    },
    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;
        }
      }
    },
  },
});

initVue(vm);
