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,
      zones: [],
      cities: [],
      btnSubmitLoading: false,
      disableForm: false,
      alert: {},
      configurations: {},
      back: '',
      urlCities: '',
    };
  },
  mounted() {
    this.isLoading = false;
  },
  methods: {
    setData({ configurations, back, cities, urlCities, zones }) {
      this.configurations = configurations;
      this.back = back;
      this.cities = cities;
      this.urlCities = urlCities;
      this.zones = zones;
    },
    changeUf() {
      this.cities = [{
        municipio: 'Carregando municipios...'
      }];

      const zoneCode = this.configurations.jamef_ufOrigem;
      const { zone_id } = this.zones.find(zone => zone.code == zoneCode);

      axios({
        headers: { 'content-type': 'application/x-www-form-urlencoded' },
        method: 'post',
        responseType: 'json',
        timeout: 10000,
        url: this.urlCities,
        data: 'zone_id=' + zone_id,
      }).then(({data: {cities}}) => {
        this.cities = cities.map(city => ({
          municipio: city.municipio
        }));
      });
    },
    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.warning) {
          this.alert = {
            type: 'error',
            message: data.warning
          }
        }

        if (data.errors) {
          this.$refs.validationObserver.setErrors(data.errors);
        }

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

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

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

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