import axiosApi, {param} from "@assets/js/axios-api";
import formMixin from "@mixins/formMixin";

const BASE_URL = document.getElementById('base-urls').dataset.baseUrlLoja;

export default {
  name: 'BaseCep',
  data() {
    return {
      bPostCode: false,
      module: this.data,
      config_module: [],
      city: '',
      cities: [],
      states: [],
      postcode_visible: '',
      error_postcode_search: '',
      postcodesearch: '',
      postcodeListAddress: [],
      postcode_loading: false,
      postcode_readonly: {
        address_1: true,
        address_2: true,
        zone_id: true,
        codigo_municipio: true,
      },
      showDontKnow: false,
      disableForm: false,
      btnSubmitLoading: false,
    }
  },
  mixins: [formMixin],
  components: {
    BaseInput: () => import(/* webpackChunkName: "BaseInput" */ '@elements/BaseInput/index.vue'),
    BaseButton: () => import(/* webpackChunkName: "BaseButton" */ '@elements/BaseButton/index.vue'),
    BaseCard: () => import(/* webpackChunkName: "BaseCard" */ '@elements/BaseCard/index.vue'),
    BaseModal: () => import(/* webpackChunkName: "BaseModal" */ '@components/BaseModal/index.vue'),
    BaseSelect: () => import(/* webpackChunkName: "BaseModal" */ '@elements/BaseSelect/index.vue'),
  },
  props: {
    is_address_user: {
      type: Boolean,
      default: false
    },
    data_errors: {
      type: Object
    },
    is_catalog:{
      type: Boolean,
      default: false
    },
    show_fields:{
      type: Boolean,
      default: false
    },
    readonly:{
      type: Boolean,
      default: false
    },
    label: {
      type: String,
    },
    error: {
      type: String,
    },
    valid: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    required: {
      type: Boolean,
      default: false,
    },
    name: {
      type: String,
    },
    index: {
      type: Number,
    },
    data: {
      type: Object,
    },
  },
  watch: {
    "module.postcode"(values) {
      this.printData(values);
    },
    "module.apelido"(values) {
      this.printData(values);
    },
    "module.address_1"(values) {
      this.printData(values);
    },
    "module.address_2"(values) {
      this.printData(values);
    },
    "module.numero"(values) {
      this.printData(values);
    },
    "module.complemento"(values) {
      this.printData(values);
    },
    "module.zone_id"(values) {
      this.printData(values);
    },
    "module.codigo_municipio"(values) {
      this.printData(values);
    },
    "module.country_id"(values) {
      this.printData(values);
    },
  },
  mounted() {
    if (this.states) {
      // Carrega estados
      axiosApi({
        headers: {'content-type': 'application/x-www-form-urlencoded'},
        url: BASE_URL + 'index.php?route=postcode/postcode/listStates',
        method: 'get',
        responseType: 'json',
        timeout: 10000,
      })
        .then(({data}) => {
          this.states = data;

          if (this.module.postcode) {
            this.onPostcode(this.module.postcode);
          }

        })
        .catch(err => console.log(err, err.response));
    }

    if (typeof success != 'undefined') {
      this.alert = {
        type: 'success',
        message: success,
      };
    }

    if (typeof warning != 'undefined') {
      this.alert = {
        type: 'error',
        message: warning,
      };
    }
  },
  methods: {
    printData(values) {
      // Envia dados ao modulo
      this.$emit('callback', this.module, this.index);
    },
    onPostcode(value) {
      // Pesquisa pelo CEP
      if (/[0-9]{5}\-[0-9]{3}/.test(value) && !this.bPostCode) {
        this.bPostCode = true;
        this.postcode_loading = true;

        axiosApi({
          url: BASE_URL + 'index.php?route=postcode/postcode/search',
          method: 'POST',
          data: param({
            cep: this.module.postcode.replace(/[-.]/g, '')
          })
        })
          .then(({data}) => {
            this.postcode_visible = true;
            const {dados, error} = data;

            if (error) {
              this.module.postcode = '';
              this.postcode_readonly = {
                address_1: false,
                address_2: false,
                zone_id: false,
                codigo_municipio: false,
              };

              this.showDontKnow = true;
              this.bPostCode = false;
              return;
            }

            if (!dados) return;

            this.setAddressPostcode(dados);

          })
          .catch(err => console.log(err, err.response))
          .finally(() => (this.postcode_loading = false));
      }
    },
    selectAddress(address) {
      // Seleciona endereço no modal 'não sei meu cep'
      this.module.postcode = address.postcode;
      this.onPostcode(this.module.postcode);
      this.postcodeListAddress = [];
      this.showDontKnow = false;
      this.btnSubmitLoading = false;
    },
    postcodeSearch() {
      // Pesquisa endereço no modal 'não sei meu cep'
      axiosApi({
        url: BASE_URL + 'index.php?route=postcode/postcode/listAddressData',
        method: 'post',
        timeout: 10000,
        data: 'dados=' + this.postcodesearch,
      })
        .then(({data}) => {
          const {dados, error} = data;
          this.error_postcode_search = '';

          if (error) {
            this.error_postcode_search = error;
            return;
          }

          if (!dados) return;
          this.btnSubmitLoading = true;
          this.postcodeListAddress = dados;
        })
        .catch(err => console.log(err, err.response));
    },
    onChangeZone() {
      // Carrega cidades
      return axiosApi({
        url: BASE_URL + 'index.php?route=postcode/postcode/listCities',
        method: 'post',
        responseType: 'json',
        timeout: 10000,
        data: 'zone_id=' + this.module.zone_id,
      })
        .then(({data}) => {
          this.cities = data.cities;
        })
        .catch(err => console.log(err, err.response));
    },
    onShowDontKnow() {
      // Habilita modal 'não sei meu cep'
      this.showDontKnow = true;
      this.btnSubmitLoading = false;
      setTimeout(() => {
        this.$refs.postcodesearch.$refs.input.focus();
      }, 400);
    },
    setAddressPostcode(dados) {
      // Preenche os campos com sua respectiva informação
      const {codigo_municipio, ...remainingData} = dados;
      const postcode_readonly = {};
      postcode_readonly.codigo_municipio = !!codigo_municipio;

      for (const key in remainingData) {
        postcode_readonly[key] = !!remainingData[key];
        this.module[key] = remainingData[key];
      }

      this.postcode_readonly = postcode_readonly;
      this.bPostCode = false;
      this.onChangeZone().then(() => {
        this.module.codigo_municipio = codigo_municipio;
      });
    },
    parseBoolean(value) {
      return Boolean(Number(value));
    },
  },
};
