<template>  
	<!--	s: 문자인증	-->
  <div class="wrap bg-wrap">
    <div  class="login-box text-auth">
        <div class="logo"></div>
        <div class="wbox">
            <h3 class="title">2차 휴대폰 문자 인증</h3>
            <p class="desc">아이디에 등록된 휴대폰번호를 입력해 주세요.</p>
            <!-- <form action=""> -->
                <ul class="pw-form">
                  <div>
                    <li><input type="text" 
                               placeholder="휴대폰번호를 입력하세요 (숫자만 입력하세요.)"  
                               v-model="mdn"
                               :maxlength="11"
                               oninput="javascript: this.value = this.value.replace(/[^0-9]/g, '');"
                               @keyup.enter="authNum">
                    <button class="btn-p2color" v-on:click="authNum">인증번호 받기</button></li>
                  </div>
                  <div>
                    <li class="bg-g">
                      <input type="text" 
                             placeholder="인증번호를 입력하세요" 
                             v-model="confirmNum" 
                             :maxlength="6"
                             oninput="javascript: this.value = this.value.replace(/[^0-9]/g, '');"
                             @keyup.enter="ajaxAuth">
                    <span class="time"> {{ timerStr }}</span></li>
                  </div>
                    <li>
                        <button class="btn-default" @click="clickMenu('/login')">취소</button>
                        <button class="btn-pcolor" v-on:click="ajaxAuth">확인</button>
                    </li>
                </ul>
            <!-- </form> -->
        </div>

      </div>
        <login-popup ref="LoginPopup"> </login-popup>
        <common-modal ref="commmonModal"></common-modal>
    </div>		 

</template>

<script>
import { mapGetters } from 'vuex';
import api from '../service/api';
import tokenSvc from '@/common/token-service';
import LoginPopup from '@/components/LoginPopup.vue'
import commonModal from "@/components/modal/commonModal";

