import AdmVue from '@assets/js/adm-vue';
import initVue from '@assets/js/initVue';

import getNumbersFromStringWithMask from '@assets/js/getNumbersFromStringWithMask';
import { brazilCurrency } from '@assets/js/filters';
import TextWithVar from '@assets/js/valid-text-with-vars';
import dinamicPriceModels from '@assets/js/dinamicPriceModels';

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'),
  },
  data() {
    return {
      configurations: {},
      customerGroups: {},
      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;
      }

      const dataPreview = {
        discountPrice: brazilCurrency(this.discountPrice),
        parcelNumber: this.configurations.parcel_number ? this.configurations.parcel_number : 3,
        parcelPrice: brazilCurrency(this.parcelPrice),
        discountValue: getNumbersFromStringWithMask(String(this.configurations.discount_value)),
      };

      const parcelNumber = this.configurations.parcel_number ? this.configurations.parcel_number : 3,
        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: dataPreview.parcelNumber,
        parcelPrice: dataPreview.parcelPrice,
        discountValue: dataPreview.discountValue,
      });

      const models = dinamicPriceModels({
        discountPrice: dataPreview.discountPrice,
        parcelNumber: dataPreview.parcelNumber,
        parcelPrice: dataPreview.parcelPrice,
        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() {
      const parcelNumber = this.configurations.parcel_number,
        parcelPrice = 100 / parcelNumber;
      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];
    },
    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);
