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: {},
      back: ''
    };
  },
  mounted() {
    this.isLoading = false;
  },
  methods: {
    setData({ configurations, back }) {
      this.configurations = configurations;
      this.back = back;
    },
    onSubmit() {
      const url = this.$refs.form.action;
      const data = new FormData();

      for (const key in this.configurations) {
        if (this.configurations.hasOwnProperty(key)) {
          const value = this.configurations[key];
          data.append(key, value);
        }
      }

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

      axios({
        method: 'post',
        url,
        data,
      }).then(({ data }) => {
        if (data.errors) {
          if (data.errors.warning) {
            this.alert = {
              type: 'error',
              message: data.errors.warning
            }
          } else {
            this.$refs.validationObserver.setErrors(data.errors);
          }

          this.btnSubmitLoading = false;
          this.disableForm = false;
        }

        if (data.success) {
          window.location.href = this.back;
        }
      });
    }
  },
});

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

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