var userService = (function () {
    var isIdDuplicated = false;
    var isEqualPassword = false;
    var isSmsAuth = false;
    var smsAuthKey = '';

    // true이면 회원가입 진행 중, false이면 회원 가입 진행중이 아님
    var isProcessingJoin = false;

    return {
        clearIdDuplicate: function () {
            isIdDuplicated = false;
        },
        checkPasswordEquality: function () {
            if (!isEqualPassword) {
                alert("비밀번호가 일치하지 않습니다.");
            }
            return isEqualPassword;
        },
        comparePasswordEquality: function (password, passwordConfirm) {
            return isEqualPassword = password === passwordConfirm;
        },
        checkIdDuplicate: function () {
            if (!isIdDuplicated) {
                alert("아이디 중복 체크를 진행해 주세요.");
            }
            return isIdDuplicated;
        },
        checkSmsAuth: function () {
            if (!isSmsAuth) {
                alert("휴대폰 번호 인증을 진행해주세요.");
            }
            return isSmsAuth;
        },
        checkLoginId: function (id) {
            var v = commonValidation.loginIdValidation(id);
            if (!v.isValid) {
                alert(v.invalidMessage);
            }
            return v.isValid;
        },
        checkPassword: function (password) {
            var v = commonValidation.passwordValidation(password);
            if (!v.isValid) {
                alert(v.invalidMessage);
            }
            return v.isValid;
        },
        checkName: function (name, nameNick) {
            var v = commonValidation.nameValidation(name, nameNick);
            if (!v.isValid) {
                alert(v.invalidMessage);
            }
            return v.isValid;
        },
        checkGender: function (gender) {
            var v = commonValidation.genderValidation(gender);
            if (!v.isValid) {
                alert(v.invalidMessage);
            }
            return v.isValid;
        },
        checkBirth: function (birth) {
            var v = commonValidation.birthValidation(birth);
            if (!v.isValid) {
                alert(v.invalidMessage);
            }
            return v.isValid;
        },
        checkPhone: function (phone, phoneNick) {
            var v = commonValidation.phoneValidation(phone, phoneNick);
            if (!v.isValid) {
                alert(v.invalidMessage);
            }
            return v.isValid;
        },
        checkEmail: function (email) {
            var v = commonValidation.emailValidation(email);
            if (!v.isValid) {
                alert(v.invalidMessage);
            }
            return v.isValid;
        },
        checkSaupjaNo: function (saupjaNo) {
            var v = commonValidation.saupjaNoValidation(saupjaNo);
            if (!v.isValid) {
                alert(v.invalidMessage);
            }
            return v.isValid;
        },
        checkUrl: function (url) {
            if (url) {
                var v = commonValidation.urlValidation(url);
                if (!v.isValid) {
                    alert(v.invalidMessage);
                }
                return v.isValid;
            } else {
                // url은 null 허용
                return true;
            }
        },
        checkNull: function (val, type, valNick) {
            if (val == "" || val == null) {
                if (type == "select") {
                    alert(valNick + " 값을 선택해주세요");
                } else if (type == "input") {
                    alert(valNick + " 값을 입력해주세요");
                }
                return false;
            } else {
                return true;
            }
        },
        joinCheckAll: function (p) {
            return this.checkLoginId(p.loginId) &&
                this.checkIdDuplicate() &&
                this.checkPassword(p.password) &&
                this.checkPasswordEquality() &&
                this.checkName(p.name) &&
                this.checkGender(p.gender) &&
                this.checkBirth(p.birth) &&
                this.checkPhone(p.phone) &&
                this.checkSmsAuth();
        },
        joinCompanyCheckAll: function (p) {
            return this.checkLoginId(p.loginId) &&
                this.checkIdDuplicate() &&
                this.checkPassword(p.password) &&
                this.checkPasswordEquality() &&
                this.checkName(p.name) &&
                this.checkGender(p.gender) &&
                this.checkBirth(p.birth) &&
                this.checkPhone(p.phone) &&
                this.checkSmsAuth() &&

                this.checkNull(p.companyGbn, "select", "기업구분") &&
                this.checkName(p.companyNm, "기업명은") &&
                this.checkSaupjaNo(p.saupjaNo) &&
                this.checkName(p.ownerName, "대표자명은") &&
                this.checkPhone(p.telNo, "전화번호는 ") &&
                this.checkPhone(p.faxNo, "팩스번호는 ") &&
                this.checkUrl(p.companySiteUrl);
        },
        companyCheckAll: function (p) {
            return this.checkName(p.companyNm, "기업명은") &&
                this.checkSaupjaNo(p.saupjaNo) &&
                this.checkName(p.ownerName, "대표자명은") &&
                this.checkPhone(p.telNo, "전화번호는 ") &&
                this.checkPhone(p.faxNo, "팩스번호는 ") &&
                this.checkNull(p.addrM) &&
                this.checkUrl(p.companySiteUrl) ;
        },
        joinRequest: function (joinParams) {
            if (isProcessingJoin) {
                return;
            }
            isProcessingJoin = true;
            $.ajax({
                url: "/clfd/user/join/join.json",
                type: "POST",
                data: {
                    userLoginId: joinParams.loginId,
                    userPwd: joinParams.password,
                    userNm: joinParams.name,
                    gender: joinParams.gender,
                    birth: joinParams.birth,
                    phone: joinParams.phone
                },
                dataType: "json",
                success: function (res) {
                    isProcessingJoin = false;
                    if (res.result === "success") {
                        // 이메일 인증 시
                        // alert("가입 완료 되었습니다. 이메일 인증 완료 후 로그인 가능합니다.");
                        // SMS 인증 시
                        alert("가입 완료 되었습니다.");
                    } else {
                        alert(res.message);
                    }
                    location.href = "/";
                },
                error: function (request, status, error) {
                    isProcessingJoin = false;
                    console.error("code:" + request.status + "\nerror:" + error);
                }
            })
        },
        joinCompanyRequest: function (joinCompanyParams) {
            if (isProcessingJoin) {
                return;
            }
            isProcessingJoin = true;
            $.ajax({
                url: "/clfd/user/join/joinCorp.json",
                type: "POST",
                data: {
                    // 관리자정보
                    userLoginId: joinCompanyParams.loginId,
                    userPwd: joinCompanyParams.password,
                    userNm: joinCompanyParams.name,
                    gender: joinCompanyParams.gender,
                    birth: joinCompanyParams.birth,
                    phone: joinCompanyParams.phone,
                    // email: joinCompanyParams.email,

                    // 기업정보
                    companyGbn: joinCompanyParams.companyGbn,
                    companyNm: joinCompanyParams.companyNm,
                    saupjaNo: joinCompanyParams.saupjaNo,
                    ownerName: joinCompanyParams.ownerName,
                    telNo: joinCompanyParams.telNo,
                    faxNo: joinCompanyParams.faxNo,
                    companySiteUrl: joinCompanyParams.companySiteUrl,
                    addrM: joinCompanyParams.addrM,
                    addrD: joinCompanyParams.addrD,
                },
                dataType: "json",
                success: function (res) {
                    isProcessingJoin = false;
                    if (res.result === "success") {
                        // 이메일 인증 시
                        // alert("가입 완료 되었습니다. 이메일 인증 완료 후 로그인 가능합니다.");
                        // SMS 인증 시
                        alert("가입 완료 되었습니다.");
                    } else {
                        alert(res.message);
                    }
                    location.href = "/";
                },
                error: function (request, status, error) {
                    isProcessingJoin = false;
                    console.error("code:" + request.status + "\nerror:" + error);
                }
            })
        },
        idDuplicateCheckRequest: function (loginId) {
            $.ajax({
                url: "/clfd/user/join/duplicate.json",
                type: "POST",
                data: {userLoginId: loginId},
                dataType: 'json',
                success: function (res) {
                    if (res.result === "nonExist") {
                        isIdDuplicated = true;
                        alert(res.message);
                    } else {
                        isIdDuplicated = false;
                        alert(res.message);
                    }
                }
            })
        },
        changePasswordCheck: function (p) {
            return this.checkPassword(p.newPassword) &&
                this.checkPasswordEquality();
        },
        changePasswordRequest: function (p, scb) {
            if(confirm("비밀번호를 변경하시겠습니까?")) {
                $.ajax({
                    url: "/clfd/pr/pwd/update.json",
                    type: "POST",
                    data: JSON.stringify({
                        password: p.password,
                        newPassword: p.newPassword,
                    }),
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function (res) {
                        if (res.result === "success") {
                            alert(res.message);
                            scb();
                        } else {
                            alert(res.message);
                        }
                    }
                })
            }
        },
        ajaxSmsSend: function (phone) {
            $.ajax({
                url: "/clfd/sms/send.json",
                type: "POST",
                data: {phone: phone},
                dataType: 'json',
                success: function (res) {
                    if (res.result === "success") {
                        alert(res.message);
                    } else {
                        alert(res.message);
                    }
                }
            })
        },
        ajaxSmsCheck: function (_smsAuthKey, _phone, scb, ecb) {
            $.ajax({
                url: "/clfd/sms/check.json",
                type: "POST",
                data: {smsAuthKey: _smsAuthKey, phone: _phone},
                dataType: 'json',
                success: function (res) {
                    if (res.result === "success") {
                        isSmsAuth = true;
                        smsAuthKey = _smsAuthKey;
                        scb();
                        alert(res.message);
                    } else {
                        isSmsAuth = false;
                        smsAuthKey = '';
                        ecb();
                        alert(res.message);
                    }
                }
            })
        }

    }
}());

