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'),
  },
  mixins: [formMixin],
  data() {
    return {
      isLoading: true,
      btnSubmitLoading: false,
      disableForm: false,
      alert: {},
      back: '',
      configurations: {},
    };
  },
  mounted() {
    this.isLoading = false;
  },
  methods: {
    setData({ configurations, back }) {
      this.configurations = configurations;
      this.back = back;
    },
    onAddModule() {
      this.configurations.descontoprimeiracompra_module.push({});
    },
    onRemoveModule(moduleIndex) {
      this.configurations.descontoprimeiracompra_module.splice(moduleIndex, 1);
    },
    onSubmit() {
      const form = this.$refs.form;
      const url = form.action;
      const data = new FormData(form);

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

      axios({
        method: 'post',
        url,
        data,
      }).then(({ data }) => {
        const { errors, success } = data;
        if (errors) {
          this.$refs.validationObserver.setErrors(errors);
          this.alert = {
            type: "error",
            message: errors
          };
        }
        if (success) {
          window.location.href = this.back;
        }
      }).catch(() => {
        this.alert = {
          type: 'warning',
          message: 'Aconteceu algo de inesperado, por favor tente novamente!'
        }
      }).then(() => {
        this.disableForm = false;
        this.btnSubmitLoading = false;
      });
    },
  },
});

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

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