package com.madeu.service.mobile.mobileuser.impl;

import com.madeu.constants.Constants;
import com.madeu.dao.mobile.mobileuser.MobileUserSqlMapDAO;
import com.madeu.service.mobile.mobileuser.MobileUserService;
import com.madeu.util.SecurityUtil;
import com.madeu.util.ValidationCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service("MobileUserService")
public class MobileUserServiceImpl implements MobileUserService {

    @Autowired
    private MobileUserSqlMapDAO mobileUserSqlMapDAO;

    /**
     * 계정정보 조회
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> selectUserAccount(
            HashMap<String, Object> paramMap) throws Exception {
        log.debug("MobileUserServiceImpl selectUserAccount START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginUserId       :"+paramMap.get("loginUserId"));

        List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();

        try{
            boolean check  = true;

            if(true == check){
                listMap = mobileUserSqlMapDAO.selectUserAccount(paramMap);

                map.put("msgCode", Constants.OK);
                map.put("success","true");
                map.put("rows",listMap);
            }
        }
        catch(Exception e){
            e.printStackTrace();
            throw e;
        }
        log.debug("MobileUserServiceImpl selectUserAccount END");
        return map;
    }

    /**
     * 이메일 계정 중복 확인
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> selectEmailCheck(
            HashMap<String, Object> paramMap) throws Exception {
        log.debug("MobileUserServiceImpl selectEmailCheck START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("email            :"+paramMap.get("email"));
        log.debug("loginType        :"+paramMap.get("loginType"));

        try{
            boolean check  = true;

            if(true == check){
                List<Map<String, Object>> listMap = mobileUserSqlMapDAO.selectEmailCheck(paramMap);

                map.put("msgCode", Constants.OK);
                map.put("success","true");
                map.put("rows",listMap);
            }
        }
        catch(Exception e){
            e.printStackTrace();
            throw e;
        }
        log.debug("MobileUserServiceImpl selectEmailCheck END");
        return map;
    }

    /**
     * 계정정보 조회
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> selectUserId(
            HashMap<String, Object> paramMap) throws Exception {
        log.debug("MobileUserServiceImpl selectUserId START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginUserId       :"+paramMap.get("loginUserId"));

        List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();

        try{
            boolean check  = true;
            listMap = mobileUserSqlMapDAO.selectUserId(paramMap);

            if(true == check){
                if(1==listMap.size()){
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "가입정보가 없습니다.");
                }
            }

            if(true == check){
                map.put("msgCode", Constants.OK);
                map.put("success","true");
                map.put("rows",listMap);
            }
        }
        catch(Exception e){
            e.printStackTrace();
            throw e;
        }
        log.debug("MobileUserServiceImpl selectUserId END");
        return map;
    }
    /**
     * 고객연락처 정보 조회
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> selectUserPhoneNumber(
            HashMap<String, Object> paramMap) throws Exception {
        log.debug("MobileUserServiceImpl selectUserPhoneNumber START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginUserId       :"+paramMap.get("loginUserId"));

        String userPhoneNumber = "";

        try{
            boolean check  = true;
            userPhoneNumber = mobileUserSqlMapDAO.selectUserPhoneNumber(paramMap);
            if(true == check){
                if(true != ValidationCheckUtil.emptyCheck(userPhoneNumber)){
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "가입정보가 없습니다.");
                }
            }

            if(true == check){
                map.put("msgCode", Constants.OK);
                map.put("success","true");
                map.put("userPhoneNumber",userPhoneNumber);
            }
        }
        catch(Exception e){
            e.printStackTrace();
            throw e;
        }
        log.debug("MobileUserServiceImpl selectUserPhoneNumber END");
        return map;
    }

    /**
     * 비밀번호 정보 수정
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public HashMap<String, Object> updatePassword(
            HashMap<String, Object> paramMap) throws Exception{
        log.debug("MobileUserServiceImpl updatePassword START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginUserId       :"+paramMap.get("loginUserId"));

        log.debug("muUserId          :"+paramMap.get("muUserId"));
        log.debug("currentPassword     :"+paramMap.get("currentPassword"));
        log.debug("newPassword         :"+paramMap.get("newPassword"));
        log.debug("confirmNewPassword  :"+paramMap.get("confirmNewPassword"));

        try{
            boolean check  = true;
            String tId = String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar c1 = Calendar.getInstance();
            String tDate = sdf.format(c1.getTime());

            String muUserId         = String.valueOf(paramMap.get("muUserId"));
            String currentPassword           = String.valueOf(paramMap.get("currentPassword"));
            String newPassword        = String.valueOf(paramMap.get("newPassword"));
            String confirmNewPassword = String.valueOf(paramMap.get("confirmNewPassword"));

            if(true != ValidationCheckUtil.emptyCheck(muUserId)){
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","고객 정보가 없습니다.");
            }

            if(true != ValidationCheckUtil.emptyCheck(currentPassword)){
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","기존 비밀번호 정보가 없습니다.");
            }

            if(true != ValidationCheckUtil.emptyCheck(newPassword)){
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","새 비밀번호 정보가 없습니다.");
            }
            else{
                if(true != ValidationCheckUtil.passwordCheck(newPassword)) {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc","비밀번호는 숫자,영문,특수문자 조합 최소 8자리 최대 20자리로 입력해야합니다.");
                }
                else if(true != ValidationCheckUtil.lengthCheck(newPassword,20)){
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc","비밀번호 정보는 20자를 넘을 수 없습니다.");
                }
            }

            if(!(newPassword).equals(confirmNewPassword)){
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","새 비밀번호와 비밀번호 확인 정보가 다릅니다.");
            }

            if(true == check){
                // 사용자 확인
                List<Map<String, Object>> userListMap = mobileUserSqlMapDAO.checkUser(paramMap);
                int userListMapSize = userListMap.size();

                if(1==userListMapSize){
                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }

            if(true == check){
                // 비밀번호 확인
                HashMap<String, Object> passwordParamMap = new HashMap<String, Object>();
                passwordParamMap.put("muUserId",paramMap.get("muUserId"));
                passwordParamMap.put("password", SecurityUtil.encryptSHA256((String) paramMap.get("currentPassword")));
                List<Map<String, Object>> passwordListMap = mobileUserSqlMapDAO.selectUserPassword(passwordParamMap);
                int totalCount = Integer.parseInt(String.valueOf(passwordListMap.get(0).get("totalCount")));

                if(totalCount==1){

                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "기존 비밀번호 정보가 올바르지 않습니다.");
                }
            }

            if(true == check){
                paramMap.put("password", SecurityUtil.encryptSHA256((String) paramMap.get("newPassword")));
                mobileUserSqlMapDAO.updatePassword(paramMap);

                map.put("msgCode", Constants.OK);
                map.put("msgDesc", "수정되었습니다.");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        log.debug("MobileUserServiceImpl updatePassword END");
        return map;
    }

    /**
     * 비밀번호 정보 수정
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public HashMap<String, Object> updateUserPassword(
            HashMap<String, Object> paramMap) throws Exception{
        log.debug("MobileUserServiceImpl updateUserPassword START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("membershipAccount          :"+paramMap.get("membershipAccount"));
        log.debug("membershipPassword         :"+paramMap.get("membershipPassword"));
        log.debug("passwordCheck              :"+paramMap.get("passwordCheck"));
        log.debug("userPhoneNumber            :"+paramMap.get("userPhoneNumber"));

        try{
            boolean check  = true;
            String tId = String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar c1 = Calendar.getInstance();
            String tDate = sdf.format(c1.getTime());

            String membershipAccount        = String.valueOf(paramMap.get("membershipAccount"));
            String membershipPassword       = String.valueOf(paramMap.get("membershipPassword"));
            String passwordCheck            = String.valueOf(paramMap.get("passwordCheck"));
            String userPhoneNumber          = String.valueOf(paramMap.get("userPhoneNumber"));


            if(true != ValidationCheckUtil.emptyCheck(membershipPassword)){
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","새 비밀번호 정보가 없습니다.");
            }
            else{
                if(true != ValidationCheckUtil.passwordCheck(membershipPassword)) {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc","비밀번호는 숫자,영문,특수문자 조합 최소 8자리 최대 20자리로 입력해야합니다.");
                }
                else if(true != ValidationCheckUtil.lengthCheck(membershipPassword,20)){
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc","비밀번호 정보는 20자를 넘을 수 없습니다.");
                }
            }

            if(!(membershipPassword).equals(passwordCheck)){
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","비밀번호와 비밀번호 확인 정보가 다릅니다.");
            }

            if(true == check){
                // 사용자 확인
                List<Map<String, Object>> userListMap = mobileUserSqlMapDAO.checkUser2(paramMap);
                int userListMapSize = userListMap.size();

                if(1==userListMapSize){
                    paramMap.put("modId", userListMap.get(0).get("muUserId"));
                    paramMap.put("userName", userListMap.get(0).get("userName"));
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }

            if(true == check){
                paramMap.put("password", SecurityUtil.encryptSHA256((String) paramMap.get("membershipPassword")));
                paramMap.put("phoneNumber", userPhoneNumber);
                mobileUserSqlMapDAO.updateUserPassword(paramMap);
                map.put("rows", mobileUserSqlMapDAO.selectUserId(paramMap));
                map.put("msgCode", Constants.OK);
                map.put("msgDesc", "수정되었습니다.");

            }
        }
        catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        log.debug("MobileUserServiceImpl updatePassword END");
        return map;
    }

    /**
     * 이메일 정보 수정
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public HashMap<String, Object> updateEmail(
            HashMap<String, Object> paramMap) throws Exception{
        log.debug("MobileUserServiceImpl updatePassword START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginUserId       :"+paramMap.get("loginUserId"));

        log.debug("muUserId          :"+paramMap.get("muUserId"));
        log.debug("email             :"+paramMap.get("email"));
        log.debug("phoneNumber       :"+paramMap.get("phoneNumber"));
        log.debug("authNumber        :"+paramMap.get("authNumber"));

        try{
            boolean check  = true;
            String tId = String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar c1 = Calendar.getInstance();
            String tDate = sdf.format(c1.getTime());

            String muUserId         = String.valueOf(paramMap.get("muUserId"));
            String email            = String.valueOf(paramMap.get("email"));
            String phoneNumber      = String.valueOf(paramMap.get("phoneNumber"));
            String authNumber       = String.valueOf(paramMap.get("authNumber"));

            if(true != ValidationCheckUtil.emptyCheck(muUserId)){
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","고객 정보가 없습니다.");
            }
//            if (ValidationCheckUtil.emptyCheck(email) && !ValidationCheckUtil.emailCheck(email)) {
//                check = false;
//                map.put("msgCode", Constants.FAIL);
//                map.put("msgDesc","유효하지 않은 이메일 형식입니다.");
//            }
            if(true != ValidationCheckUtil.emptyCheck(phoneNumber)){
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","고객 연락처 정보가 없습니다.");
            }
            if(true != ValidationCheckUtil.emptyCheck(authNumber)){
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","인증번호 정보가 없습니다.");
            }

//            if(true == check){
//                // 사용자 확인
//                List<Map<String, Object>> userListMap = mobileUserSqlMapDAO.checkUser(paramMap);
//                int userListMapSize = userListMap.size();
//                if(1==userListMapSize){
//                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
//                    String userPhoneNumber = String.valueOf(userListMap.get(0).get("phoneNumber"));
//                    if(!userPhoneNumber.equals(phoneNumber)){
//                        check = false;
//                        map.put("msgCode", Constants.FAIL);
//                        map.put("msgDesc", "등록된 휴대폰번호가 아닙니다.");
//                    }
//                }else {
//                    check = false;
//                    map.put("msgCode", Constants.FAIL);
//                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
//                }
//            }

            if(true == check){
                mobileUserSqlMapDAO.updateEmail(paramMap);

                map.put("msgCode", Constants.OK);
                map.put("msgDesc", "수정되었습니다.");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        log.debug("WebMemberServiceImpl updateEmail END");
        return map;
    }

}
