import AdmVue from '@assets/js/adm-vue';
import TextWithVar from '@assets/js/valid-text-with-vars';
import copyContent from '@assets/js/copyContent';
import modelPrice from '../../../model/marketplace/marketplace/marketplacePrice.js';
import axiosApi from '@assets/js/axios-api.js';

function setTextWithVar(e) {
  const message = e.target.textWithVar.insertVarNameInText(e.detail.text);

  if (message) {
    window.dispatchEvent(new CustomEvent('errorVarNameInText', { detail: message }));
  }
}

const vm = new AdmVue({
  directives: {
    textareaWithVar: {
      update: function(el) {
        const textArea = el.querySelector('textarea');
        textArea.textWithVar = new TextWithVar(textArea);
        textArea.removeEventListener('add', setTextWithVar);
        textArea.addEventListener('add', setTextWithVar);
      },
    },
  },
  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'),
    AsideContent: () => import(/* webpackChunkName: "AsideContent" */ '@components/AsideContent/index.vue'),
    BaseTextarea: () => import(/* webpackChunkName: "BaseTextarea" */ '@elements/BaseTextarea/index.vue'),
    GroupInput: () => import(/* webpackChunkName: "BaseTabs" */ '@components/GroupInput/index.vue'),
    MarketPrice: () => import(/* webpackChunkName: "MarketPrice" */ '@components/MarketPrice/index.vue'),
  },
  data() {
    return {
      configurations: {
        mercadolivre_app_id: '',
        mercadolivre_app_secret: '',
        mercadolivre_attr_status: false,
        mercadolivre_data_pedido: '',
        mercadolivre_debug: false,
        mercadolivre_status: false,
        mercadolivre_pagina_produtos: false,
        mercadolivre_nfe_status: false,
        mercadolivre_update_customer_address: false,
        mercadolivre_initial_description: '',
        mercadolivre_final_description: '',
        mercadolivre_category_tree: '',
        mercadolivre_mercaId: '',
        mercadolivre_category_auto: false,
        mercadolivre_mercaListType: '',
        mercadolivre_mercaCondition: '',
        mercadolivre_mercaWarrantyType: '',
        mercadolivre_mercaWarranty: '',
        mercadolivre_mercaWarrantyTypeTime: '',
        merca_status: [],
        mercadolivre_automatic_message_status: false,
        mercadolivre_automatic_message: [],
        mercadolivre_comission_status: false,
        mercadolivre_shipping_alter: '',
        mercadolivre_shipping_free: false,
        mercadolivre_cnpj_transportadora: '',
        mercadolivre_order_email_status: false,
        mercadolivre_alert_emails: '',
        mercadolivre_user_buyer: '',
        mercadolivre_user_seller: '',
        mercadolivre_order_status_nfe: '',
        mercadolivre_description_status: 1,
      },
      disableForm: false,
      loadingBtn: false,
      instructions: false,
      tabAdvertisement: [],
      tabsMsgAutomatic: [],
      textUrlCallCopy: '',
      textUrlNotyCopy: '',
      mercadolivre_cat_selection: [],
      classCategory: true,
      disableAutomatic: false,
      marketPriceObject: {},
      mktPrice: [],
      mktPriceDelete: [],
    };
  },
  created() {},
  beforeMount() {
    this.marketPriceObject = JSON.parse(this.marketprice);
    this.configurations.merca_status = this.merca_statuses;

    if (this.marketPriceObject.mktpriceadjustments.length) {
      this.marketPriceObject.mktpriceadjustments = this.marketPriceObject.mktpriceadjustments;
    }

    this.tabs = this.mlSettingsTabs.filter(item => {
      const tabs = { text: item.text, active: item.active };

      if (item.text == this.Type_MlSettings.usergroup) {
        if (this.userGroup) {
          return tabs;
        }
      } else {
        return tabs;
      }
    });

    this.tabAdvertisement = this.mlAdvertisementTabs;
    this.textUrlCallCopy = this.text_url_copy;
    this.textUrlNotyCopy = this.text_url_copy;
    this.tabsMsgAutomatic = this.order_statuses.map(item => {
      return { text: item.name, id: item.order_status_id, active: false };
    });

    const options = this.mercadolivre_cats.map(item => {
      return { id: item.mercaId, name: item.name };
    });
    this.mercadolivre_cat_selection.push({ options });

    this.mercadolivre_types_comission.map(item => {
      const comission = 'mercadolivre_comission_' + item.value;

      this.$set(
        this.configurations,
        comission,
        typeof this.configurations[comission] != 'undefined' ? this.configurations[comission] : ''
      );
    });
  },
  mounted() {},
  watch: {},
  computed: {
    sendData() {
      const mktPriceAdjustments = this.mktPrice.map(item => {
        item.marketplace_price_adjustments = item.marketplace_price_adjustments.filter(value => value != null);
        item = modelPrice.format(item);
        return item;
      });
      return {
        ...this.configurations,
        mktpriceadjustments: { data: mktPriceAdjustments, delete: this.mktPriceDelete },
      };
    },
    writtenTabs() {
      return this.tabsMsgAutomatic.map(item => {
        const automaticMessage = this.configurations.mercadolivre_automatic_message[item.id];
        const written = typeof automaticMessage !== 'undefined' && automaticMessage.trim() != '';

        if (written) {
          item.text = '• ' + item.text.replace('• ', '');
        } else {
          item.text = item.text.replace('• ', '');
        }

        return { text: item.text, id: item.id, active: item.active };
      });
    },
  },
  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,
        };
      }
    },
    formSuccess({ mktpriceadjustments }) {
      const marketPriceObject = this.cloneObject(this.marketPriceObject);
      marketPriceObject.mktpriceadjustments = mktpriceadjustments;
      this.marketPriceObject = marketPriceObject;
    },
    onCopyUrl(url) {
      copyContent(url);
      if (url == this.url.autentication) {
        this.textUrlCallCopy = this.text_url_coped;
        setTimeout(() => {
          this.textUrlCallCopy = this.text_url_copy;
        }, 2000);
      } else {
        this.textUrlNotyCopy = this.text_url_coped;
        setTimeout(() => {
          this.textUrlNotyCopy = this.text_url_copy;
        }, 2000);
      }
    },
    clickTab(tab, value) {
      this[tab] = value;
    },
    parseBoolean(value) {
      return Boolean(Number(value));
    },
    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('• ', '');
    },
    addElement(element, index) {
      this.$refs['personalizedText_' + index][0].$refs.textarea.dispatchEvent(
        new CustomEvent('add', { detail: { text: element } })
      );
    },
    validateAccount: async function() {
      try {
        this.loadingBtn = true;

        const { data } = await this.axiosApi({
          url: this.url.validateaccount,
          method: 'GET',
          data: {},
        });

        const { error, success } = data;

        if (error) {
          this.alert = {
            type: 'error',
            message: error,
          };
        }

        if (success) {
          this.alert = {
            type: 'success',
            message: success,
          };
        }
      } catch (e) {
        console.log(e);
      } finally {
        this.configurations = { ...this.configurations };
        this.loadingBtn = false;
      }
    },
    getCategories: async function(catid, selectKey) {
      try {
        const { data } = await this.axiosApi({
          url: this.url.category,
          method: 'GET',
          params: { catId: catid },
        });

        const { categories, allowed } = data;
        this.classCategory = !!allowed;

        if (this.mercadolivre_cat_selection.length - 1 > selectKey) {
          this.mercadolivre_cat_selection.splice(selectKey + 1, this.mercadolivre_cat_selection.length - selectKey);
        }

        let { name } = this.mercadolivre_cat_selection[selectKey].options.find(item => item.id == catid);

        if (categories.length) {
          this.mercadolivre_cat_selection = this.mercadolivre_cat_selection.filter((item, index) => index <= selectKey);
          this.mercadolivre_cat_selection = [
            ...this.mercadolivre_cat_selection,
            { parentid: catid, parentName: name, options: categories },
          ];
          name = null;
        }

        let parentNames = this.mercadolivre_cat_selection.map(item => item.parentName);

        parentNames = parentNames.filter(parentName => typeof parentName != 'undefined');

        if (name) {
          parentNames.push(name);
        }

        this.configurations.mercadolivre_category_tree = parentNames.join(' » ');
        this.configurations.mercadolivre_mercaId = catid;
      } catch (e) {
        console.log(e);
      } finally {
        this.configurations = { ...this.configurations };
      }
    },
    attCategories: async function() {
      try {
        this.loadingBtn = true;

        const { data } = await this.axiosApi({
          url: this.url.sincat,
          method: 'GET',
        });

        const { error, success } = data;

        if (error) {
          this.alert = {
            type: 'error',
            message: error,
          };
        }

        if (success) {
          this.alert = {
            type: 'success',
            message: success,
          };
        }
      } catch (e) {
        console.log(e);
      } finally {
        this.configurations = { ...this.configurations };
        this.loadingBtn = false;
      }
    },
    shippingType: async function() {
      try {
        this.loadingBtn = true;

        const { data } = await this.axiosApi({
          url: this.url.typeshipping,
          method: 'GET',
        });

        const { error, success, options } = data;

        if (error) {
          this.alert = {
            type: 'error',
            message: error,
          };
        }

        if (success) {
          this.modoenvios = options;
          this.alert = {
            type: 'success',
            message: success,
          };
        }
      } catch (e) {
        console.log(e);
      } finally {
        this.configurations = { ...this.configurations };
        this.loadingBtn = false;
      }
    },
  },
});

AdmVue.init(vm);