export default {
  name: 'Params',
  props: {
      userId: {
          type: String,
          default : ''
      }
  },
  data: function() {
    return {
      row:{},
      errors: [],
      mdn: '',
      confirmNum: '',
      userId: '',
      isAuthNum: false,
      isLogin: true,
      pwd: '',
      text: '',
      number: '',
      timer: null,
      timeCounter: 180,
      timerStr: "03:00"
    };
  },
  components: {
    LoginPopup : LoginPopup
    ,commonModal
  },
  created() {
    if(!!tokenSvc.getToken()){
      this.$store.commit("login/isLogin", true);
      this.$store.commit("login/isAuthChk", true);
      this.$router.push({ path: '/' });
    }else{
      if(!this.getLogin){
        this.$router.push({ path: '/login' });
      }
    }
  },
  mounted() {
    if (localStorage.hubwebUserId) {
      this.userId = localStorage.hubwebUserId;
    }
    this.isLogin = this.getLogin;
    this.pwd = this.getPwd;
  },
  computed: {
    ...mapGetters({
      getLogin: 'login/isLogin',
      getErrorPage: 'login/isErrorPage',
      getAuthChk: 'login/isAuthChk',
      getPwd: 'login/getPwd'
    }),
  },
  watch: {
    getLogin(data) {
      if (data != null && data != '' && data == true) {
        this.isLogin = true;
      } else {
        this.isLogin = false;
      }
    },
    getPwd(data) {
      if(data != null && data != ''){
        this.pwd = data;
      }
    }
  },
  destroyed() {
    let cont = document.querySelector(".wrap");
    cont.classList.remove("bg-wrap");
  },
  methods: {
      // 2차 인증번호 요청
      async authNum(){
        var vm = this;
        let userId =  vm.$route.params.userId;
        if(!this.isLogin){
          vm.$store.commit("login/isLogin", false);
          vm.$store.commit("login/isAuthChk", false);
          vm.$router.push({ path: '/'});
          return;
        }
          if (vm.mdn == null || vm.mdn.trim() == "" || vm.mdn.length < 11 || !vm.mdn){
            // vm.ModalOpen('modal06');
            this.row.title = '휴대폰번호 확인';
            this.row.msg1 = '휴대폰번호를 확인해 주세요.';
            this.$refs.commmonModal.alertModalOpen(this.row);
            return false;
          }
        var params = {
              "oprtrId": userId,
              "hpNo": this.mdn,
              "isLogin" : this.isLogin
          }
        try {
          const response = await api.authNum(params)
          console.log(response);
          var rsp = response.data;
          if(rsp.retCode == '0000'){
            this.timerStop(this.timer);
            this.timer = this.timerStart();
            this.row.title = '인증번호 발송';
            this.row.msg1 = '인증번호를 발송하였습니다.';
            this.$refs.commmonModal.alertModalOpen(this.row);
            // vm.ModalOpen('modal07');
            // console.log('시간 3:00 카운트 하기');
            this.isAuthNum = true;
          }else if (!this.timer) {
            this.timerStop(this.timer);
            this.timer = null;
            this.row.title = '인증번호 발송';
            this.row.msg1 = '인증번호를 발송하였습니다.';
            this.$refs.commmonModal.alertModalOpen(this.row);
            // vm.ModalOpen('modal06');
            // 실패 -> 실패 코드에 따라 실패 팝업 보여주기
            //인증시간 초과 후 “시간초과!” 문구로 변경
          }
        } catch(err) {
          this.row.title = '로그인';
          this.row.msg1 = '실패 하였습니다.';
          this.$refs.commmonModal.alertModalOpen(this.row);
        }
      },

      // 2차 인증 확인
      async ajaxAuth(){
        var vm = this;
        let userId =  vm.$route.params.userId;
        if (!vm.formCheck()){
          alert(vm.errors[0]);
          return false;
        }

        if(this.timeCounter == 0){
          this.ModalOpen('modal10');
          return false;
        }
        var params = {
            "oprtrId": userId,
            "hpNo": this.mdn,
            "chrVal": this.confirmNum,
            "isLogin": this.isLogin,
            "oprtrPw": this.pwd
        }

          //인증번호 확인
        try {
          const response = await api.confirmNum(params)
          const rsp = response.data;
          console.log("RESULT_CODE : "+rsp.retCode);
          if(rsp.retCode == '0000'){
             vm.$store.commit("login/isLogin", true);
             //var nextUrl = rsp.data.nextUrl;
             //vm.$router.push({ path: nextUrl});
             vm.$router.push({ path: '/'});
          }else if (rsp.retCode == '4008'){
            this.row.title = '휴대폰번호 확인';
            this.row.msg1 = '휴대폰번호를 확인해주세요.';
            this.row.msg2 = '아이디에 등록된 휴대폰번호로만 인증이 가능합니다.';
            this.$refs.commmonModal.alertModalOpen(this.row);
          }else if (rsp.retCode == '4009'){
            this.row.title = '인증실패';
            this.row.msg1 = '인증시간 초과되었습니다.';
            this.row.msg2 = '다시 휴대폰번호를 입력해주세요.';
            this.$refs.commmonModal.alertModalOpen(this.row);
          }else if (rsp.retCode == '4010'){
            this.row.title = '인증실패';
            this.row.msg1 = '잘못된 인증번호입니다.';
            this.row.msg2 = '5회 실패 시 로그아웃됩니다.';
            this.$refs.commmonModal.alertModalOpen(this.row);
          }else if (rsp.retCode == '4011'){
            this.row.title = '인증실패';
            this.row.msg1 = '인증번호 5회 실패하였습니다.';
            this.row.msg2 = '로그아웃되어 다시 로그인해주세요.';
            this.$refs.commmonModal.alertModalOpen(this.row);
            vm.$store.commit("login/isLogin", false);
            vm.$store.commit("login/isAuthChk", false);
            vm.$router.push({ path: '/'});
          }
        } catch(err) {
          //alert("실패 하였습니다.");
          this.row.title = '인증번호';
          this.row.msg1 = '실패 하였습니다.';
          this.$refs.commmonModal.alertModalOpen(this.row);
        }
      },
      formCheck: function() {
          this.errors = [];
          if(!this.mdn){
            this.row.title = '휴대폰번호 확인';
            this.row.msg1 = '휴대폰번호를 확인해 주세요.';
            this.$refs.commmonModal.alertModalOpen(this.row);
          } else if(!this.isAuthNum){
            this.row.title = '인증번호 입력';
            this.row.msg1 = '인증요청을 먼저 해주세요.';
            this.$refs.commmonModal.alertModalOpen(this.row);
          }else if(!this.confirmNum){
            this.row.title = '인증번호 입력';
            this.row.msg1 = '인증번호를 입력하세요.';
            this.$refs.commmonModal.alertModalOpen(this.row);
          }
          return this.errors.length == 0;
      },

    clickMenu(link){
     this.$router.push({
          path: link
      });
      },

    ModalOpen: function(target){
    this.$refs.LoginPopup.ModalOpen(target);
  },
  timerStart: function() {
  // 1초에 한번씩 start 호출
    this.timeCounter = 180;
    var interval = setInterval(() => {
    this.timeCounter--;
    //1초씩 감소
    this.timerStr = this.prettyTime();
    if (this.timeCounter <= 0)
    {
      this.timerStop(interval);
    }
    }, 1000);

    return interval;
  },

    timerStop: function(Timer)
     {
      clearInterval(Timer);
     this.timeCounter = 0;
     },

     prettyTime: function() {
       // 시간 형식으로 변환 리턴
        let time = this.timeCounter / 60;
        let minutes = parseInt(time);
        let secondes = Math.round((time - minutes) * 60);

         return (
           minutes.toString().padStart(2, "0") +
           ":"
           + secondes.toString().padStart(2, "0")
                );
     },

  }
};
</script>
