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;
    },
    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 }) => {
        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
          }
          this.page = 'faixaceps';
        }
      }).catch(() => {
        this.alert = {
          type: 'warning',
          message: 'Aconteceu 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');
}
