import Vue from 'vue';
import axios from 'axios';

import formMixin from '@mixins/formMixin';

const vm = new Vue({
  components: {
    BaseAlert: () => import(/* webpackChunkName: "BaseAlert" */ '@elements/BaseAlert/index.vue'),
    BaseCard: () => import(/* webpackChunkName: "BaseCard" */ '@elements/BaseCard/index.vue'),
    TheHeader: () => import(/* webpackChunkName: "TheHeader" */ '@components/TheHeader/index.vue'),
    BaseTabs: () => import(/* webpackChunkName: "BaseTabs" */ '@components/BaseTabs/index.vue'),
    SearchProduct: () => import(/* webpackChunkName: "SearchProduct" */ '@components/SearchProduct/index.vue'),
  },
  mixins: [formMixin],
  data() {
    return {
      isLoading: true,
      btnSubmitLoading: false,
      disableForm: false,
      alert: {},
      configurations: [],
      openSearchProduct: false,
    };
  },
  beforeMount() {
    if (this.configurations.length) {
      this.configurations.map(configuration => {
        configuration.tabs = [
          {
            text: 'Módulos',
            active: true,
          },
          {
            text: 'Produtos',
            active: false,
          },
        ];
        configuration.openSearchProduct = false;
      });
    }
  },
  mounted() {
    this.isLoading = false;
  },
  methods: {
    onValidationObserverSubmit(validationObserver) {
      validationObserver = validationObserver || this.$refs.validationObserver;

      const isInvalid = validationObserver.flags.invalid;
      if (isInvalid) {
        this.alert = {
          type: 'error',
          message: 'Alguns campos estão incorretos. Corrija os campos em vermelho.',
        };
      }
    },
    setData({ configurations }) {
      this.configurations = configurations;
    },
    onToggleSearchProduct(configurationIndex) {
      const { configurations } = this;

      const newValue = !configurations[configurationIndex].openSearchProduct;
      configurations[configurationIndex].openSearchProduct = newValue;

      this.configurations = [...configurations];
    },
    onProductsSelected(productsSelected, configurationIndex) {
      this.configurations[configurationIndex].featured_product = [...productsSelected];
    },
    onAddConfiguration() {
      this.configurations.push({
        featured_module: [],
        featured_product: [],
        featured_title: '',
        tabs: [
          {
            text: 'Módulos',
            active: true,
          },
          {
            text: 'Produtos',
            active: false,
          },
        ],
      });
    },
    onRemoveConfiguration(configurationIndex) {
      this.configurations.splice(configurationIndex, 1);
    },
    onAddModule(configurationIndex) {
      const { configurations } = this;
      const featuredModule = configurations[configurationIndex].featured_module;

      let sortOrder = 0;
      if (featuredModule[featuredModule.length - 1]) {
        const { sort_order } = featuredModule[featuredModule.length - 1];
        sortOrder = Number(sort_order) + 1;
      }

      featuredModule.push({
        limit: '24',
        sort_order: sortOrder,
      });

      this.configurations = [...configurations];
    },
    onRemoveModule(configurationIndex, moduleIndex) {
      this.configurations[configurationIndex].featured_module.splice(moduleIndex, 1);
    },
    onSubmit() {
      const errorModuleProduct = this.configurations.some(
        item => !item.featured_module.length || !item.featured_product.length
      );
      if (errorModuleProduct) {
        this.alert = {
          type: 'error',
          message: 'Adicione pelo menos um módulo e um produto.',
        };
        return;
      }

      const form = this.$refs.form;
      const method = form.method;
      const url = form.action;
      const data = new FormData(form);

      this.btnSubmitLoading = true;
      this.disableForm = true;

      axios({
        method,
        url,
        data,
      })
        .then(({ data }) => {
          console.log(data);
          const { warning, errors, success } = data;
          if (warning) {
            this.alert = {
              type: 'warning',
              message: warning,
            };
          }
          if (errors) {
            this.$refs.validationObserver.setErrors(errors);
            this.alert = {
              type: 'error',
              message: 'Alguns campos estão incorretos. Corrija os campos em vermelho.',
            };
          }
          if (success) {
            this.alert = {
              type: 'success',
              message: success,
            };
          }
        })
        .catch(() => {
          this.alert = {
            type: 'warning',
            message: 'Aconteceu algo de inesperado, por favor tente novamente!',
          };
        })
        .finally(() => {
          this.disableForm = false;
          this.btnSubmitLoading = false;
        });
    },
    onChangeTab(tabOptions, configurationIndex) {
      this.configurations[configurationIndex].tabs = tabOptions;

      this.configurations = [...this.configurations];
    },
  },
});

if (document.readyState === 'complete') {
  init();
} else {
  document.addEventListener('DOMContentLoaded', function() {
    init();
  });
}

function init() {
  vm.setData(DATA);
  vm.$mount('#root');
}
