<template>
  <div class="m-sign-up">
    <div class="m-sign-up__title">{{ $t("Wellcome") }}</div>
    <div class="m-sign-up__text">
      لطفا کد کشور خود را تایید و شماره موبایل خود را وارد کنید
    </div>
    <div class="m-sign-up__form">
      <div class="m-sign-up__form-row">
        <select id="single" class="select2-container--default form-control">
          <option>ایران</option>
        </select>
      </div>

      <div class="m-sign-up__form-row m-sign-up__number">
        <div
          class="form-group position-relative"
          :class="{ 'form-group--error': $v.mobile.$error }"
        >
          <input
            class="form-control"
            type="tel"
            name="mobile"
            id="mobile"
            v-model.trim="$v.mobile.$model"
            placeholder="۹۱۰۰۰۰۰۰۰۰"
            @input="resetErrors"
            dir="ltr"
          />
          <span>+98</span>
        </div>
        <div v-if="submitStatus === 'ERROR'">
          <div class="error" v-if="!$v.mobile.required">
            {{ $t("IsRequired") }}
          </div>
          <div class="error" v-if="!$v.mobile.minLength">
            {{ $t("MinLength", { n: 10 }) }}
          </div>
          <div class="error" v-if="!$v.mobile.maxLength">
            {{ $t("MaxLength", { n: 11 }) }}
          </div>
          <!-- <div class="error" v-if="!$v.mobile.between">
            Must be between {{ $v.mobile.$params.between.min }} and
            {{ $v.mobile.$params.between.max }}
          </div> -->
        </div>

        <div class="sign-up__form-row sign-up__simple-input">
          <div
            class="form-group position-relative d-flex align-items-center"
            :class="{ 'form-group--error': $v.captcha.$error }"
          >
            <input
              class="form-control elem__placeholder-gray mb-0 flex-grow-1 p-3"
              type="text"
              name="captcha"
              v-model.trim="$v.captcha.$model"
              placeholder="کد تایید"
              dir="ltr"
            />
            <div class="d-flex border-1 p-2">
              <div class="captcha-container" style="width: 7em">
                <img
                  style="width: 100%; height: 100%; object-fit: contain"
                  :src="captchaImage"
                  alt=""
                />
              </div>
              <button-component
                style="min-width: auto"
                @click="resetCaptcha"
                classes="border-0"
                buttonText=""
                :buttonLoading="loading"
              >
                <svg style="width: 1.3em" class="icon icon-reset-form">
                  <use xlink:href="#icon-reset-form"></use>
                </svg>
              </button-component>
            </div>
          </div>
          <div v-if="submitStatus === 'ERROR'">
            <div class="error" v-if="!$v.captcha.required">
              {{ $t("IsRequired") }}
            </div>
          </div>
        </div>

        <div class="m-sign-up__btn-container">
          <a
            href="#login"
            class="m-sign-up__text text__gray"
            @click.prevent="$emit('set-component', { name: 'login' })"
            >ورود با پست الکترونیک</a
          >
          <button class="btn" :disabled="loading" v-on:click="getCode()">
            تایید شماره
          </button>
        </div>
      </div>

      <!-- <p class="typo__p" v-if="submitStatus === 'OK'">
        Thanks for your submission!
      </p>
      <p class="typo__p" v-if="submitStatus === 'ERROR'">
        Please fill the form correctly.
      </p>
      <p class="typo__p" v-if="submitStatus === 'PENDING'">Sending...</p> -->
    </div>
  </div>
</template>

<script>
import authMixin from "~/mixins/authMixin";
import {
  required,
  minLength,
  maxLength,
  between,
} from "vuelidate/lib/validators";

import { mapState, mapActions } from "pinia";
import { useCommonStore } from "~/stores/commonStore";
import { useAuthStore } from "~/stores/authStore";
export default {
  mounted(){
    this.getCaptcha().then((res)=>{
      this.captchaImage = `data:image/jpeg; charset=utf-8; base64, ${res}`;
    }).catch(err=>{
      this.captchaImage =  import(`assets/common/img/captcha.png`).default;
    })
  },
  validations: {
    mobile: {
      required,
      minLength: minLength(10),
      maxLength: maxLength(10),
    },
    captcha: {},
  },
  mixins: [authMixin],

  data() {
    return {
      mobile: "",
      enableResetPassword: false,
      captcha: undefined,
      captchaImage:""

    };
  },
  computed: {
    ...mapState(useAuthStore,["getResetPasswordState"]),
  },
  methods: {
    ...mapActions(useCommonStore, ["SET_USER_FULL_NAME", "SET_USER_PHONE_NUMBER"]),
    resetErrors() {
      if (this.$v.$invalid) this.$v.$reset();
    },
    getCode() {
      var vm = this;
      this.$v.$touch();

      if (this.$v.$invalid) {
        this.submitStatus = "ERROR";
      } else {
        if (this.loading) return;
        this.loading = true;

        this.submitStatus = "PENDING";

        this.phoneLogin({
          mobile: parseInt(vm.mobile, 10),
          captcha: vm.captcha,
        })
          .then((res) => {
            this.submitStatus = "OK";

            mySwalToast({
              title: res.message,
            });

            this.SET_USER_FULL_NAME(res.data);
            this.SET_USER_PHONE_NUMBER(this.mobile);

            if (this.getResetPasswordState) this.redirectToResetPage(res.data);
            else this.redirectToActivePage();
          })
          
          .finally(() => {
            this.loading = false;
          });
      }
    },
    redirectToResetPage(data) {
      var vm = this;

      try {
        this.$emit("set-component", {
          name: "reset-pass-phone",
          params: {
            usernameemail: this.usernameemail,
            mobile: parseInt(vm.mobile, 10),
            userData: data,
          },
        });

        // this.$router.push({
        //   name: "resetpassphone",
        //   params: {
        //     usernameemail: this.usernameemail,
        //     mobile: this.mobile,
        //     userData: data,
        //   },
        // });
      } catch (err) {
        
      }
    },
    redirectToActivePage() {
      var vm = this;

      try {
        this.$emit("set-component", {
          name: "activate",
          params: { 
            mobile: parseInt(vm.mobile, 10),
          },
        });

        // this.$router.push({
        //   name: "activate",
        //   params: { mobile: this.mobile },
        // });
      } catch (err) {
        
      }
    },
  },
};
</script>
<style scoped>
.blink_me {
  animation: blinker 1s linear infinite;
}
@keyframes blinker {
  50% {
    opacity: 0;
  }
}
</style>