userService.myPageModule = function () {
    var that = this;
    var user = {
        loginId: undefined,
        name: undefined,
        gender: undefined,
        birth: undefined
    };
    var userPhone = {
        phone: undefined,
        newPhone: undefined
    };

    return {
        myPageRequest: function (drawPage) {
            $.ajax({
                url: "/clfd/pr/myPage.json",
                type: "GET",
                success: function (res) {
                    if (res.result === "success") {
                        setUser(res);
                        setUserPhone(res);
                        drawPage(user, userPhone);
                    } else {
                        alert(res.message);
                    }
                }
            });

            function setUser(res) {
                user.loginId = res.user.userLoginId;
                user.name = res.user.userNm;
                user.gender = res.user.gender;
                user.birth = res.user.birth;
            }

            function setUserPhone(res) {
                userPhone.phone = res.user.phone;
            }

        },
        isChangedForUpdate: function (changedUser) {
            return !this.isEqualWithEmptyCheck(user, changedUser);
        },
        isEqualWithEmptyCheck: function (value, other) {
            return _.isEqualWith(value, other, function (a, b) {
                if (_.isEmpty(a) && _.isEmpty(b)) {
                    return true;
                }
            });
        },
        myPageChangeCheckAll: function (p) {
            return that.checkName(p.name) &&
                that.checkGender(p.gender) &&
                that.checkBirth(p.birth);
        },
        myPageUpdateRequest: function (p, scb) {
            var data = {
                userLoginId: p.loginId,
                userNm: p.name,
                gender: p.gender,
                birth: p.birth
            }
            if(confirm("정보를 수정하시겠습니까?")) {
                $.ajax({
                    url: "/clfd/pr/myPage/update.json",
                    type: "POST",
                    data: data,
                    dataType: 'json',
                    success: function (res) {
                        if (res.result === "success") {
                            alert(res.message);
                            scb();
                        } else {
                            alert(res.message);
                        }
                    }
                })
            }
        },
        ajaxSmsUpdatePhone: function (_smsAuthKey, _phone, scb, ecb) {
            if (_.isEmpty(_phone)) {
                alert("변경 휴대폰 번호를 입력해주세요.");
                return;
            }
            if (_.isEmpty(_smsAuthKey)) {
                alert("인증번호를 입력해주세요.");
                return;
            }
            $.ajax({
                url: "/clfd/sms/update-phone.json",
                type: "POST",
                data: {smsAuthKey: _smsAuthKey, phone: _phone, loginId: user.loginId},
                dataType: 'json',
                success: function (res) {
                    if (res.result === "success") {
                        scb(res);
                        alert(res.message);
                    } else {
                        ecb();
                        alert(res.message);
                    }
                }
            })
        }
    }
}
