import Vue from 'vue';
import axios from 'axios';

import * as filters from '@assets/js/filters';
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'),
    BaseInputFile: () => import(/* webpackChunkName: "BaseInputFile" */ '@elements/BaseInputFile/index.vue'),
  },
  mixins: [formMixin],
  data() {
    return {
      isLoading: true,
      btnSubmitLoading: false,
      disableForm: false,
      alert: {},
      configurations: {},
      modules: [],
      form: {},
      tabs: [
        { text: 'Configuração'},
        { text: 'Pagamentos'}
      ],
      activedTab: 0
    };
  },
  mounted() {
    this.isLoading = false;

    this.modules.map((item, index) => {
      item.expand = false;
    });

  },
  methods: {
    setData({ configurations, modules }) {
      this.configurations = configurations;
      this.modules = modules;
    },
    onSaveConfig() {
      const form = this.$refs.formConfig;
      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.configValidationObserver.setErrors(errors);
        }
        if (success) {
          this.alert = {
            type: 'success',
            message: success
          }
        }
      }).catch(() => {
        this.alert = {
          type: 'warning',
          message: 'Aconteceu de inesperado, por favor tente novamente!'
        }
      }).then(() => {
        this.disableForm = false;
        this.btnSubmitLoading = false;
      });
    },
    onChangeContentTab(newTabs){
      const activeContentTabIndex = newTabs.findIndex(tab => tab.active);
      this.activedTab = activeContentTabIndex;
      this.tabs = newTabs;
    },
    onAddPayment(){
      this.modules.push({expand:true});
    },
    onExpandModule(row){

      const payments = this.modules;

      payments[row].expand = !payments[row].expand;

      this.modules = [...payments];

    },
    onRemoveModule(row){
      this.modules.splice(row, '1');
    },
  },
});

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

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