import formMixin from '@mixins/formMixin';
import axiosApi from '@assets/js/axios-api';
import param from '@assets/js/param';

export default {
  name: 'TheLogin',
  props: {
    info: {
      type: Object,
      required: true,
    },
  },
  mixins: [formMixin],
  data() {
    return {
      redirect: '',
      captcha: '',
      ...this.info,
    };
  },
  mounted() {
    if (this.show_captcha) {
      if (this.google_captcha) {
        this.reCaptchaRender();
      } else {
        this.captchaRender();
      }
    }

    if (this.google_enable) {
      this.googleLogin();
      window.onresize =  () => {
        this.googleButtonRender();
      };
    }

  },
  beforeDestroy() {
    this.$refs.validationObserver.reset();
  },
  computed: {
    sendData() {
      return Object.assign({
          email_login: this.email_login,
          password: this.password,
          captcha: this.captcha,
        },
        this.google_captcha ? { 'g-recaptcha-response': this['g-recaptcha-response'] } : {},
        this.checkout ? {checkout: this.checkout} : {}
      )
    },
  },
  methods: {
    formError(data) {
      this.session_captcha = data.session_captcha;
      this.google_captcha = data.google_captcha;
      this.alert = {
        type: 'error',
        message: data.errors.warning,
      };
      if (this.google_captcha) {
        this.reCaptchaRender();
      } else {
        this.captchaRender();
      }
    },
    onSubmit() {

      if (this.google_captcha && this.$refs.grecaptcha.innerHTML !== '') {
        this.sendData['g-recaptcha-response'] = grecaptcha.getResponse();
      }
      this.sendData['google_captcha'] = (this.google_captcha && this.$refs.grecaptcha.innerHTML !== '');
      this.sendData['default_captcha'] = this.default_captcha;
      formMixin.methods.onSubmit.call(this);
    },
    handleSubmitForm() {
      this.$refs.validationObserver.validate().then(valid => {
        if (valid) {
          this.onSubmit();
        }
      });
    },
    logarRedes(userData) {
      if (!userData.emailRedeSocial && !userData.jwtIdToken) return;

      this.alert = {};

      axiosApi({
        url: 'index.php?route=account/login/socialLogin',
        method: 'post',
        data: param(userData),
      })
        .then(({ data }) => {
          if (data.login) {

            axiosApi({
              url: this.$refs.form.action,
              method: 'post',
            })
              .then(({data}) => {
                if (data.redirect) {
                  window.location.href = data.redirect;
                }
              })
              .catch(err => console.log(err, err.response));

          } else {
            this.$emit('page', 'register');
            this.$emit('alert', {
              type: 'warning',
              message: data.warning,
            });
            this.$emit('userinfo', {
              email: data.emailRedeSocial,
              name: data.nomeRedeSocial,
              firstname: data.primeiroNomeRedeSocial,
              lastname: data.sobrenomeRedeSocial,
            });
          }
        })
        .catch(err => console.log(err, err.response));
    },
    facebookLogin() {
      this.$refs.validationObserver.reset();
      $LAB
        .setOptions({ AllowDuplicates: false })
        .script('https://connect.facebook.net/pt_BR/sdk.js')
        .wait(() => this.fbLogin());
    },
    fbLogin() {
      const statusChangeCallback = response => {
        if (response.status === 'connected') {
          chamaAPI(response.authResponse.accessToken);
        } else {
          FB.login(
            response => {
              if (response.status === 'connected') {
                chamaAPI(response.authResponse.accessToken);
              }
            },
            {
              scope: 'public_profile,email', // escopos de permissão para acesso.
              enable_profile_selector: true,
            }
          );
        }
      };

      const carregarFacebookAPI = () => {
		    FB.init({
          appId: this.facebook_id,
          cookie: true,
          xfbml: true,
          version: 'v14.0',
        });

        FB.getLoginStatus(response => {
          statusChangeCallback(response);
        });
      };

      const chamaAPI = accessToken => {
        FB.api(
          '/me',
          { fields: 'name, first_name, last_name, email' },
          ({ id, email, name, first_name, last_name }) => {

            this.logarRedes({
              emailRedeSocial: email,
              nomeRedeSocial: name,
              primeiroNomeRedeSocial: first_name,
              sobrenomeRedeSocial: last_name,
              idRedeSocial: id,
              origemLogin: 'facebook',
              tokenloginsocial: accessToken,
              tipo_validacao_social: 'login',
            });

          }
        );
      };

      try {
        carregarFacebookAPI();
      } catch (e) {
        this.alert = {
          type: 'warning',
          message: 'Verifique se você tem acesso liberado ao Facebook https://www.facebook.com/.',
        };
      }
    },
    googleLogin() {
      $LAB
        .setOptions({ AllowDuplicates: false })
        .script('https://accounts.google.com/gsi/client')
        .wait(() => this.ggLogin());
    },
    ggLogin() {
      try {

        google.accounts.id.initialize({
          client_id: this.google_id,
          callback: this.handleCredentialResponse,
        });

        this.googleButtonRender();


       google.accounts.id.prompt();


      } catch (err) {
        console.log(err);
        this.alert = {
          type: 'warning',
          message: 'Verifique se você tem acesso liberado ao Google https://accounts.google.com/signin/v2/.',
        };
      }
    },
    googleButtonRender() {

      if (google.accounts.id) {
        let btnDiv = document.getElementById('buttondiv');
        if (btnDiv) {
          const wdt = btnDiv.clientWidth - 20;
          google.accounts.id.renderButton(
            btnDiv,
            {
              type: 'standard',
              size: 'large',
              theme: 'outline',
              text: 'signin',
              width: wdt
            });
        }
      }
    },
    handleCredentialResponse (response) {
      if (response) {
        this.logarRedes({
          jwtIdToken: response.credential,
          origemLogin: 'google',
          tipo_validacao_social: 'login',
        });
      }
    },
    reCaptchaRender() {
      if (!this.session_captcha) {
        if (this.google_captcha && typeof grecaptcha.render != 'undefined') {
          let grecaptchaDiv = this.$refs.grecaptcha;
          if (typeof grecaptchaDiv !== 'undefined' && !grecaptchaDiv.innerHTML) {
            grecaptcha.render(grecaptchaDiv, {
              sitekey: this.site_key,
            });
          } else {
            grecaptcha.reset();
          }
        } else {
          setTimeout(() => {
            this.reCaptchaRender();
          }, 400);
        }
      }
    },
    captchaRender() {
       this.default_captcha = true;
    },
  }
};
