import getDynamicTabsMixin from '@assets/js/getDynamicTabsMixin';
import formMixin from '@mixins/formMixin';
import { v4 as uuidv4 } from 'uuid';

const Type = require('@catalog/view/javascript/types.js');
const newPriceItemTitle = 'Nova configuração de preço';

const mixTab = getDynamicTabsMixin({ name: 'mktPrice', title: 'title' });

export default {
  name: 'MarketPrice',
  props: {
    marketPrice: {
      type: Object,
      required: true,
    },
    invalidForm: {
      type: Boolean,
      required: true,
    },
    loadingBtn: {
      type: Boolean,
      required: true,
    },
  },
  mixins: [mixTab, formMixin],
  components: {
    BaseCard: () => import(/* webpackChunkName: "BaseCard" */ '@elements/BaseCard/index.vue'),
    BaseTabs: () => import(/* webpackChunkName: "BaseTabs" */ '@components/BaseTabs/index.vue'),
    AsideContent: () => import(/* webpackChunkName: "AsideContent" */ '@components/AsideContent/index.vue'),
  },
  data() {
    return {
      newPriceItem: {
        id: '',
        marketplace_price_id: null,
        title: newPriceItemTitle,
        customer_group_id: '',
        standard: 0,
        tipo_integracao: this.marketPrice.tipo_integracao,
        marketplace_price_adjustments: [],
      },
      ...this.marketPrice,
      maxAjustments: 4,
    };
  },
  watch: {
    'marketPrice.mktpriceadjustments': function(val, oldVal) {
      this.mktPrice = val;
    },
  },
  created() {},
  beforeMount() {
    const { TypesForJs } = this;
    if (TypesForJs) {
      for (let i = 0; i < TypesForJs.length; i++) {
        this[TypesForJs[i].name] = new Type(TypesForJs[i]);
      }
    }

    if (this.marketPrice.mktpriceadjustments) {
      this.mktPrice = this.marketPrice.mktpriceadjustments.map(item => {
        const priceAdjustments = Array.isArray(item.marketplace_price_adjustments)
          ? item.marketplace_price_adjustments
          : [];

        return {
          marketplace_price_id: item.marketplace_price_id,
          title: item.title,
          customer_group_id: item.customer_group_id,
          standard: item.standard,
          tipo_integracao: item.tipo_integracao,
          marketplace_price_adjustments: priceAdjustments,
        };
      });
    } else {
      this.mktPrice = [];
    }
  },
  computed: {
    validateDuplicateAdjustment() {
      const result = { valid: [], message: 'Existem combinações de campos repetidas' };

      const tabActive = this.mktPriceTabs.findIndex(item => item.active);

      if (tabActive < 0) {
        return result;
      }

      let { marketplace_price_adjustments: adjustments } = this.mktPrice[tabActive];

      if (adjustments.length > 1) {
        adjustments = adjustments.map(item => {
          const type_adjustment = item ? item.type_adjustment : null;
          const adjustment = item ? item.adjustment : null;

          return { type_adjustment, adjustment };
        });

        const valid = adjustments.map((item, index) => {
          for (const index2 in adjustments) {
            let isDuplicated = true;
            const item2 = adjustments[index2];

            if (index != index2) {
              for (const key in item2) {
                isDuplicated = item[key] == item2[key] && isDuplicated;
              }

              if (isDuplicated) {
                return false;
              }
            }
          }

          return true;
        });
        result.valid = valid;
      }

      return result;
    },
  },
  methods: {
    parseBoolean(value) {
      return Boolean(Number(value));
    },
    cloneObject(value) {
      return JSON.parse(JSON.stringify(value));
    },
    newPriceAdd() {
      if (this.mktPrice.length) {
        const hasEmptyPrice = this.mktPrice.find(({ mercadolivre_price_title: title }) => {
          return title === '' || title === newPriceItemTitle;
        });

        if (hasEmptyPrice) {
          this.$emit('alert', {
            type: 'error',
            message: 'Termine de configurar antes de criar um novo preço',
          });
          return;
        }
      }

      this.newPriceItem.id = uuidv4();

      this.mktPrice = [this.cloneObject(this.newPriceItem), ...this.mktPrice];
    },
    addAdjustmentPrice(priceIndex) {
      const mktPrice = this.cloneObject(this.mktPrice);

      mktPrice[priceIndex].marketplace_price_adjustments = [
        ...mktPrice[priceIndex].marketplace_price_adjustments,
        {
          type_adjustment: Type_MarketplaceTypeAdjustment.Tp_Acre,
          adjustment: Type_MarketplaceAdjustmentPrice.Tp_Percentual,
          value: '',
        },
      ];

      this.mktPrice = mktPrice;
    },
    removeAdjustmentPrice(priceIndex, adjustmentIndex) {
      const mktPrice = this.cloneObject(this.mktPrice);

      mktPrice[priceIndex].marketplace_price_adjustments = mktPrice[
        priceIndex
      ].marketplace_price_adjustments.map((item, index) => (index != adjustmentIndex ? item : null));

      this.mktPrice = mktPrice;
    },
    removePrice(priceIndex) {
      if (this.mktPrice[priceIndex].marketplace_price_id > 0) {
        this.$emit('deleted', this.mktPrice[priceIndex].marketplace_price_id);
      }

      this.mktPrice = this.mktPrice.filter((item, index) => index != priceIndex);
    },
    setMaskAdjustmentValue(value) {
      return value == Type_MarketplaceAdjustmentPrice.Tp_Percentual ? 'percentage' : 'brazilCurrency';
    },
    titleTabsAside(asideTabs) {
      if (asideTabs && asideTabs.length === 0) return '';

      const activeTab = asideTabs.find(item => item.active);
      const activeText = { ...activeTab };

      return (activeText.text || asideTabs[0].text).replace('• ', '');
    },
    changeMercadolivreStandard(priceIndex) {
      const mktPrice = this.cloneObject(this.mktPrice);
      const errors = {};

      this.mktPrice = mktPrice.map((item, index) => {
        errors['mktPrice[' + index + '][standard]'] = [];
        item.standard = index === priceIndex ? 1 : 0;
        return item;
      });

      this.$emit('errors', errors);
    },
  },
};
