package kr.co.jinwoosi.clfd.clfd.sms.web;

import kr.co.jinwoosi.clfd.clfd.sms.service.SmsService;
import kr.co.jinwoosi.clfd.clfd.sms.vo.SmsState;
import kr.co.jinwoosi.clfd.clfd.sms.vo.SmsVo;
import kr.co.jinwoosi.clfd.clfd.user.service.ClfdUserService;
import kr.co.jinwoosi.clfd.framework.security.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SmsAuthController {

    @Autowired
    private SmsService smsService;
    @Autowired
    private ClfdUserService clfdUserService;

    @RequestMapping(value = "/clfd/sms/send.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> smsSend(HttpServletRequest request, @RequestParam("phone") String phone) {
        Map<String, String> result = new HashMap<String, String>();
        HttpSession session = request.getSession();

        SmsVo smsVo = smsService.sendSmsAuthKey(phone);
        if (smsVo.getSmsState() == SmsState.SUCCESS) {
            session.setAttribute("smsAuthKey", smsVo.getSmsAuthKey());
            session.setAttribute("phone", phone);
            result.put("result", "success");
        } else {
            result.put("result", "fail");
        }
        result.put("message", smsVo.getMessage());

        return result;
    }

    @RequestMapping(value = "/clfd/sms/check.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> smsCheck(HttpServletRequest request, @RequestParam("smsAuthKey") String smsAuthKey,
                                        @RequestParam("phone") String phone) {
        Map<String, String> result = new HashMap<String, String>();
        HttpSession session = request.getSession();
        String sessionSmsAuthKey = (String) session.getAttribute("smsAuthKey");
        String sessionPhone = (String) session.getAttribute("phone");

        if (sessionSmsAuthKey != null && sessionSmsAuthKey.equals(smsAuthKey) &&
            sessionPhone != null && sessionPhone.equals(phone)) {
            result.put("result", "success");
            result.put("message", "인증이 완료되었습니다.");
        } else if (sessionPhone == null || !sessionPhone.equals(phone)) {
            result.put("result", "fail");
            result.put("message", "인증 휴대폰 번호가 다릅니다.");
        } else {
            result.put("result", "fail");
            result.put("message", "인증 번호가 다릅니다.");
        }
        return result;
    }

    @RequestMapping(value = "/clfd/sms/find/id.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> smsFindId(HttpServletRequest request, @RequestParam("smsAuthKey") String smsAuthKey,
                                        @RequestParam("phone") String phone) {
        Map<String, Object> result = new HashMap<String, Object>();
        HttpSession session = request.getSession();
        String sessionSmsAuthKey = (String) session.getAttribute("smsAuthKey");
        String sessionPhone = (String) session.getAttribute("phone");

        if (sessionSmsAuthKey != null && sessionSmsAuthKey.equals(smsAuthKey) &&
                sessionPhone != null && sessionPhone.equals(phone)) {

            List<String> findIds = clfdUserService.findLoginIdByPhone(phone);
            if (findIds.size() == 0) {
                result.put("result", "fail");
                result.put("message", "해당 휴대폰 번호로 가입된 아이디가 없습니다.");
            } else {
                result.put("result", "success");
                result.put("data", findIds);
                result.put("message", "아이디 찾기를 완료하였습니다.");
            }

        } else if (sessionPhone == null || !sessionPhone.equals(phone)) {
            result.put("result", "fail");
            result.put("message", "인증 휴대폰 번호가 다릅니다.");
        } else {
            result.put("result", "fail");
            result.put("message", "인증 번호가 다릅니다.");
        }
        return result;
    }

    @RequestMapping(value = "/clfd/sms/find/pw.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> smsFindPw(HttpServletRequest request,
                                         @RequestParam("smsAuthKey") String smsAuthKey,
                                         @RequestParam("phone") String phone,
                                         @RequestParam("loginId") String loginId
                                         ) {
        Map<String, Object> result = new HashMap<String, Object>();
        HttpSession session = request.getSession();
        String sessionSmsAuthKey = (String) session.getAttribute("smsAuthKey");
        String sessionPhone = (String) session.getAttribute("phone");

        if (sessionSmsAuthKey != null && sessionSmsAuthKey.equals(smsAuthKey) &&
                sessionPhone != null && sessionPhone.equals(phone)) {

            Map<String, Object> pwResult = clfdUserService.findPasswordForSms(loginId, phone);
            Boolean isFind = (Boolean) pwResult.get("isFind");
            if (!isFind) {
                result.put("result", "fail");
                result.put("message", pwResult.get("message"));
            } else {
                result.put("result", "success");
                result.put("data", pwResult);
                result.put("message", pwResult.get("message"));
            }
        } else if (sessionPhone == null || !sessionPhone.equals(phone)) {
            result.put("result", "fail");
            result.put("message", "인증 휴대폰 번호가 다릅니다.");
        } else {
            result.put("result", "fail");
            result.put("message", "인증 번호가 다릅니다.");
        }
        return result;
    }

    @RequestMapping(value = "/clfd/sms/update-phone.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> smsUpdatePhone(HttpServletRequest request,
                                              @RequestParam("smsAuthKey") String smsAuthKey,
                                              @RequestParam("phone") String phone) {
        Map<String, String> result = new HashMap<String, String>();
        User loginUser = (User) request.getSession().getAttribute("user");
        HttpSession session = request.getSession();
        String sessionSmsAuthKey = (String) session.getAttribute("smsAuthKey");
        String sessionPhone = (String) session.getAttribute("phone");

        if (loginUser == null || StringUtils.isEmpty(loginUser.getUserId())) {
            result.put("result", "fail");
            result.put("message", "로그인 확인에 실패하였습니다.");
            return result;
        }

        if (sessionSmsAuthKey != null && sessionSmsAuthKey.equals(smsAuthKey) &&
                sessionPhone != null && sessionPhone.equals(phone)) {
            User updateUser = new User();
            updateUser.setUserId(loginUser.getUserId());
            updateUser.setPhone(phone);
            try {
                clfdUserService.updateUser(updateUser);
                result.put("result", "success");
                result.put("message", "휴대폰 번호를 수정하였습니다.");
            } catch (RuntimeException e) {
                result.put("result", "success");
                result.put("message", "인증은 하였지만 휴대폰 번호 수정에 실패하였습니다.");
            }
        } else if (sessionPhone == null || !sessionPhone.equals(phone)) {
            result.put("result", "fail");
            result.put("message", "인증 휴대폰 번호가 다릅니다.");
        } else {
            result.put("result", "fail");
            result.put("message", "인증 번호가 다릅니다.");
        }
        return result;
    }

}
