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: {},
      configurations: {},
    };
  },
  mounted() {
    this.isLoading = false;
  },
  methods: {
    setData({ configurations }) {
      this.configurations = configurations;
    },
    onAddModule() {
      this.configurations.free_module.push({
        free_titlefutura: this.configurations.free_titlefutura
      });
    },
    onRemoveModule(moduleIndex) {
      this.configurations.free_module.splice(moduleIndex, 1);
    },
    onSubmit() {
      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);
        }
        if (success) {
          this.alert = {
            type: 'success',
            message: success
          }
        }
      }).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');
}
