<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>
                <ul class="pw-form">
                  <div>
                    <li><input type="text" 
                               ref="_phone"
                               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>
        </div>

      </div>        
        <common-modal ref="commmonModal"></common-modal>
    </div>		 

</template>

<script>
import { mapGetters } from 'vuex';
import api from '../service/api';
import { utils_mixin, chkPattern2 } from '../service/mixins';
import commonModal from "../components/commonModal";
import tokenSvc from '@/common/token-service';
import axios from 'axios';

export default {
  name: 'Params',
  mixins: [utils_mixin, chkPattern2],
  props: {
      userIds: {
          type: String,
          default : ''
      }
  },
  data: function() {
    return {
      row:{},
      errors: [],
      mdn: '',
      confirmNum: '',
      // userId: '',
      oprtrId : '',
      isAuthNum: false,
      isLogin: false,
      isAuth: false,
      pwd: '',
      text: '',
      number: '',
      timer: null,
      timeCounter: 180,
      timerStr: "03:00",
      tempList: [],
      accessToken: '',
    };
  },
  components: {    
    commonModal
  },
  created() {    
    // if(!this.getLogin){
    //   this.$router.push({ path: '/login' });
    // }        
     
  },
  mounted() {
    // if (localStorage.hubwebUserId) {
    //   this.oprtrId = localStorage.hubwebUserId;
    // }
    this.$store.commit("login/isLogin", false);

    this.isLogin = this.getLogin;    
    this.pwd = this.getPwd;    
    this.accessToken = this.getToken;
    this.oprtrId = this.userId;
    this.ajaxlogin();
  },
  computed: {
    ...mapGetters({
      getLogin: 'login/isLogin',
      getErrorPage: 'login/isErrorPage',
      getAuthChk: 'login/isAuthChk',
      getPwd: 'login/getPwd',
      getToken: 'login/getToken',      
      userId: 'login/userId',
    }),
  },
  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;
      }
    },
    getAuthChk(data){
      if (data != null && data != '' && data == true) {
        this.isAuth = true;
      } else {
        this.isAuth = false;
      }
    },
    getToken(data){      
      if (data != null && data != '') {
        this.accessToken = data;
      } else {
        this.accessToken = '';
      }
    },
    // userId(data){
    //   if (data != null && data != '') {
    //     this.oprtrId = data;
    //   } else {
    //     this.oprtrId = '';
    //   }
    // }
  },
  destroyed() {
    let cont = document.querySelector(".wrap");
    cont.classList.remove("bg-wrap");
  },
  methods: {      
      async ajaxlogin() {
        var vm = this;
        vm.errors = null; 
        var params = {
          "oprtrId": this.oprtrId,
          "accessToken": this.accessToken
        }
        
        try {          
          const response = await api.loginCheck(params);
          const rsp = response.data;
                             
          if(rsp.retCode == '0000'){            
            var accessToken = rsp.data.accessToken;
            if(vm.accessToken == accessToken){
              vm.$store.commit("login/isLogin", true);
              vm.$store.commit("login/removeToken", true);     
            }else{
              vm.$store.commit("login/isLogin", false);
              this.$router.push({ path: '/login' });  
            }
          } else {            
            vm.$store.commit("login/isLogin", false);
            this.$router.push({ path: '/login' });
          }
        } catch(err) {          
          vm.$store.commit("login/isLogin", false);
          this.$router.push({ path: '/login' });
        }
      },

      // 2차 인증번호 요청
      async authNum(){
        var vm = this;
        //let userId =  vm.$route.params.userId;
        let userId = this.oprtrId;
        this.row = {}

        if(!this.isLogin){
          vm.$store.commit("login/isLogin", false);
          vm.$store.commit("login/isAuthChk", false);
          vm.$router.push({ path: '/'});
          return false;
        }

        const hp = this.mdn;

        if(this.isNull(hp)){
          this.row.title = '로그인';
          this.row.msg1 = '휴대폰번호를 입력하세요.';
          this.$refs.commmonModal.alertModalOpen(this.row);
          return false;
        }

        if(!this.isNull(hp) && !this.isMobile(hp)){
          this.row.title = '로그인';
          this.row.msg1 = '휴대폰 번호 형식이 잘못되었습니다. 확인해 주세요.';
          this.$refs.commmonModal.alertModalOpen(this.row);
          this.$refs._phone.focus();
          return false;
        }

        var params = {
              "oprtrId": userId,
              "hpNo": this.mdn,
              "isLogin" : this.isLogin
          }
        try {
          const response = await api.authNum(params)
          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);
            this.isAuthNum = true;
          }else if(rsp.retCode == '4008'){
            this.row.title = '휴대폰번호 확인';
            this.row.msg1 = '휴대폰번호를 확인해주세요.';
            this.row.msg2 = '아이디에 등록된 휴대폰번호로만 인증이 가능합니다.';
            this.$refs.commmonModal.alertModalOpen(this.row);
          }else if(rsp.retCode == '4011'){
            this.row.title = '인증실패';
            this.row.msg1 = '잘못된 인증번호입니다.';
            this.row.msg2 = '5회 실패 시 로그아웃됩니다.';
            this.row.callFnc = 'login'
            vm.$store.commit("login/isLogin", false);
            vm.$store.commit("login/isAuthChk", false);
            this.$refs.commmonModal.alertModalOpen(this.row);
          }else if(rsp.retCode == '4022'){
            this.row.title = '인증실패';
            this.row.msg1 = '계정 잠김 잠시후 다시 시도해주세요.';
            this.row.msg2 = '로그아웃 됩니다.';
            this.row.callFnc = 'login'
            vm.$store.commit("login/isLogin", false);
            vm.$store.commit("login/isAuthChk", false);
            this.$refs.commmonModal.alertModalOpen(this.row);
          }else if (!this.timer) {
            this.timerStop(this.timer);
            this.timer = null;
            this.row.title = '인증번호 발송';
            this.row.msg1 = '인증번호를 발송하였습니다.';
            this.$refs.commmonModal.alertModalOpen(this.row);
          }
        } catch(err) {
          this.row.title = '로그인';
          this.row.msg1 = '실패 하였습니다.';
          this.$refs.commmonModal.alertModalOpen(this.row);
        }
      },

      // 2차 인증 확인
      async ajaxAuth(){
        var vm = this;        
        let userId = this.oprtrId

        this.row = {}
        if(!this.mdn){
          this.row.title = '휴대폰번호 확인';
          this.row.msg1 = '휴대폰번호를 확인해 주세요.';
          this.$refs.commmonModal.alertModalOpen(this.row);
          return false;
        }
        if(!this.isAuthNum){
          this.row.title = '인증번호 입력';
          this.row.msg1 = '인증요청을 먼저 해주세요.';
          this.$refs.commmonModal.alertModalOpen(this.row);
          return false;
        }

        if(!this.confirmNum){
          this.row.title = '인증번호 입력';
          this.row.msg1 = '인증번호를 입력하세요.';
          this.$refs.commmonModal.alertModalOpen(this.row);
          return false;
        }

        if(this.timeCounter == 0){
          // this.ModalOpen('modal10');
          this.row.title = '인증실패';
          this.row.msg1 = '인증시간 초과되었습니다.';
          this.row.msg2 = '다시 휴대폰번호를 입력해주세요.';
          this.$refs.commmonModal.alertModalOpen(this.row);
          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 response = await axios.post('/api/v1/bo/login/confirmNum', params);
          const rsp = response.data;          
          if(rsp.retCode == '0000'){
             vm.$store.commit("login/isLogin", true);
             vm.$store.commit("login/isAuthChk", true);
             vm.$store.commit("login/userId", rsp.data.userId);
             vm.$store.commit("login/userNm", rsp.data.userNm);            
             var rootUrl = rsp.data.nextUrl;
             vm.$store.commit("login/rootUrl", rsp.data.nextUrl);             
             var menuUrls = rsp.data.menuUrls;
             menuUrls.push('/');
             menuUrls.push('/login');
             menuUrls.push('/view/login/auth');
             menuUrls.push('/view/login/updatePassword');
             menuUrls.push('/view/login/resetPassword');
             menuUrls.push('/view/error/404');
             menuUrls.push('/view/error/500');
             vm.$store.commit("login/setMenuUrls", menuUrls);
             vm.$store.commit("login/saveAuthToken", rsp.data.authToken);
             //localStorage.authToken = rsp.data.authToken;
             sessionStorage.setItem('authToken', rsp.data.authToken);
             sessionStorage.setItem('refreshToken', rsp.data.refreshToken);
             //api.setToken(rsp.data.authToken);
             vm.$router.push({ path: rootUrl});
          }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) {
          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
      });
    },

    
  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")
                );
     },
    alertCalbackFnc(callFnc){
      if(callFnc === 'login'){
        this.$router.push({ path: '/'});
      }
    },    
  }
};
</script>
