import AdmVue from '@assets/js/adm-vue.js';
import initVue from '@assets/js/initVue.js';
import axiosApi from '@assets/js/axios-api';
import formMixin from '@assets/components/mixins/formMixin';

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

const vm = new AdmVue({
  components: {
    BaseCard: () => import(/* webpackChunkName: "BaseCard" */ '@elements/BaseCard/index.vue'),
    TheInterests: () => import(/* webpackChunkName: "TheInterests" */ '@components/TheInterests/index.vue'),
    TheLogin: () => import(/* webpackChunkName: "TheLogin" */ '@components/TheLogin/index.vue'),
    TheForgotten: () => import(/* webpackChunkName: "TheForgotten" */ '@components/TheForgotten/index.vue'),
    BaseModal: () => import(/* webpackChunkName: "BaseModal" */ '@components/BaseModal/index.vue'),
  },
  data() {
    return {
      pessoa: '',
      email: '',
      password: '',
      confirm: '',
      newsletter: '',
      firstname: '',
      lastname: '',
      razao_social: '',
      cpf: '',
      rg: '',
      cnpj: '',
      perfil: '',
      contribuinte: '',
      inscricao_estadual: '',
      telephone: '',
      fax: '',
      celular: '',
      sexo: '',
      data_nascimento: '',
      company: '',
      postcode: '',
      apelido: '',
      address_1: '',
      tipo_logradouro: '',
      logradouro: '',
      city: '',
      numero: '',
      complemento: '',
      address_2: '',
      zone_id: '',
      codigo_municipio: '',
      country_id: '',
      captcha: '',
      agree: '',
      submitted: false,

      page: 'login', // register|login|forgotten
      postcode_visible: '',
      postcode_readonly: {
        address_1: true,
        address_2: true,
        zone_id: true,
        codigo_municipio: true,
      },
      postcode_loading: false,
      cities: [],
      error_agree: '',
      error_google_captcha: '',
      error_postcode_search: '',
      showDontKnow: false,
      postcodesearch: '',
      postcodeListAddress: [],
      interests_categories: {},
      feedback_whatsapp_status: false,
      feedback_whatsapp_number: '',
      isFutura: false,
    };
  },
  mounted() {
    if (this.postcode) {
      this.onPostcode(this.postcode);
    }
    this.$refs.registerNew.removeAttribute('hidden');
    const isPessoaJuridica = this.fields_register_brazil_tipo_de_pessoa == this.Type_CadastroPessoa.Tp_Juridico;
    const isPessoaFisica = this.fields_register_brazil_tipo_de_pessoa == this.Type_CadastroPessoa.Tp_Fisico;
    const isBoth = this.fields_register_brazil_tipo_de_pessoa == this.Type_CadastroPessoa.Tp_Ambos;

    if (this.pessoa = isPessoaJuridica) {
      this.pessoa = 'J';
    } else if (this.pessoa = isPessoaFisica) {
      this.pessoa = 'F';
    }   else if (this.pessoa = isBoth) {
        this.pessoa = '';
    }

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

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

    if (typeof customerml != 'undefined') {
      this.alert = {
        type: 'warning',
        message: customerml,
      };
    }
  },
  updated() {
    if (this.page === 'register') {
      if (typeof this.$refs.validationObserver != 'undefined') {
        this.$refs.validationObserver.reset();
      }

      this.reCaptchaRender();
    }
  },
  computed: {
    sendData() {
      const categories = {};

      this.interests_categories.categories
        .filter(category => category.children.filter(child => child.checked).length)
        .map(category => {
          categories[category.id] = {
            status: category.checked ? 'on' : '',
          };
          category.children
            .filter(child => child.checked)
            .map(child => {
              categories[category.id][child.id] = 'on';
            });
        });

      return Object.assign(
        {
          categories,
          pessoa: this.pessoa,
          email: this.email,
          password: this.password,
          confirm: this.confirm,
          newsletter: this.newsletter,
          firstname: this.firstname,
          lastname: this.lastname,
          telephone: this.telephone,
          fax: this.fax,
          celular: this.celular,
          company: this.company,
          postcode: this.postcode,
          apelido: this.apelido,
          address_1: this.address_1,
          tipo_logradouro: this.tipo_logradouro,
          logradouro: this.logradouro,
          city: this.city,
          numero: this.numero,
          complemento: this.complemento,
          address_2: this.address_2,
          zone_id: this.zone_id,
          codigo_municipio: this.codigo_municipio,
          country_id: this.country_id,
          captcha: this.captcha,
        },
        this.feedback_whatsapp_status
          ? {
              feedback_whatsapp_status: Number(this.feedback_whatsapp_status),
              feedback_whatsapp_number: this.feedback_whatsapp_number,
            }
          : {},
        this.agree ? { agree: this.agree } : {},
        this.google_captcha ? { 'g-recaptcha-response': this['g-recaptcha-response'] } : {},
        this.pessoa == 'J'
          ? {
              razao_social: this.razao_social,
              cnpj: this.cnpj,
              perfil: this.perfil,
              contribuinte: this.contribuinte,
              inscricao_estadual: this.inscricao_estadual,
            }
          : {
              cpf: this.cpf,
              rg: this.rg,
              sexo: this.sexo,
              data_nascimento: this.data_nascimento,
            }
      );
    },
  },
  methods: {
    reCaptchaRender() {
      if (this.google_captcha && typeof grecaptcha.render != 'undefined') {
        if (this.$refs.grecaptcha.innerHTML === '') {
          grecaptcha.render(this.$refs.grecaptcha, {
            sitekey: this.site_key,
          });
        } else {
          grecaptcha.reset();
        }
      } else {
        setTimeout(() => {
          this.reCaptchaRender();
        }, 400);
      }
    },
    disabledAfterToday(date) {
      const today = new Date();

      return date > today;
    },
    setUserInfo(userInfo) {
      this.email = userInfo.email;
      this.name = userInfo.name;
      this.firstname = userInfo.firstname;
      this.lastname = userInfo.lastname;
    },
    goToError() {
      setTimeout(() => {
        const errorInput = document.querySelector('.field-error');
        if (errorInput) {
          window.scrollTo(0, errorInput.offsetTop);
        }
      }, 400);
    },
    formError({ errors }) {
      this.$refs.validationObserver.setErrors(errors);
      this.error_agree = errors.error_agree || '';
      this.error_google_captcha = errors.error_google_captcha || '';

      this.goToError();

      this.reCaptchaRender();
    },
    validateEmail() {
      if (!this.email) return;

      return axiosApi({
        url: 'index.php?route=account/register_new/email',
        method: 'post',
        data: 'email=' + this.email,
      })
        .then(({ data }) => {
          if (data.errors) {
            this.$refs.validationObserver.setErrors(data.errors);
          }
        })
        .catch(err => console.log(err, err.response));
    },
    setCategories(categories) {
      this.interests_categories = { ...this.interests_categories, categories };
    },

    onPostcode(value) {
      if (/[0-9]{5}\-[0-9]{3}/.test(value)) {
        this.postcode_loading = true;
        axiosApi({
          headers: { 'content-type': 'application/x-www-form-urlencoded' },
          url: BASE_URL + 'index.php?route=postcode/postcode/search',
          method: 'post',
          responseType: 'json',
          timeout: 10000,
          data: 'cep=' + this.postcode.replace(/[-.]/g, ''),
        })
          .then(({ data }) => {
            this.postcode_visible = true;
            const { dados, error } = data;

            if (error) {
              this.postcode_readonly = {
                address_1: false,
                address_2: false,
                zone_id: false,
                codigo_municipio: false,
              };
              this.$refs.validationObserver.setErrors({ postcode: [error] });
              return;
            }

            if (!dados) return;

            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[key] = remainingData[key];
            }

            this.postcode_readonly = postcode_readonly;

            this.onChangeZone().then(() => {
              this.codigo_municipio = codigo_municipio;
            });
            setTimeout(() => {
              this.$refs.apelido.$refs.input.focus();
            }, 400);
          })
          .catch(err => console.log(err, err.response))
          .finally(() => (this.postcode_loading = false));
      }
    },
    selectAddress(address) {
      this.postcode = address.postcode;
      this.postcodeListAddress = [];
      this.showDontKnow = false;
    },
    setAddressInfo(codigoMunicipio) {
      const cityInfo = this.cities.find(({ codigo_municipio }) => String(codigo_municipio) === String(codigoMunicipio));
      this.city = cityInfo.municipio;
    },
    postcodeSearch() {
      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.postcodeListAddress = dados;
        })
        .catch(err => console.log(err, err.response));
    },
    onChangeZone() {
      return axiosApi({
        url: BASE_URL + 'index.php?route=postcode/postcode/listCities',
        method: 'post',
        responseType: 'json',
        timeout: 10000,
        data: 'zone_id=' + this.zone_id,
      })
        .then(({ data }) => {
          this.cities = data.cities;
        })
        .catch(err => console.log(err, err.response));
    },
    onSubmit() {

      this.submitted = true;

      if(!this.pessoa) {
        return;
      }

      if (this.google_captcha) {
        this['g-recaptcha-response'] = grecaptcha.getResponse();
      }
      formMixin.methods.onSubmit.call(this);
    },
    handleSubmitForm() {
      this.$refs.validationObserver.validate().then(valid => {
        if (valid) {
          this.onSubmit();
        } else {
          this.goToError();
        }
      });
    },
    onShowDontKnow() {
      this.showDontKnow = true;

      setTimeout(() => {
        this.$refs.postcodesearch.$refs.input.focus();
      }, 400);
    },
    parseBoolean(value) {
      return Boolean(Number(value));
    },
  },
});

initVue(vm);
