import styles from "./signup.module.scss";
import { useState } from "react";
import authApi from "../../apis/auth.api.js";
import { Redirect } from "react-router-dom";
import catchErrors from "../../utils/catchErrors.js";
const Signup = () => {
//회원정보
const [user, setUser] = useState({
userId: "",
userName:"",
userEmail: "",
userNickName: "",
userBirthday: "",
userMbnum: "",
userPassword: "",
userRePassword: ""
})
const [startTime, setStartTime] = useState("");
const [number, setNumber] = useState(null);
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(false);
//각 타입별 error 유무 state
const [mbError,setMbError] = useState(false);
const [error, setError] = useState("");
const [errorMsg, setErrorMsg] = useState({
errorId: false,
errorName: false,
errorEmail: false,
errorNickName: false,
errorBirthday: false,
errorMbnum: false,
errorPassword: false,
})
const [confirmMb, setConfirmMb] = useState(false);
//입력할때마다 state에 저장
const handleUserOnChange = (e) => {
setUser({
...user,
[e.target.name]: e.target.value
})
if (e.target.name === "userBirthday" || e.target.name === "userMbum") {
setUser({
...user,
[e.target.name]: String(e.target.value)
})
}
}
//인증번호 보내기
const handleOnClickMbnum = async (e) => {
e.preventDefault();
try {
setStartTime("");
setError("");
setLoading(true)
const phone = user.userMbnum;
const message = await authApi.confirmMbnum(phone);
if(message.isSuccess){
setMbError("보냄");
setStartTime(message.startTime);
}
} catch (error) {
console.log('error'+ error)
}finally {
setLoading(false);
}
}
//인증번호 입력
const handleOnChangeMb = (e) => {
setNumber(String(e.target.value));
}
//인증번호 검증
const handleOnClickMbConfirm = async (e) => {
e.preventDefault();
try {
setError("");
setLoading(true);
const confirmNum = {userMbnum : user.userMbnum, number : number, startTime : startTime};
const message = await authApi.confirmNum(confirmNum);
setMbError(message);
if(message === "성공"){
setConfirmMb(true);
console.log("인증완료");
}
} catch (error) {
catchErrors(error, setError);
}finally {
setLoading(false);
}
}
//비밀번호일치 여부만 클라이언트에서 확인
const validationPw = () => {
if(user.userPassword !== user.userRePassword){
return false;
}else{return true;}
}
//서버로 전송
const handleOnSummit = async (e) => {
e.preventDefault();
try {
setError("");
//처리가 될때까지 버튼(가입하기)이 안눌리게 지정
setLoading(true);
let validPw = validationPw();
if(confirmMb){
if(validPw){
const userData = user;
//서버로 전송
const error = await authApi.signup(userData);
if(error === "성공"){
setSuccess(true);
}else{
setErrorMsg(error);
alert("형식에 맞게 다시 작성해주세요");
}
}else{
throw new Error("비밀번호가 일치하지 않습니다.");
}
}else{
throw new Error("핸드폰 번호를 인증해주세요.");
}
} catch (error) {
//에러전송
catchErrors(error, setError);
} finally {
setLoading(false);
}
}
if(success){
return