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: {},
      tabs: [],
      configurations: {},
      activeContentTabIndex: 0
    };
  },
  mounted() {
    this.isLoading = false;
  },
  methods: {
    setData({ tabs, configurations, token }) {
      var hash = window.location.hash ? window.location.hash : "#tab-info=0";
      var hashNumber = hash.split("=")[1];
      var isNumber = !isNaN(hashNumber);
      var tabsMaxIndex = tabs.length - 1; //pois o index começa no zero e vai ser feita uma comparaçao log a baixo usando o index e a quantidade de Tabs

      if (isNumber && hashNumber >= 0 && hashNumber <= tabsMaxIndex) {
        tabs[Number(hashNumber)].active = true;
        this.activeContentTabIndex = Number(hashNumber);
      }

      this.tabs = tabs;
      this.configurations = configurations;
      this.token = token;
    },
    onChangeContentTab(newTabs) {
      const activeContentTabIndex = newTabs.findIndex(tab => tab.active);
      this.activeContentTabIndex = activeContentTabIndex;
      this.tabs = newTabs;
    },
    onAddService() {
      this.configurations.correios_servicos.push([]);
    },
    onRemoveService(serviceIndex) {
      const configurations = this.configurations;
      configurations.correios_servicos.splice(serviceIndex, 1);
      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;
      this.configurations.correios_invalid_credential = 0;
      
      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);

            this.alert = {
              type: "error",
              message:
                "Alguns campos estão incorretos. Corrija os campos em vermelho."
            };
          }
          if (success) {

            this.$refs.validationObserver.setErrors({
              correios_contrato_senha: [],
              correios_contrato_user: [],
              correios_postCartao: []
            });

            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;
        });
    },
    adminCodeTest() {
      const {
        correios_contrato_codigo,
        correios_contrato_senha,
        correios_postcode,
        correios_api_status
      } = this.configurations;
      const info = Boolean(
        correios_contrato_codigo &&
          correios_contrato_senha &&
          correios_postcode &&
          correios_api_status !== "1"
      );

      if (info) {
        axios({
          headers: {
            "content-type": "application/x-www-form-urlencoded"
          },
          method: "post",
          url:
            "index.php?route=shipping/correios/adminCodeTest&token=" +
            this.token,
          data: window.objectToParam({
            nCdEmpresa: this.configurations.correios_contrato_codigo,
            sDsSenha: this.configurations.correios_contrato_senha,
            sCepOrigem: this.configurations.correios_postcode
          })
        })
          .then(response => {
            if (response.data) {
              const erro = response.data.match(/<Erro>99<\/Erro>/);

              if (erro) {
                this.$refs.validationObserver.setErrors({
                  correios_contrato_codigo: ["Código administrativo inválido."]
                });
              }
            }
          })
          .catch(() => console.log("erro"));
      } else {
        this.$refs.validationObserver.setErrors({
          correios_contrato_codigo: ""
        });
      }
    }
  }
});

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

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